commit 5f53c811bf3d354f81842b8d2e98f2b58ef86b8d Author: Damillora Date: Sun Feb 9 14:13:33 2020 +0700 BlueFire source code diff --git a/api/.gitignore b/api/.gitignore new file mode 100644 index 0000000..d740c49 --- /dev/null +++ b/api/.gitignore @@ -0,0 +1,9 @@ +.DS_Store + +application/cache/* +!application/cache/index.html +!application/cache/.htaccess + +application/logs/* +!application/logs/index.html +!application/logs/.htaccess \ No newline at end of file diff --git a/api/.htaccess b/api/.htaccess new file mode 100644 index 0000000..d554ee6 --- /dev/null +++ b/api/.htaccess @@ -0,0 +1,3 @@ +Header set Access-Control-Allow-Origin "*" +Header set Access-Control-Allow-Methods "*" +Header set Access-Control-Allow-Headers "*" diff --git a/api/.travis.yml b/api/.travis.yml new file mode 100644 index 0000000..b3456f3 --- /dev/null +++ b/api/.travis.yml @@ -0,0 +1,4 @@ +branches: + except: + - 2.1-stable + - master \ No newline at end of file diff --git a/api/application/.htaccess b/api/application/.htaccess new file mode 100644 index 0000000..14249c5 --- /dev/null +++ b/api/application/.htaccess @@ -0,0 +1 @@ +Deny from all \ No newline at end of file diff --git a/api/application/cache/.htaccess b/api/application/cache/.htaccess new file mode 100644 index 0000000..3418e55 --- /dev/null +++ b/api/application/cache/.htaccess @@ -0,0 +1 @@ +deny from all \ No newline at end of file diff --git a/api/application/cache/index.html b/api/application/cache/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/cache/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/config/autoload.php b/api/application/config/autoload.php new file mode 100644 index 0000000..17c5092 --- /dev/null +++ b/api/application/config/autoload.php @@ -0,0 +1,116 @@ + '', + 'xhtml1-strict' => '', + 'xhtml1-trans' => '', + 'xhtml1-frame' => '', + 'html5' => '', + 'html4-strict' => '', + 'html4-trans' => '', + 'html4-frame' => '' + ); + +/* End of file doctypes.php */ +/* Location: ./application/config/doctypes.php */ \ No newline at end of file diff --git a/api/application/config/foreign_chars.php b/api/application/config/foreign_chars.php new file mode 100644 index 0000000..14b0d73 --- /dev/null +++ b/api/application/config/foreign_chars.php @@ -0,0 +1,64 @@ + 'ae', + '/ö|œ/' => 'oe', + '/ü/' => 'ue', + '/Ä/' => 'Ae', + '/Ü/' => 'Ue', + '/Ö/' => 'Oe', + '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', + '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', + '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', + '/ç|ć|ĉ|ċ|č/' => 'c', + '/Ð|Ď|Đ/' => 'D', + '/ð|ď|đ/' => 'd', + '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', + '/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e', + '/Ĝ|Ğ|Ġ|Ģ/' => 'G', + '/ĝ|ğ|ġ|ģ/' => 'g', + '/Ĥ|Ħ/' => 'H', + '/ĥ|ħ/' => 'h', + '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', + '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', + '/Ĵ/' => 'J', + '/ĵ/' => 'j', + '/Ķ/' => 'K', + '/ķ/' => 'k', + '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', + '/ĺ|ļ|ľ|ŀ|ł/' => 'l', + '/Ñ|Ń|Ņ|Ň/' => 'N', + '/ñ|ń|ņ|ň|ʼn/' => 'n', + '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', + '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', + '/Ŕ|Ŗ|Ř/' => 'R', + '/ŕ|ŗ|ř/' => 'r', + '/Ś|Ŝ|Ş|Š/' => 'S', + '/ś|ŝ|ş|š|ſ/' => 's', + '/Ţ|Ť|Ŧ/' => 'T', + '/ţ|ť|ŧ/' => 't', + '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', + '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', + '/Ý|Ÿ|Ŷ/' => 'Y', + '/ý|ÿ|ŷ/' => 'y', + '/Ŵ/' => 'W', + '/ŵ/' => 'w', + '/Ź|Ż|Ž/' => 'Z', + '/ź|ż|ž/' => 'z', + '/Æ|Ǽ/' => 'AE', + '/ß/'=> 'ss', + '/IJ/' => 'IJ', + '/ij/' => 'ij', + '/Œ/' => 'OE', + '/ƒ/' => 'f' +); + +/* End of file foreign_chars.php */ +/* Location: ./application/config/foreign_chars.php */ \ No newline at end of file diff --git a/api/application/config/hooks.php b/api/application/config/hooks.php new file mode 100644 index 0000000..a4ad2be --- /dev/null +++ b/api/application/config/hooks.php @@ -0,0 +1,16 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/config/migration.php b/api/application/config/migration.php new file mode 100644 index 0000000..df42a3c --- /dev/null +++ b/api/application/config/migration.php @@ -0,0 +1,41 @@ +migration->latest() this is the version that schema will +| be upgraded / downgraded to. +| +*/ +$config['migration_version'] = 0; + + +/* +|-------------------------------------------------------------------------- +| Migrations Path +|-------------------------------------------------------------------------- +| +| Path to your migrations folder. +| Typically, it will be within your application path. +| Also, writing permission is required within the migrations path. +| +*/ +$config['migration_path'] = APPPATH . 'migrations/'; + + +/* End of file migration.php */ +/* Location: ./application/config/migration.php */ \ No newline at end of file diff --git a/api/application/config/mimes.php b/api/application/config/mimes.php new file mode 100644 index 0000000..100f7d4 --- /dev/null +++ b/api/application/config/mimes.php @@ -0,0 +1,106 @@ + 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'), + 'bin' => 'application/macbinary', + 'dms' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'exe' => array('application/octet-stream', 'application/x-msdownload'), + 'class' => 'application/octet-stream', + 'psd' => 'application/x-photoshop', + 'so' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => array('application/pdf', 'application/x-download'), + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'), + 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'), + 'wbxml' => 'application/wbxml', + 'wmlc' => 'application/wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'gz' => 'application/x-gzip', + 'php' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => 'application/x-javascript', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => array('application/x-tar', 'application/x-gzip-compressed'), + 'xhtml' => 'application/xhtml+xml', + 'xht' => 'application/xhtml+xml', + 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'), + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mpga' => 'audio/mpeg', + 'mp2' => 'audio/mpeg', + 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'), + 'aif' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'rv' => 'video/vnd.rn-realvideo', + 'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'), + 'bmp' => array('image/bmp', 'image/x-windows-bmp'), + 'gif' => 'image/gif', + 'jpeg' => array('image/jpeg', 'image/pjpeg'), + 'jpg' => array('image/jpeg', 'image/pjpeg'), + 'jpe' => array('image/jpeg', 'image/pjpeg'), + 'png' => array('image/png', 'image/x-png'), + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'txt' => 'text/plain', + 'text' => 'text/plain', + 'log' => array('text/plain', 'text/x-log'), + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'doc' => 'application/msword', + 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'), + 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'), + 'word' => array('application/msword', 'application/octet-stream'), + 'xl' => 'application/excel', + 'eml' => 'message/rfc822', + 'json' => array('application/json', 'text/json') + ); + + +/* End of file mimes.php */ +/* Location: ./application/config/mimes.php */ diff --git a/api/application/config/profiler.php b/api/application/config/profiler.php new file mode 100644 index 0000000..f8a5b1a --- /dev/null +++ b/api/application/config/profiler.php @@ -0,0 +1,17 @@ + array('grin.gif', '19', '19', 'grin'), + ':lol:' => array('lol.gif', '19', '19', 'LOL'), + ':cheese:' => array('cheese.gif', '19', '19', 'cheese'), + ':)' => array('smile.gif', '19', '19', 'smile'), + ';-)' => array('wink.gif', '19', '19', 'wink'), + ';)' => array('wink.gif', '19', '19', 'wink'), + ':smirk:' => array('smirk.gif', '19', '19', 'smirk'), + ':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'), + ':-S' => array('confused.gif', '19', '19', 'confused'), + ':wow:' => array('surprise.gif', '19', '19', 'surprised'), + ':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'), + ':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'), + '%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'), + ';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'), + ':P' => array('raspberry.gif', '19', '19', 'raspberry'), + ':blank:' => array('blank.gif', '19', '19', 'blank stare'), + ':long:' => array('longface.gif', '19', '19', 'long face'), + ':ohh:' => array('ohh.gif', '19', '19', 'ohh'), + ':grrr:' => array('grrr.gif', '19', '19', 'grrr'), + ':gulp:' => array('gulp.gif', '19', '19', 'gulp'), + '8-/' => array('ohoh.gif', '19', '19', 'oh oh'), + ':down:' => array('downer.gif', '19', '19', 'downer'), + ':red:' => array('embarrassed.gif', '19', '19', 'red face'), + ':sick:' => array('sick.gif', '19', '19', 'sick'), + ':shut:' => array('shuteye.gif', '19', '19', 'shut eye'), + ':-/' => array('hmm.gif', '19', '19', 'hmmm'), + '>:(' => array('mad.gif', '19', '19', 'mad'), + ':mad:' => array('mad.gif', '19', '19', 'mad'), + '>:-(' => array('angry.gif', '19', '19', 'angry'), + ':angry:' => array('angry.gif', '19', '19', 'angry'), + ':zip:' => array('zip.gif', '19', '19', 'zipper'), + ':kiss:' => array('kiss.gif', '19', '19', 'kiss'), + ':ahhh:' => array('shock.gif', '19', '19', 'shock'), + ':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'), + ':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'), + ':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'), + ':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'), + ':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'), + ':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'), + ':vampire:' => array('vampire.gif', '19', '19', 'vampire'), + ':snake:' => array('snake.gif', '19', '19', 'snake'), + ':exclaim:' => array('exclaim.gif', '19', '19', 'excaim'), + ':question:' => array('question.gif', '19', '19', 'question') // no comma after last item + + ); + +/* End of file smileys.php */ +/* Location: ./application/config/smileys.php */ \ No newline at end of file diff --git a/api/application/config/user_agents.php b/api/application/config/user_agents.php new file mode 100644 index 0000000..e2d3c3a --- /dev/null +++ b/api/application/config/user_agents.php @@ -0,0 +1,178 @@ + 'Windows Longhorn', + 'windows nt 5.2' => 'Windows 2003', + 'windows nt 5.0' => 'Windows 2000', + 'windows nt 5.1' => 'Windows XP', + 'windows nt 4.0' => 'Windows NT 4.0', + 'winnt4.0' => 'Windows NT 4.0', + 'winnt 4.0' => 'Windows NT', + 'winnt' => 'Windows NT', + 'windows 98' => 'Windows 98', + 'win98' => 'Windows 98', + 'windows 95' => 'Windows 95', + 'win95' => 'Windows 95', + 'windows' => 'Unknown Windows OS', + 'os x' => 'Mac OS X', + 'ppc mac' => 'Power PC Mac', + 'freebsd' => 'FreeBSD', + 'ppc' => 'Macintosh', + 'linux' => 'Linux', + 'debian' => 'Debian', + 'sunos' => 'Sun Solaris', + 'beos' => 'BeOS', + 'apachebench' => 'ApacheBench', + 'aix' => 'AIX', + 'irix' => 'Irix', + 'osf' => 'DEC OSF', + 'hp-ux' => 'HP-UX', + 'netbsd' => 'NetBSD', + 'bsdi' => 'BSDi', + 'openbsd' => 'OpenBSD', + 'gnu' => 'GNU/Linux', + 'unix' => 'Unknown Unix OS' + ); + + +// The order of this array should NOT be changed. Many browsers return +// multiple browser types so we want to identify the sub-type first. +$browsers = array( + 'Flock' => 'Flock', + 'Chrome' => 'Chrome', + 'Opera' => 'Opera', + 'MSIE' => 'Internet Explorer', + 'Internet Explorer' => 'Internet Explorer', + 'Shiira' => 'Shiira', + 'Firefox' => 'Firefox', + 'Chimera' => 'Chimera', + 'Phoenix' => 'Phoenix', + 'Firebird' => 'Firebird', + 'Camino' => 'Camino', + 'Netscape' => 'Netscape', + 'OmniWeb' => 'OmniWeb', + 'Safari' => 'Safari', + 'Mozilla' => 'Mozilla', + 'Konqueror' => 'Konqueror', + 'icab' => 'iCab', + 'Lynx' => 'Lynx', + 'Links' => 'Links', + 'hotjava' => 'HotJava', + 'amaya' => 'Amaya', + 'IBrowse' => 'IBrowse' + ); + +$mobiles = array( + // legacy array, old values commented out + 'mobileexplorer' => 'Mobile Explorer', +// 'openwave' => 'Open Wave', +// 'opera mini' => 'Opera Mini', +// 'operamini' => 'Opera Mini', +// 'elaine' => 'Palm', + 'palmsource' => 'Palm', +// 'digital paths' => 'Palm', +// 'avantgo' => 'Avantgo', +// 'xiino' => 'Xiino', + 'palmscape' => 'Palmscape', +// 'nokia' => 'Nokia', +// 'ericsson' => 'Ericsson', +// 'blackberry' => 'BlackBerry', +// 'motorola' => 'Motorola' + + // Phones and Manufacturers + 'motorola' => "Motorola", + 'nokia' => "Nokia", + 'palm' => "Palm", + 'iphone' => "Apple iPhone", + 'ipad' => "iPad", + 'ipod' => "Apple iPod Touch", + 'sony' => "Sony Ericsson", + 'ericsson' => "Sony Ericsson", + 'blackberry' => "BlackBerry", + 'cocoon' => "O2 Cocoon", + 'blazer' => "Treo", + 'lg' => "LG", + 'amoi' => "Amoi", + 'xda' => "XDA", + 'mda' => "MDA", + 'vario' => "Vario", + 'htc' => "HTC", + 'samsung' => "Samsung", + 'sharp' => "Sharp", + 'sie-' => "Siemens", + 'alcatel' => "Alcatel", + 'benq' => "BenQ", + 'ipaq' => "HP iPaq", + 'mot-' => "Motorola", + 'playstation portable' => "PlayStation Portable", + 'hiptop' => "Danger Hiptop", + 'nec-' => "NEC", + 'panasonic' => "Panasonic", + 'philips' => "Philips", + 'sagem' => "Sagem", + 'sanyo' => "Sanyo", + 'spv' => "SPV", + 'zte' => "ZTE", + 'sendo' => "Sendo", + + // Operating Systems + 'symbian' => "Symbian", + 'SymbianOS' => "SymbianOS", + 'elaine' => "Palm", + 'palm' => "Palm", + 'series60' => "Symbian S60", + 'windows ce' => "Windows CE", + + // Browsers + 'obigo' => "Obigo", + 'netfront' => "Netfront Browser", + 'openwave' => "Openwave Browser", + 'mobilexplorer' => "Mobile Explorer", + 'operamini' => "Opera Mini", + 'opera mini' => "Opera Mini", + + // Other + 'digital paths' => "Digital Paths", + 'avantgo' => "AvantGo", + 'xiino' => "Xiino", + 'novarra' => "Novarra Transcoder", + 'vodafone' => "Vodafone", + 'docomo' => "NTT DoCoMo", + 'o2' => "O2", + + // Fallback + 'mobile' => "Generic Mobile", + 'wireless' => "Generic Mobile", + 'j2me' => "Generic Mobile", + 'midp' => "Generic Mobile", + 'cldc' => "Generic Mobile", + 'up.link' => "Generic Mobile", + 'up.browser' => "Generic Mobile", + 'smartphone' => "Generic Mobile", + 'cellphone' => "Generic Mobile" + ); + +// There are hundreds of bots but these are the most common. +$robots = array( + 'googlebot' => 'Googlebot', + 'msnbot' => 'MSNBot', + 'slurp' => 'Inktomi Slurp', + 'yahoo' => 'Yahoo', + 'askjeeves' => 'AskJeeves', + 'fastcrawler' => 'FastCrawler', + 'infoseek' => 'InfoSeek Robot 1.0', + 'lycos' => 'Lycos' + ); + +/* End of file user_agents.php */ +/* Location: ./application/config/user_agents.php */ \ No newline at end of file diff --git a/api/application/controllers/assignment.php b/api/application/controllers/assignment.php new file mode 100644 index 0000000..00b3697 --- /dev/null +++ b/api/application/controllers/assignment.php @@ -0,0 +1,41 @@ +sp('sp_getAssignments', array(), 'LOCALDB')->result(); + return $this->load->view('json_view', array('json' => $res)); + } + public function insert(){ + $post = $this->input->post(); + $filename = date("Y").'-'.date("m").'-'.$post['Filename']; + $res = $this->sp('sp_insertAssignments', array( + 'AssignmentName' => $post['AssignmentName'], + 'AssignmentPath' => "storage/".$filename, + ), 'LOCALDB')->result(); + if(count($res)==0){ + if (!file_exists('storage')) mkdir('storage'); + foreach ($_FILES as $file) file_put_contents("storage/".$filename, fopen($file["tmp_name"], "r")); + } + return $this->load->view('json_view', array('json' => array('success' => true))); + } + public function getByID(){ + $post = $this->input->post(); + $res = $this->sp('sp_getAssignmentByID', array( + 'AssignmentID' => $post['id'], + ), 'LOCALDB')->result()[0]; + return $this->load->view('json_view', array('json' => $res)); + } + public function update(){ + $post = $this->input->post(); + $filename = date("Y").'-'.date("m").'-'.$post['Filename']; + $res = $this->sp('sp_updateAssignments', array( + 'AssignmentID' => $post['AssignmentID'], + 'AssignmentName' => $post['AssignmentName'], + 'AssignmentPath' => "storage/".$filename, + ), 'LOCALDB')->result(); + if(count($res)==0){ + if (!file_exists('storage')) mkdir('storage'); + foreach ($_FILES as $file) file_put_contents("storage/".$filename, fopen($file["tmp_name"], "r")); + } + return $this->load->view('json_view', array('json' => array('success' => true))); + } +} \ No newline at end of file diff --git a/api/application/controllers/index.html b/api/application/controllers/index.html new file mode 100644 index 0000000..065d2da --- /dev/null +++ b/api/application/controllers/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/controllers/training.php b/api/application/controllers/training.php new file mode 100644 index 0000000..e4f24f1 --- /dev/null +++ b/api/application/controllers/training.php @@ -0,0 +1,249 @@ + +sp('sp_denyApplicationEntry', array( + 'applicationID' => $id + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view',array('json' => 'success')); + } + + public function acceptEntry(){ + $id = $_POST['id']; + $result = $this->sp('sp_hiredApplicationEntry', array( + 'applicationID' => $id + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view',array('json' => 'success')); + } + + public function getEntries(){ + // $id = $_POST['id']; + $res = $this->sp('sp_getAllEntry', array( +// 'userId'=>$id + ), 'BLUEFIREDATABASE')->result(); + $data = array( + 'json' => $res, + ); + return $this->load->view('json_view', $data); + } + + public function getBookmark(){ + $id = $_POST['id']; + $res = $this->sp('sp_getBookmark', array( + 'userId'=>$id + ), 'BLUEFIREDATABASE')->result(); + $data = array( + 'json' => $res, + ); + return $this->load->view('json_view', $data); + } + + public function insertBookmark(){ + $id = $_POST['id']; + $userId = $_POST['userId']; + + $result = $this->sp('sp_insertBookmark', array( + 'userId' => $userId, + 'jobId' => $id + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view',array('json' => 'success')); + } + + public function deleteBookmark(){ + $id = $_POST['id']; + $result = $this->sp('sp_deleteBookmark', array( + 'bookmarkID' => $id + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view',array('json' => 'success')); + } + + public function getAllCountry(){ + $res = $this->sp('sp_getAllCountry',array(),'BLUEFIREDATABASE')->result(); + $data = array( + 'json'=>$res, + ); + return $this->load->view('json_view',$data); + } + + public function getAllCity(){ + $res = $this->sp('sp_getAllCity', array(), 'BLUEFIREDATABASE')->result(); + $data = array( + 'json' => $res, + ); + return $this->load->view('json_view', $data); + } + + public function uploadFile(){ + if(!file_exists('storage')) mkdir('storage'); + $filename = null; + foreach($_FILES as $file){ + file_put_contents('storage/'.$file["name"], fopen($file["tmp_name"],"r")); + $filename = $file["name"]; + } + return $this->load->view('json_view', array('json' => $filename)); + } + + public function updateJob(){ + $jobId = $_POST['jobId']; + $name = $_POST['jobName']; + $cityId = $_POST['cityId']; + $deadline = $_POST['deadline']; + $jobLevel = $_POST['jobLevel']; + $jobDesc = $_POST['jobDesc']; + + $res = $this->sp('sp_updateJob',array( + 'jobId'=>$jobId, + 'name'=>$name, + 'cityId'=>$cityId, + 'jobLevel'=>$jobLevel, + 'deadline'=>$deadline, + 'description'=>$jobDesc + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view',array('json'=>$res)); + } + + public function getListJob(){ + $res = $this->sp('sp_getListJob', array(), 'BLUEFIREDATABASE')->result(); + $data = array( + 'json' => $res, + ); + return $this->load->view('json_view', $data); + } + + public function getJob(){ + $id = (int)$_GET['jobId']; + $res = $this->sp('sp_getJob', array( + 'jobId' => $id + ), 'BLUEFIREDATABASE')->result(); + $data = array( + 'json' => $res, + ); + return $this->load->view('json_view', $data); + } + + public function deleteJob(){ + $id = $_POST['id']; + $result = $this->sp('sp_deleteJob', array( + 'jobId' => $id + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view',array('json' => 'success')); + } + + public function getAllJob(){ + $res = $this->sp('sp_getAllJob', array(), 'BLUEFIREDATABASE')->result(); + $data = array( + 'json' => $res, + ); + return $this->load->view('json_view', $data); + } + + public function insertJob(){ + $name = $_POST['jobName']; + $cityId = $_POST['cityId']; + $deadline = $_POST['deadline']; + $jobLevel = $_POST['jobLevel']; + $jobDesc = $_POST['jobDesc']; + + $res = $this->sp('sp_insertJob',array( + 'name'=>$name, + 'cityId'=>$cityId, + 'jobLevel'=>$jobLevel, + 'deadline'=>$deadline, + 'description'=>$jobDesc, + ),'BLUEFIREDATABASE')->row(); + var_dump(sqlsrv_errors()); + return $this->load->view('json_view',array('json'=>$res)); + } + + public function submitApplication(){ + $userId = $_POST['userId']; + $jobId = $_POST['jobId']; + $email = $_POST['email']; + $company = $_POST['company']; + $position = $_POST['position']; + $university = $_POST['university']; + $cv = $_POST['cv']; + $portofolio = $_POST['portofolio']; + + $res = $this->sp('sp_insertEntry',array( + 'userId' => $userId, + 'jobId'=> $jobId, + 'email'=> $email, + 'prevCompanyName'=> $company, + 'prevPosition'=> $position, + 'universityName'=> $university, + 'cvLink'=> $cv, + 'portofolioLink'=> $portofolio, + + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view', array('json'=>$res)); + } + + public function insertUser(){ + $password = $_POST['password']; + $pass = password_hash($password, PASSWORD_DEFAULT); + $name = $_POST['name']; + $DOB = $_POST['dob']; + $gender = $_POST['gender']; + $address = $_POST['address']; + $phone = $_POST['phone']; + $email = $_POST['email']; + $res = $this->sp('sp_insertUser',array( + 'password' =>$pass, + 'name' =>$name, + 'DOB' =>$DOB, + 'gender' =>$gender, + 'address' =>$address, + 'phone' => $phone, + 'email' =>$email + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view', array('json'=>$res)); + } + + public function insertAdmin(){ + $password = $_POST['password']; + $pass = password_hash($password, PASSWORD_DEFAULT); + $name = $_POST['name']; + $res = $this->sp('sp_insertAdmin',array( + 'password' =>$pass, + 'name' =>$name + ),'BLUEFIREDATABASE')->row(); + return $this->load->view('json_view', array('json'=>$res)); + } + + public function loginUser(){ + $password = $_POST['Password']; + $name = $_POST['Name']; + $res = $this->sp('sp_loginUser',array( + 'name' =>$name, + ),'BLUEFIREDATABASE')->result(); + for ($i = 0;$iPassword)){ + $data = array( + 'json' =>$res, + ); + return $this->load->view('json_view', $data); + }; + } + }; + } + public function loginAdmin(){ + $password = $_POST['Password']; + $name = $_POST['Name']; + $res = $this->sp('sp_loginAdmin',array( + 'name' =>$name, + ),'BLUEFIREDATABASE')->result(); + for ($i = 0;$iAdminPassword)){ + $data = array( + 'json' =>$res, + ); + return $this->load->view('json_view', $data); + }; + } + }; + } +} diff --git a/api/application/controllers/welcome.php b/api/application/controllers/welcome.php new file mode 100644 index 0000000..21bef43 --- /dev/null +++ b/api/application/controllers/welcome.php @@ -0,0 +1,27 @@ + + * @see http://codeigniter.com/user_guide/general/urls.html + */ + public function index() + { + $this->load->view('welcome_message'); + } +} + +/* End of file welcome.php */ +/* Location: ./application/controllers/welcome.php */ \ No newline at end of file diff --git a/api/application/core/BM_Controller.php b/api/application/core/BM_Controller.php new file mode 100644 index 0000000..40c663c --- /dev/null +++ b/api/application/core/BM_Controller.php @@ -0,0 +1,25 @@ +load->database($db, TRUE); + + $param_name = array(); + $param_list = array(); + foreach($array as $key => $val) + { + $param_name[] = '@' . $key . '=?'; + $param_list[] = $val; + } + + $sp_name .= ' '. implode(', ', $param_name); + + $Data = $DBS->query($sp_name, $param_list); + $this->db->close(); + return $Data; + } +} + +/* End of file BM_Controller.php */ \ No newline at end of file diff --git a/api/application/core/index.html b/api/application/core/index.html new file mode 100644 index 0000000..065d2da --- /dev/null +++ b/api/application/core/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/errors/error_404.php b/api/application/errors/error_404.php new file mode 100644 index 0000000..792726a --- /dev/null +++ b/api/application/errors/error_404.php @@ -0,0 +1,62 @@ + + + +404 Page Not Found + + + +
+

+ +
+ + \ No newline at end of file diff --git a/api/application/errors/error_db.php b/api/application/errors/error_db.php new file mode 100644 index 0000000..b396cda --- /dev/null +++ b/api/application/errors/error_db.php @@ -0,0 +1,62 @@ + + + +Database Error + + + +
+

+ +
+ + \ No newline at end of file diff --git a/api/application/errors/error_general.php b/api/application/errors/error_general.php new file mode 100644 index 0000000..fd63ce2 --- /dev/null +++ b/api/application/errors/error_general.php @@ -0,0 +1,62 @@ + + + +Error + + + +
+

+ +
+ + \ No newline at end of file diff --git a/api/application/errors/error_php.php b/api/application/errors/error_php.php new file mode 100644 index 0000000..f085c20 --- /dev/null +++ b/api/application/errors/error_php.php @@ -0,0 +1,10 @@ +
+ +

A PHP Error was encountered

+ +

Severity:

+

Message:

+

Filename:

+

Line Number:

+ +
\ No newline at end of file diff --git a/api/application/errors/index.html b/api/application/errors/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/errors/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/helpers/index.html b/api/application/helpers/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/helpers/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/hooks/index.html b/api/application/hooks/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/hooks/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/index.html b/api/application/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/language/english/index.html b/api/application/language/english/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/language/english/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/libraries/index.html b/api/application/libraries/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/libraries/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/logs/index.html b/api/application/logs/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/logs/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/models/index.html b/api/application/models/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/models/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/third_party/index.html b/api/application/third_party/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/third_party/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/views/index.html b/api/application/views/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/application/views/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/application/views/json_view.php b/api/application/views/json_view.php new file mode 100644 index 0000000..a846995 --- /dev/null +++ b/api/application/views/json_view.php @@ -0,0 +1,3 @@ + + + + + Welcome to CodeIgniter + + + + + +
+

Welcome to CodeIgniter!

+ +
+

The page you are looking at is being generated dynamically by CodeIgniter.

+ +

If you would like to edit this page you'll find it located at:

+ application/views/welcome_message.php + +

The corresponding controller for this page is found at:

+ application/controllers/welcome.php + +

If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.

+
+ + +
+ + + \ No newline at end of file diff --git a/api/index.php b/api/index.php new file mode 100644 index 0000000..f253ae3 --- /dev/null +++ b/api/index.php @@ -0,0 +1,205 @@ +load->view('json_view', array('json' => $filename)); + } \ No newline at end of file diff --git a/api/storage/assetlatihan.txt b/api/storage/assetlatihan.txt new file mode 100644 index 0000000..2954d5a --- /dev/null +++ b/api/storage/assetlatihan.txt @@ -0,0 +1,57 @@ + + + \ No newline at end of file diff --git a/api/storage/snippet.txt b/api/storage/snippet.txt new file mode 100644 index 0000000..dde03f5 --- /dev/null +++ b/api/storage/snippet.txt @@ -0,0 +1,39 @@ +--JS +var sv; +var subView = { + title : 'PengenPulang - Binusmaya', + require : 'PengenPulang', + rel : 'wrapper', + onLoaded : function(){ + window.document.title = this.title; + sv = this; + $(".alert").hide(); + $('#photoInput').on('change',function(){ + var form_data = new FormData(); + var file_date = $('#photoInput').prop('files')[0]; + form_data.append('file',file_date); + BM.ajax({ + url : mv.urlController + 'training/uploadFile', + type : 'POST', + data : form_data, + method : 'POST', + processData: false, + contentType: false, + success: function(data){ + $('#textPhotoInput').val(data); + } + }); + }) + }, +}; + +--PHP + public function uploadFile(){ + if(!file_exists('storage')) mkdir('storage'); + foreach($_FILES as $file){ + file_put_contents('storage/'.$file["name"], fopen($file["tmp_name"],"r")); + $filename = $file["name"]; + } + return $this->load->view('json_view', array('json' => $filename)); + } + diff --git a/api/storage/uploadFile.txt b/api/storage/uploadFile.txt new file mode 100644 index 0000000..c40642c --- /dev/null +++ b/api/storage/uploadFile.txt @@ -0,0 +1,8 @@ + public function uploadFile(){ + if(!file_exists('storage')) mkdir('storage'); + foreach($_FILES as $file){ + file_put_contents('storage/'.$file["name"], fopen($file["tmp_name"],"r")); + $filename = $file["name"]; + } + return $this->load->view('json_view', array('json' => $filename)); + } \ No newline at end of file diff --git a/api/system/.htaccess b/api/system/.htaccess new file mode 100644 index 0000000..14249c5 --- /dev/null +++ b/api/system/.htaccess @@ -0,0 +1 @@ +Deny from all \ No newline at end of file diff --git a/api/system/core/Benchmark.php b/api/system/core/Benchmark.php new file mode 100644 index 0000000..a200727 --- /dev/null +++ b/api/system/core/Benchmark.php @@ -0,0 +1,118 @@ +marker[$name] = microtime(); + } + + // -------------------------------------------------------------------- + + /** + * Calculates the time difference between two marked points. + * + * If the first parameter is empty this function instead returns the + * {elapsed_time} pseudo-variable. This permits the full system + * execution time to be shown in a template. The output class will + * swap the real value for this variable. + * + * @access public + * @param string a particular marked point + * @param string a particular marked point + * @param integer the number of decimal places + * @return mixed + */ + function elapsed_time($point1 = '', $point2 = '', $decimals = 4) + { + if ($point1 == '') + { + return '{elapsed_time}'; + } + + if ( ! isset($this->marker[$point1])) + { + return ''; + } + + if ( ! isset($this->marker[$point2])) + { + $this->marker[$point2] = microtime(); + } + + list($sm, $ss) = explode(' ', $this->marker[$point1]); + list($em, $es) = explode(' ', $this->marker[$point2]); + + return number_format(($em + $es) - ($sm + $ss), $decimals); + } + + // -------------------------------------------------------------------- + + /** + * Memory Usage + * + * This function returns the {memory_usage} pseudo-variable. + * This permits it to be put it anywhere in a template + * without the memory being calculated until the end. + * The output class will swap the real value for this variable. + * + * @access public + * @return string + */ + function memory_usage() + { + return '{memory_usage}'; + } + +} + +// END CI_Benchmark class + +/* End of file Benchmark.php */ +/* Location: ./system/core/Benchmark.php */ \ No newline at end of file diff --git a/api/system/core/CodeIgniter.php b/api/system/core/CodeIgniter.php new file mode 100644 index 0000000..e0819c8 --- /dev/null +++ b/api/system/core/CodeIgniter.php @@ -0,0 +1,402 @@ + $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Set a liberal script execution time limit + * ------------------------------------------------------ + */ + if (function_exists("set_time_limit") == TRUE AND @ini_get("safe_mode") == 0) + { + @set_time_limit(300); + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->_call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + */ + $CFG =& load_class('Config', 'core'); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config)) + { + $CFG->_assign_to_config($assign_to_config); + } + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + * + * Note: Order here is rather important as the UTF-8 + * class needs to be used very early on, but it cannot + * properly determine if UTf-8 can be supported until + * after the Config class is instantiated. + * + */ + + $UNI =& load_class('Utf8', 'core'); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core'); + $RTR->_set_routing(); + + // Set any routing overrides that may exist in the main index file + if (isset($routing)) + { + $RTR->_set_overrides($routing); + } + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->_call_hook('cache_override') === FALSE) + { + if ($OUT->_display_cache($CFG, $URI) == TRUE) + { + exit; + } + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require BASEPATH.'core/Controller.php'; + + function &get_instance() + { + return CI_Controller::get_instance(); + } + + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Load the local application controller + // Note: The Router class automatically validates the controller path using the router->_validate_request(). + // If this include fails it means that the default controller in the Routes.php file is not resolving to something valid. + if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().'.php')) + { + show_error('Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.'); + } + + include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().'.php'); + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + +/* + * ------------------------------------------------------ + * Security check + * ------------------------------------------------------ + * + * None of the functions in the app controller or the + * loader class can be called via the URI, nor can + * controller functions that begin with an underscore + */ + $class = $RTR->fetch_class(); + $method = $RTR->fetch_method(); + + if ( ! class_exists($class) + OR strncmp($method, '_', 1) == 0 + OR in_array(strtolower($method), array_map('strtolower', get_class_methods('CI_Controller'))) + ) + { + if ( ! empty($RTR->routes['404_override'])) + { + $x = explode('/', $RTR->routes['404_override']); + $class = $x[0]; + $method = (isset($x[1]) ? $x[1] : 'index'); + if ( ! class_exists($class)) + { + if ( ! file_exists(APPPATH.'controllers/'.$class.'.php')) + { + show_404("{$class}/{$method}"); + } + + include_once(APPPATH.'controllers/'.$class.'.php'); + } + } + else + { + show_404("{$class}/{$method}"); + } + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->_call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->_call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + // Is there a "remap" function? If so, we call it instead + if (method_exists($CI, '_remap')) + { + $CI->_remap($method, array_slice($URI->rsegments, 2)); + } + else + { + // is_callable() returns TRUE on some versions of PHP 5 for private and protected + // methods, so we'll use this workaround for consistent behavior + if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI)))) + { + // Check and see if we are using a 404 override and use it. + if ( ! empty($RTR->routes['404_override'])) + { + $x = explode('/', $RTR->routes['404_override']); + $class = $x[0]; + $method = (isset($x[1]) ? $x[1] : 'index'); + if ( ! class_exists($class)) + { + if ( ! file_exists(APPPATH.'controllers/'.$class.'.php')) + { + show_404("{$class}/{$method}"); + } + + include_once(APPPATH.'controllers/'.$class.'.php'); + unset($CI); + $CI = new $class(); + } + } + else + { + show_404("{$class}/{$method}"); + } + } + + // Call the requested method. + // Any URI segments present (besides the class/function) will be passed to the method for convenience + call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2)); + } + + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->_call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->_call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->_call_hook('post_system'); + +/* + * ------------------------------------------------------ + * Close the DB connection if one exists + * ------------------------------------------------------ + */ + if (class_exists('CI_DB') AND isset($CI->db)) + { + $CI->db->close(); + } + + +/* End of file CodeIgniter.php */ +/* Location: ./system/core/CodeIgniter.php */ \ No newline at end of file diff --git a/api/system/core/Common.php b/api/system/core/Common.php new file mode 100644 index 0000000..f235b87 --- /dev/null +++ b/api/system/core/Common.php @@ -0,0 +1,565 @@ + 5 +* we'll set a static variable. +* +* @access public +* @param string +* @return bool TRUE if the current version is $version or higher +*/ +if ( ! function_exists('is_php')) +{ + function is_php($version = '5.0.0') + { + static $_is_php; + $version = (string)$version; + + if ( ! isset($_is_php[$version])) + { + $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE; + } + + return $_is_php[$version]; + } +} + +// ------------------------------------------------------------------------ + +/** + * Tests for file writability + * + * is_writable() returns TRUE on Windows servers when you really can't write to + * the file, based on the read-only attribute. is_writable() is also unreliable + * on Unix servers if safe_mode is on. + * + * @access private + * @return void + */ +if ( ! function_exists('is_really_writable')) +{ + function is_really_writable($file) + { + // If we're on a Unix server with safe_mode off we call is_writable + if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE) + { + return is_writable($file); + } + + // For windows servers and safe_mode "on" installations we'll actually + // write a file then read it. Bah... + if (is_dir($file)) + { + $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100)); + + if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) + { + return FALSE; + } + + fclose($fp); + @chmod($file, DIR_WRITE_MODE); + @unlink($file); + return TRUE; + } + elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) + { + return FALSE; + } + + fclose($fp); + return TRUE; + } +} + +// ------------------------------------------------------------------------ + +/** +* Class registry +* +* This function acts as a singleton. If the requested class does not +* exist it is instantiated and set to a static variable. If it has +* previously been instantiated the variable is returned. +* +* @access public +* @param string the class name being requested +* @param string the directory where the class should be found +* @param string the class name prefix +* @return object +*/ +if ( ! function_exists('load_class')) +{ + function &load_class($class, $directory = 'libraries', $prefix = 'CI_') + { + static $_classes = array(); + + // Does the class exist? If so, we're done... + if (isset($_classes[$class])) + { + return $_classes[$class]; + } + + $name = FALSE; + + // Look for the class first in the local application/libraries folder + // then in the native system/libraries folder + foreach (array(APPPATH, BASEPATH) as $path) + { + if (file_exists($path.$directory.'/'.$class.'.php')) + { + $name = $prefix.$class; + + if (class_exists($name) === FALSE) + { + require($path.$directory.'/'.$class.'.php'); + } + + break; + } + } + + // Is the request a class extension? If so we load it too + if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php')) + { + $name = config_item('subclass_prefix').$class; + + if (class_exists($name) === FALSE) + { + require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'); + } + } + + // Did we find the class? + if ($name === FALSE) + { + // Note: We use exit() rather then show_error() in order to avoid a + // self-referencing loop with the Excptions class + exit('Unable to locate the specified class: '.$class.'.php'); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = new $name(); + return $_classes[$class]; + } +} + +// -------------------------------------------------------------------- + +/** +* Keeps track of which libraries have been loaded. This function is +* called by the load_class() function above +* +* @access public +* @return array +*/ +if ( ! function_exists('is_loaded')) +{ + function &is_loaded($class = '') + { + static $_is_loaded = array(); + + if ($class != '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; + } +} + +// ------------------------------------------------------------------------ + +/** +* Loads the main config.php file +* +* This function lets us grab the config file even if the Config class +* hasn't been instantiated yet +* +* @access private +* @return array +*/ +if ( ! function_exists('get_config')) +{ + function &get_config($replace = array()) + { + static $_config; + + if (isset($_config)) + { + return $_config[0]; + } + + // Is the config file in the environment folder? + if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php')) + { + $file_path = APPPATH.'config/config.php'; + } + + // Fetch the config file + if ( ! file_exists($file_path)) + { + exit('The configuration file does not exist.'); + } + + require($file_path); + + // Does the $config array exist in the file? + if ( ! isset($config) OR ! is_array($config)) + { + exit('Your config file does not appear to be formatted correctly.'); + } + + // Are any values being dynamically replaced? + if (count($replace) > 0) + { + foreach ($replace as $key => $val) + { + if (isset($config[$key])) + { + $config[$key] = $val; + } + } + } + + $_config[0] =& $config; + return $_config[0]; + } +} + +// ------------------------------------------------------------------------ + +/** +* Returns the specified config item +* +* @access public +* @return mixed +*/ +if ( ! function_exists('config_item')) +{ + function config_item($item) + { + static $_config_item = array(); + + if ( ! isset($_config_item[$item])) + { + $config =& get_config(); + + if ( ! isset($config[$item])) + { + return FALSE; + } + $_config_item[$item] = $config[$item]; + } + + return $_config_item[$item]; + } +} + +// ------------------------------------------------------------------------ + +/** +* Error Handler +* +* This function lets us invoke the exception class and +* display errors using the standard error template located +* in application/errors/errors.php +* This function will send the error page directly to the +* browser and exit. +* +* @access public +* @return void +*/ +if ( ! function_exists('show_error')) +{ + function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered') + { + $_error =& load_class('Exceptions', 'core'); + echo $_error->show_error($heading, $message, 'error_general', $status_code); + exit; + } +} + +// ------------------------------------------------------------------------ + +/** +* 404 Page Handler +* +* This function is similar to the show_error() function above +* However, instead of the standard error template it displays +* 404 errors. +* +* @access public +* @return void +*/ +if ( ! function_exists('show_404')) +{ + function show_404($page = '', $log_error = TRUE) + { + $_error =& load_class('Exceptions', 'core'); + $_error->show_404($page, $log_error); + exit; + } +} + +// ------------------------------------------------------------------------ + +/** +* Error Logging Interface +* +* We use this as a simple mechanism to access the logging +* class and send messages to be logged. +* +* @access public +* @return void +*/ +if ( ! function_exists('log_message')) +{ + function log_message($level = 'error', $message, $php_error = FALSE) + { + static $_log; + + if (config_item('log_threshold') == 0) + { + return; + } + + $_log =& load_class('Log'); + $_log->write_log($level, $message, $php_error); + } +} + +// ------------------------------------------------------------------------ + +/** + * Set HTTP Status Header + * + * @access public + * @param int the status code + * @param string + * @return void + */ +if ( ! function_exists('set_status_header')) +{ + function set_status_header($code = 200, $text = '') + { + $stati = array( + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 307 => 'Temporary Redirect', + + 400 => 'Bad Request', + 401 => 'Unauthorized', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported' + ); + + if ($code == '' OR ! is_numeric($code)) + { + show_error('Status codes must be numeric', 500); + } + + if (isset($stati[$code]) AND $text == '') + { + $text = $stati[$code]; + } + + if ($text == '') + { + show_error('No status text available. Please check your status code number or supply your own message text.', 500); + } + + $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE; + + if (substr(php_sapi_name(), 0, 3) == 'cgi') + { + header("Status: {$code} {$text}", TRUE); + } + elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') + { + header($server_protocol." {$code} {$text}", TRUE, $code); + } + else + { + header("HTTP/1.1 {$code} {$text}", TRUE, $code); + } + } +} + +// -------------------------------------------------------------------- + +/** +* Exception Handler +* +* This is the custom exception handler that is declaired at the top +* of Codeigniter.php. The main reason we use this is to permit +* PHP errors to be logged in our own log files since the user may +* not have access to server logs. Since this function +* effectively intercepts PHP errors, however, we also need +* to display errors based on the current error_reporting level. +* We do that with the use of a PHP error template. +* +* @access private +* @return void +*/ +if ( ! function_exists('_exception_handler')) +{ + function _exception_handler($severity, $message, $filepath, $line) + { + // We don't bother with "strict" notices since they tend to fill up + // the log file with excess information that isn't normally very helpful. + // For example, if you are running PHP 5 and you use version 4 style + // class functions (without prefixes like "public", "private", etc.) + // you'll get notices telling you that these have been deprecated. + if ($severity == E_STRICT) + { + return; + } + + $_error =& load_class('Exceptions', 'core'); + + // Should we display the error? We'll get the current error_reporting + // level and add its bits with the severity bits to find out. + if (($severity & error_reporting()) == $severity) + { + $_error->show_php_error($severity, $message, $filepath, $line); + } + + // Should we log the error? No? We're done... + if (config_item('log_threshold') == 0) + { + return; + } + + $_error->log_exception($severity, $message, $filepath, $line); + } +} + +// -------------------------------------------------------------------- + +/** + * Remove Invisible Characters + * + * This prevents sandwiching null characters + * between ascii characters, like Java\0script. + * + * @access public + * @param string + * @return string + */ +if ( ! function_exists('remove_invisible_characters')) +{ + function remove_invisible_characters($str, $url_encoded = TRUE) + { + $non_displayables = array(); + + // every control character except newline (dec 10) + // carriage return (dec 13), and horizontal tab (dec 09) + + if ($url_encoded) + { + $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15 + $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31 + } + + $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127 + + do + { + $str = preg_replace($non_displayables, '', $str, -1, $count); + } + while ($count); + + return $str; + } +} + +// ------------------------------------------------------------------------ + +/** +* Returns HTML escaped variable +* +* @access public +* @param mixed +* @return mixed +*/ +if ( ! function_exists('html_escape')) +{ + function html_escape($var) + { + if (is_array($var)) + { + return array_map('html_escape', $var); + } + else + { + return htmlspecialchars($var, ENT_QUOTES, config_item('charset')); + } + } +} + +/* End of file Common.php */ +/* Location: ./system/core/Common.php */ \ No newline at end of file diff --git a/api/system/core/Config.php b/api/system/core/Config.php new file mode 100644 index 0000000..5dffbf3 --- /dev/null +++ b/api/system/core/Config.php @@ -0,0 +1,379 @@ +config =& get_config(); + log_message('debug', "Config Class Initialized"); + + // Set the base_url automatically if none was provided + if ($this->config['base_url'] == '') + { + if (isset($_SERVER['HTTP_HOST'])) + { + $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; + $base_url .= '://'. $_SERVER['HTTP_HOST']; + $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); + } + + else + { + $base_url = 'http://localhost/'; + } + + $this->set_item('base_url', $base_url); + } + } + + // -------------------------------------------------------------------- + + /** + * Load Config File + * + * @access public + * @param string the config file name + * @param boolean if configuration values should be loaded into their own section + * @param boolean true if errors should just return false, false if an error message should be displayed + * @return boolean if the file was loaded correctly + */ + function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) + { + $file = ($file == '') ? 'config' : str_replace('.php', '', $file); + $found = FALSE; + $loaded = FALSE; + + $check_locations = defined('ENVIRONMENT') + ? array(ENVIRONMENT.'/'.$file, $file) + : array($file); + + foreach ($this->_config_paths as $path) + { + foreach ($check_locations as $location) + { + $file_path = $path.'config/'.$location.'.php'; + + if (in_array($file_path, $this->is_loaded, TRUE)) + { + $loaded = TRUE; + continue 2; + } + + if (file_exists($file_path)) + { + $found = TRUE; + break; + } + } + + if ($found === FALSE) + { + continue; + } + + include($file_path); + + if ( ! isset($config) OR ! is_array($config)) + { + if ($fail_gracefully === TRUE) + { + return FALSE; + } + show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); + } + + if ($use_sections === TRUE) + { + if (isset($this->config[$file])) + { + $this->config[$file] = array_merge($this->config[$file], $config); + } + else + { + $this->config[$file] = $config; + } + } + else + { + $this->config = array_merge($this->config, $config); + } + + $this->is_loaded[] = $file_path; + unset($config); + + $loaded = TRUE; + log_message('debug', 'Config file loaded: '.$file_path); + break; + } + + if ($loaded === FALSE) + { + if ($fail_gracefully === TRUE) + { + return FALSE; + } + show_error('The configuration file '.$file.'.php does not exist.'); + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Fetch a config file item + * + * + * @access public + * @param string the config item name + * @param string the index name + * @param bool + * @return string + */ + function item($item, $index = '') + { + if ($index == '') + { + if ( ! isset($this->config[$item])) + { + return FALSE; + } + + $pref = $this->config[$item]; + } + else + { + if ( ! isset($this->config[$index])) + { + return FALSE; + } + + if ( ! isset($this->config[$index][$item])) + { + return FALSE; + } + + $pref = $this->config[$index][$item]; + } + + return $pref; + } + + // -------------------------------------------------------------------- + + /** + * Fetch a config file item - adds slash after item (if item is not empty) + * + * @access public + * @param string the config item name + * @param bool + * @return string + */ + function slash_item($item) + { + if ( ! isset($this->config[$item])) + { + return FALSE; + } + if( trim($this->config[$item]) == '') + { + return ''; + } + + return rtrim($this->config[$item], '/').'/'; + } + + // -------------------------------------------------------------------- + + /** + * Site URL + * Returns base_url . index_page [. uri_string] + * + * @access public + * @param string the URI string + * @return string + */ + function site_url($uri = '') + { + if ($uri == '') + { + return $this->slash_item('base_url').$this->item('index_page'); + } + + if ($this->item('enable_query_strings') == FALSE) + { + $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix'); + return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix; + } + else + { + return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri); + } + } + + // ------------------------------------------------------------- + + /** + * Base URL + * Returns base_url [. uri_string] + * + * @access public + * @param string $uri + * @return string + */ + function base_url($uri = '') + { + return $this->slash_item('base_url').ltrim($this->_uri_string($uri), '/'); + } + + // ------------------------------------------------------------- + + /** + * Build URI string for use in Config::site_url() and Config::base_url() + * + * @access protected + * @param $uri + * @return string + */ + protected function _uri_string($uri) + { + if ($this->item('enable_query_strings') == FALSE) + { + if (is_array($uri)) + { + $uri = implode('/', $uri); + } + $uri = trim($uri, '/'); + } + else + { + if (is_array($uri)) + { + $i = 0; + $str = ''; + foreach ($uri as $key => $val) + { + $prefix = ($i == 0) ? '' : '&'; + $str .= $prefix.$key.'='.$val; + $i++; + } + $uri = $str; + } + } + return $uri; + } + + // -------------------------------------------------------------------- + + /** + * System URL + * + * @access public + * @return string + */ + function system_url() + { + $x = explode("/", preg_replace("|/*(.+?)/*$|", "\\1", BASEPATH)); + return $this->slash_item('base_url').end($x).'/'; + } + + // -------------------------------------------------------------------- + + /** + * Set a config file item + * + * @access public + * @param string the config item key + * @param string the config item value + * @return void + */ + function set_item($item, $value) + { + $this->config[$item] = $value; + } + + // -------------------------------------------------------------------- + + /** + * Assign to Config + * + * This function is called by the front controller (CodeIgniter.php) + * after the Config class is instantiated. It permits config items + * to be assigned or overriden by variables contained in the index.php file + * + * @access private + * @param array + * @return void + */ + function _assign_to_config($items = array()) + { + if (is_array($items)) + { + foreach ($items as $key => $val) + { + $this->set_item($key, $val); + } + } + } +} + +// END CI_Config class + +/* End of file Config.php */ +/* Location: ./system/core/Config.php */ diff --git a/api/system/core/Controller.php b/api/system/core/Controller.php new file mode 100644 index 0000000..fddb81e --- /dev/null +++ b/api/system/core/Controller.php @@ -0,0 +1,64 @@ + $class) + { + $this->$var =& load_class($class); + } + + $this->load =& load_class('Loader', 'core'); + + $this->load->initialize(); + + log_message('debug', "Controller Class Initialized"); + } + + public static function &get_instance() + { + return self::$instance; + } +} +// END Controller class + +/* End of file Controller.php */ +/* Location: ./system/core/Controller.php */ \ No newline at end of file diff --git a/api/system/core/Exceptions.php b/api/system/core/Exceptions.php new file mode 100644 index 0000000..869739a --- /dev/null +++ b/api/system/core/Exceptions.php @@ -0,0 +1,193 @@ + 'Error', + E_WARNING => 'Warning', + E_PARSE => 'Parsing Error', + E_NOTICE => 'Notice', + E_CORE_ERROR => 'Core Error', + E_CORE_WARNING => 'Core Warning', + E_COMPILE_ERROR => 'Compile Error', + E_COMPILE_WARNING => 'Compile Warning', + E_USER_ERROR => 'User Error', + E_USER_WARNING => 'User Warning', + E_USER_NOTICE => 'User Notice', + E_STRICT => 'Runtime Notice' + ); + + + /** + * Constructor + */ + public function __construct() + { + $this->ob_level = ob_get_level(); + // Note: Do not log messages from this constructor. + } + + // -------------------------------------------------------------------- + + /** + * Exception Logger + * + * This function logs PHP generated error messages + * + * @access private + * @param string the error severity + * @param string the error string + * @param string the error filepath + * @param string the error line number + * @return string + */ + function log_exception($severity, $message, $filepath, $line) + { + $severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity]; + + log_message('error', 'Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * 404 Page Not Found Handler + * + * @access private + * @param string the page + * @param bool log error yes/no + * @return string + */ + function show_404($page = '', $log_error = TRUE) + { + $heading = "404 Page Not Found"; + $message = "The page you requested was not found."; + + // By default we log this, but allow a dev to skip it + if ($log_error) + { + log_message('error', '404 Page Not Found --> '.$page); + } + + echo $this->show_error($heading, $message, 'error_404', 404); + exit; + } + + // -------------------------------------------------------------------- + + /** + * General Error Page + * + * This function takes an error message as input + * (either as a string or an array) and displays + * it using the specified template. + * + * @access private + * @param string the heading + * @param string the message + * @param string the template name + * @param int the status code + * @return string + */ + function show_error($heading, $message, $template = 'error_general', $status_code = 500) + { + set_status_header($status_code); + + $message = '

'.implode('

', ( ! is_array($message)) ? array($message) : $message).'

'; + + if (ob_get_level() > $this->ob_level + 1) + { + ob_end_flush(); + } + ob_start(); + include(APPPATH.'errors/'.$template.'.php'); + $buffer = ob_get_contents(); + ob_end_clean(); + return $buffer; + } + + // -------------------------------------------------------------------- + + /** + * Native PHP error handler + * + * @access private + * @param string the error severity + * @param string the error string + * @param string the error filepath + * @param string the error line number + * @return string + */ + function show_php_error($severity, $message, $filepath, $line) + { + $severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity]; + + $filepath = str_replace("\\", "/", $filepath); + + // For safety reasons we do not show the full file path + if (FALSE !== strpos($filepath, '/')) + { + $x = explode('/', $filepath); + $filepath = $x[count($x)-2].'/'.end($x); + } + + if (ob_get_level() > $this->ob_level + 1) + { + ob_end_flush(); + } + ob_start(); + include(APPPATH.'errors/error_php.php'); + $buffer = ob_get_contents(); + ob_end_clean(); + echo $buffer; + } + + +} +// END Exceptions Class + +/* End of file Exceptions.php */ +/* Location: ./system/core/Exceptions.php */ \ No newline at end of file diff --git a/api/system/core/Hooks.php b/api/system/core/Hooks.php new file mode 100644 index 0000000..33f1c03 --- /dev/null +++ b/api/system/core/Hooks.php @@ -0,0 +1,248 @@ +_initialize(); + log_message('debug', "Hooks Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Initialize the Hooks Preferences + * + * @access private + * @return void + */ + function _initialize() + { + $CFG =& load_class('Config', 'core'); + + // If hooks are not enabled in the config file + // there is nothing else to do + + if ($CFG->item('enable_hooks') == FALSE) + { + return; + } + + // Grab the "hooks" definition file. + // If there are no hooks, we're done. + + if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/hooks.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php'); + } + elseif (is_file(APPPATH.'config/hooks.php')) + { + include(APPPATH.'config/hooks.php'); + } + + + if ( ! isset($hook) OR ! is_array($hook)) + { + return; + } + + $this->hooks =& $hook; + $this->enabled = TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Call Hook + * + * Calls a particular hook + * + * @access private + * @param string the hook name + * @return mixed + */ + function _call_hook($which = '') + { + if ( ! $this->enabled OR ! isset($this->hooks[$which])) + { + return FALSE; + } + + if (isset($this->hooks[$which][0]) AND is_array($this->hooks[$which][0])) + { + foreach ($this->hooks[$which] as $val) + { + $this->_run_hook($val); + } + } + else + { + $this->_run_hook($this->hooks[$which]); + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Run Hook + * + * Runs a particular hook + * + * @access private + * @param array the hook details + * @return bool + */ + function _run_hook($data) + { + if ( ! is_array($data)) + { + return FALSE; + } + + // ----------------------------------- + // Safety - Prevents run-away loops + // ----------------------------------- + + // If the script being called happens to have the same + // hook call within it a loop can happen + + if ($this->in_progress == TRUE) + { + return; + } + + // ----------------------------------- + // Set file path + // ----------------------------------- + + if ( ! isset($data['filepath']) OR ! isset($data['filename'])) + { + return FALSE; + } + + $filepath = APPPATH.$data['filepath'].'/'.$data['filename']; + + if ( ! file_exists($filepath)) + { + return FALSE; + } + + // ----------------------------------- + // Set class/function name + // ----------------------------------- + + $class = FALSE; + $function = FALSE; + $params = ''; + + if (isset($data['class']) AND $data['class'] != '') + { + $class = $data['class']; + } + + if (isset($data['function'])) + { + $function = $data['function']; + } + + if (isset($data['params'])) + { + $params = $data['params']; + } + + if ($class === FALSE AND $function === FALSE) + { + return FALSE; + } + + // ----------------------------------- + // Set the in_progress flag + // ----------------------------------- + + $this->in_progress = TRUE; + + // ----------------------------------- + // Call the requested class and/or function + // ----------------------------------- + + if ($class !== FALSE) + { + if ( ! class_exists($class)) + { + require($filepath); + } + + $HOOK = new $class; + $HOOK->$function($params); + } + else + { + if ( ! function_exists($function)) + { + require($filepath); + } + + $function($params); + } + + $this->in_progress = FALSE; + return TRUE; + } + +} + +// END CI_Hooks class + +/* End of file Hooks.php */ +/* Location: ./system/core/Hooks.php */ \ No newline at end of file diff --git a/api/system/core/Input.php b/api/system/core/Input.php new file mode 100644 index 0000000..0c1f2b0 --- /dev/null +++ b/api/system/core/Input.php @@ -0,0 +1,849 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + + global $SEC; + $this->security =& $SEC; + + // Do we need the UTF-8 class? + if (UTF8_ENABLED === TRUE) + { + global $UNI; + $this->uni =& $UNI; + } + + // Sanitize global arrays + $this->_sanitize_globals(); + } + + // -------------------------------------------------------------------- + + /** + * Fetch from array + * + * This is a helper function to retrieve values from global arrays + * + * @access private + * @param array + * @param string + * @param bool + * @return string + */ + function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE) + { + if ( ! isset($array[$index])) + { + return FALSE; + } + + if ($xss_clean === TRUE) + { + return $this->security->xss_clean($array[$index]); + } + + return $array[$index]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch an item from the GET array + * + * @access public + * @param string + * @param bool + * @return string + */ + function get($index = NULL, $xss_clean = FALSE) + { + // Check if a field has been provided + if ($index === NULL AND ! empty($_GET)) + { + $get = array(); + + // loop through the full _GET array + foreach (array_keys($_GET) as $key) + { + $get[$key] = $this->_fetch_from_array($_GET, $key, $xss_clean); + } + return $get; + } + + return $this->_fetch_from_array($_GET, $index, $xss_clean); + } + + // -------------------------------------------------------------------- + + /** + * Fetch an item from the POST array + * + * @access public + * @param string + * @param bool + * @return string + */ + function post($index = NULL, $xss_clean = FALSE) + { + // Check if a field has been provided + if ($index === NULL AND ! empty($_POST)) + { + $post = array(); + + // Loop through the full _POST array and return it + foreach (array_keys($_POST) as $key) + { + $post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean); + } + return $post; + } + + return $this->_fetch_from_array($_POST, $index, $xss_clean); + } + + + // -------------------------------------------------------------------- + + /** + * Fetch an item from either the GET array or the POST + * + * @access public + * @param string The index key + * @param bool XSS cleaning + * @return string + */ + function get_post($index = '', $xss_clean = FALSE) + { + if ( ! isset($_POST[$index]) ) + { + return $this->get($index, $xss_clean); + } + else + { + return $this->post($index, $xss_clean); + } + } + + // -------------------------------------------------------------------- + + /** + * Fetch an item from the COOKIE array + * + * @access public + * @param string + * @param bool + * @return string + */ + function cookie($index = '', $xss_clean = FALSE) + { + return $this->_fetch_from_array($_COOKIE, $index, $xss_clean); + } + + // ------------------------------------------------------------------------ + + /** + * Set cookie + * + * Accepts six parameter, or you can submit an associative + * array in the first parameter containing all the values. + * + * @access public + * @param mixed + * @param string the value of the cookie + * @param string the number of seconds until expiration + * @param string the cookie domain. Usually: .yourdomain.com + * @param string the cookie path + * @param string the cookie prefix + * @param bool true makes the cookie secure + * @return void + */ + function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE) + { + if (is_array($name)) + { + // always leave 'name' in last place, as the loop will break otherwise, due to $$item + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'name') as $item) + { + if (isset($name[$item])) + { + $$item = $name[$item]; + } + } + } + + if ($prefix == '' AND config_item('cookie_prefix') != '') + { + $prefix = config_item('cookie_prefix'); + } + if ($domain == '' AND config_item('cookie_domain') != '') + { + $domain = config_item('cookie_domain'); + } + if ($path == '/' AND config_item('cookie_path') != '/') + { + $path = config_item('cookie_path'); + } + if ($secure == FALSE AND config_item('cookie_secure') != FALSE) + { + $secure = config_item('cookie_secure'); + } + + if ( ! is_numeric($expire)) + { + $expire = time() - 86500; + } + else + { + $expire = ($expire > 0) ? time() + $expire : 0; + } + + setcookie($prefix.$name, $value, $expire, $path, $domain, $secure); + } + + // -------------------------------------------------------------------- + + /** + * Fetch an item from the SERVER array + * + * @access public + * @param string + * @param bool + * @return string + */ + function server($index = '', $xss_clean = FALSE) + { + return $this->_fetch_from_array($_SERVER, $index, $xss_clean); + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * @return string + */ + public function ip_address() + { + if ($this->ip_address !== FALSE) + { + return $this->ip_address; + } + + $proxy_ips = config_item('proxy_ips'); + if ( ! empty($proxy_ips)) + { + $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips)); + foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header) + { + if (($spoof = $this->server($header)) !== FALSE) + { + // Some proxies typically list the whole chain of IP + // addresses through which the client has reached us. + // e.g. client_ip, proxy_ip1, proxy_ip2, etc. + if (strpos($spoof, ',') !== FALSE) + { + $spoof = explode(',', $spoof, 2); + $spoof = $spoof[0]; + } + + if ( ! $this->valid_ip($spoof)) + { + $spoof = FALSE; + } + else + { + break; + } + } + } + + $this->ip_address = ($spoof !== FALSE && in_array($_SERVER['REMOTE_ADDR'], $proxy_ips, TRUE)) + ? $spoof : $_SERVER['REMOTE_ADDR']; + } + else + { + $this->ip_address = $_SERVER['REMOTE_ADDR']; + } + + if ( ! $this->valid_ip($this->ip_address)) + { + $this->ip_address = '0.0.0.0'; + } + + return $this->ip_address; + } + + // -------------------------------------------------------------------- + + /** + * Validate IP Address + * + * @access public + * @param string + * @param string ipv4 or ipv6 + * @return bool + */ + public function valid_ip($ip, $which = '') + { + $which = strtolower($which); + + // First check if filter_var is available + if (is_callable('filter_var')) + { + switch ($which) { + case 'ipv4': + $flag = FILTER_FLAG_IPV4; + break; + case 'ipv6': + $flag = FILTER_FLAG_IPV6; + break; + default: + $flag = ''; + break; + } + + return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flag); + } + + if ($which !== 'ipv6' && $which !== 'ipv4') + { + if (strpos($ip, ':') !== FALSE) + { + $which = 'ipv6'; + } + elseif (strpos($ip, '.') !== FALSE) + { + $which = 'ipv4'; + } + else + { + return FALSE; + } + } + + $func = '_valid_'.$which; + return $this->$func($ip); + } + + // -------------------------------------------------------------------- + + /** + * Validate IPv4 Address + * + * Updated version suggested by Geert De Deckere + * + * @access protected + * @param string + * @return bool + */ + protected function _valid_ipv4($ip) + { + $ip_segments = explode('.', $ip); + + // Always 4 segments needed + if (count($ip_segments) !== 4) + { + return FALSE; + } + // IP can not start with 0 + if ($ip_segments[0][0] == '0') + { + return FALSE; + } + + // Check each segment + foreach ($ip_segments as $segment) + { + // IP segments must be digits and can not be + // longer than 3 digits or greater then 255 + if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate IPv6 Address + * + * @access protected + * @param string + * @return bool + */ + protected function _valid_ipv6($str) + { + // 8 groups, separated by : + // 0-ffff per group + // one set of consecutive 0 groups can be collapsed to :: + + $groups = 8; + $collapsed = FALSE; + + $chunks = array_filter( + preg_split('/(:{1,2})/', $str, NULL, PREG_SPLIT_DELIM_CAPTURE) + ); + + // Rule out easy nonsense + if (current($chunks) == ':' OR end($chunks) == ':') + { + return FALSE; + } + + // PHP supports IPv4-mapped IPv6 addresses, so we'll expect those as well + if (strpos(end($chunks), '.') !== FALSE) + { + $ipv4 = array_pop($chunks); + + if ( ! $this->_valid_ipv4($ipv4)) + { + return FALSE; + } + + $groups--; + } + + while ($seg = array_pop($chunks)) + { + if ($seg[0] == ':') + { + if (--$groups == 0) + { + return FALSE; // too many groups + } + + if (strlen($seg) > 2) + { + return FALSE; // long separator + } + + if ($seg == '::') + { + if ($collapsed) + { + return FALSE; // multiple collapsed + } + + $collapsed = TRUE; + } + } + elseif (preg_match("/[^0-9a-f]/i", $seg) OR strlen($seg) > 4) + { + return FALSE; // invalid segment + } + } + + return $collapsed OR $groups == 1; + } + + // -------------------------------------------------------------------- + + /** + * User Agent + * + * @access public + * @return string + */ + function user_agent() + { + if ($this->user_agent !== FALSE) + { + return $this->user_agent; + } + + $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT']; + + return $this->user_agent; + } + + // -------------------------------------------------------------------- + + /** + * Sanitize Globals + * + * This function does the following: + * + * Unsets $_GET data (if query strings are not enabled) + * + * Unsets all globals if register_globals is enabled + * + * Standardizes newline characters to \n + * + * @access private + * @return void + */ + function _sanitize_globals() + { + // It would be "wrong" to unset any of these GLOBALS. + $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', + '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA', + 'system_folder', 'application_folder', 'BM', 'EXT', + 'CFG', 'URI', 'RTR', 'OUT', 'IN'); + + // Unset globals for securiy. + // This is effectively the same as register_globals = off + foreach (array($_GET, $_POST, $_COOKIE) as $global) + { + if ( ! is_array($global)) + { + if ( ! in_array($global, $protected)) + { + global $$global; + $$global = NULL; + } + } + else + { + foreach ($global as $key => $val) + { + if ( ! in_array($key, $protected)) + { + global $$key; + $$key = NULL; + } + } + } + } + + // Is $_GET data allowed? If not we'll set the $_GET to an empty array + if ($this->_allow_get_array == FALSE) + { + $_GET = array(); + } + else + { + if (is_array($_GET) AND count($_GET) > 0) + { + foreach ($_GET as $key => $val) + { + $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); + } + } + } + + // Clean $_POST Data + if (is_array($_POST) AND count($_POST) > 0) + { + foreach ($_POST as $key => $val) + { + $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); + } + } + + // Clean $_COOKIE Data + if (is_array($_COOKIE) AND count($_COOKIE) > 0) + { + // Also get rid of specially treated cookies that might be set by a server + // or silly application, that are of no use to a CI application anyway + // but that when present will trip our 'Disallowed Key Characters' alarm + // http://www.ietf.org/rfc/rfc2109.txt + // note that the key names below are single quoted strings, and are not PHP variables + unset($_COOKIE['$Version']); + unset($_COOKIE['$Path']); + unset($_COOKIE['$Domain']); + + foreach ($_COOKIE as $key => $val) + { + $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); + } + } + + // Sanitize PHP_SELF + $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']); + + + // CSRF Protection check on HTTP requests + if ($this->_enable_csrf == TRUE && ! $this->is_cli_request()) + { + $this->security->csrf_verify(); + } + + log_message('debug', "Global POST and COOKIE data sanitized"); + } + + // -------------------------------------------------------------------- + + /** + * Clean Input Data + * + * This is a helper function. It escapes data and + * standardizes newline characters to \n + * + * @access private + * @param string + * @return string + */ + function _clean_input_data($str) + { + if (is_array($str)) + { + $new_array = array(); + foreach ($str as $key => $val) + { + $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); + } + return $new_array; + } + + /* We strip slashes if magic quotes is on to keep things consistent + + NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and + it will probably not exist in future versions at all. + */ + if ( ! is_php('5.4') && get_magic_quotes_gpc()) + { + $str = stripslashes($str); + } + + // Clean UTF-8 if supported + if (UTF8_ENABLED === TRUE) + { + $str = $this->uni->clean_string($str); + } + + // Remove control characters + $str = remove_invisible_characters($str); + + // Should we filter the input data? + if ($this->_enable_xss === TRUE) + { + $str = $this->security->xss_clean($str); + } + + // Standardize newlines if needed + if ($this->_standardize_newlines == TRUE) + { + if (strpos($str, "\r") !== FALSE) + { + $str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str); + } + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Clean Keys + * + * This is a helper function. To prevent malicious users + * from trying to exploit keys we make sure that keys are + * only named with alpha-numeric text and a few other items. + * + * @access private + * @param string + * @return string + */ + function _clean_input_keys($str) + { + if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str)) + { + exit('Disallowed Key Characters.'); + } + + // Clean UTF-8 if supported + if (UTF8_ENABLED === TRUE) + { + $str = $this->uni->clean_string($str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Request Headers + * + * In Apache, you can simply call apache_request_headers(), however for + * people running other webservers the function is undefined. + * + * @param bool XSS cleaning + * + * @return array + */ + public function request_headers($xss_clean = FALSE) + { + // Look at Apache go! + if (function_exists('apache_request_headers')) + { + $headers = apache_request_headers(); + } + else + { + $headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE'); + + foreach ($_SERVER as $key => $val) + { + if (strncmp($key, 'HTTP_', 5) === 0) + { + $headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean); + } + } + } + + // take SOME_HEADER and turn it into Some-Header + foreach ($headers as $key => $val) + { + $key = str_replace('_', ' ', strtolower($key)); + $key = str_replace(' ', '-', ucwords($key)); + + $this->headers[$key] = $val; + } + + return $this->headers; + } + + // -------------------------------------------------------------------- + + /** + * Get Request Header + * + * Returns the value of a single member of the headers class member + * + * @param string array key for $this->headers + * @param boolean XSS Clean or not + * @return mixed FALSE on failure, string on success + */ + public function get_request_header($index, $xss_clean = FALSE) + { + if (empty($this->headers)) + { + $this->request_headers(); + } + + if ( ! isset($this->headers[$index])) + { + return FALSE; + } + + if ($xss_clean === TRUE) + { + return $this->security->xss_clean($this->headers[$index]); + } + + return $this->headers[$index]; + } + + // -------------------------------------------------------------------- + + /** + * Is ajax Request? + * + * Test to see if a request contains the HTTP_X_REQUESTED_WITH header + * + * @return boolean + */ + public function is_ajax_request() + { + return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest'); + } + + // -------------------------------------------------------------------- + + /** + * Is cli Request? + * + * Test to see if a request was made from the command line + * + * @return bool + */ + public function is_cli_request() + { + return (php_sapi_name() === 'cli' OR defined('STDIN')); + } + +} + +/* End of file Input.php */ +/* Location: ./system/core/Input.php */ \ No newline at end of file diff --git a/api/system/core/Lang.php b/api/system/core/Lang.php new file mode 100644 index 0000000..5ac6718 --- /dev/null +++ b/api/system/core/Lang.php @@ -0,0 +1,160 @@ +is_loaded, TRUE)) + { + return; + } + + $config =& get_config(); + + if ($idiom == '') + { + $deft_lang = ( ! isset($config['language'])) ? 'english' : $config['language']; + $idiom = ($deft_lang == '') ? 'english' : $deft_lang; + } + + // Determine where the language file is and load it + if ($alt_path != '' && file_exists($alt_path.'language/'.$idiom.'/'.$langfile)) + { + include($alt_path.'language/'.$idiom.'/'.$langfile); + } + else + { + $found = FALSE; + + foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) + { + if (file_exists($package_path.'language/'.$idiom.'/'.$langfile)) + { + include($package_path.'language/'.$idiom.'/'.$langfile); + $found = TRUE; + break; + } + } + + if ($found !== TRUE) + { + show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile); + } + } + + + if ( ! isset($lang)) + { + log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile); + return; + } + + if ($return == TRUE) + { + return $lang; + } + + $this->is_loaded[] = $langfile; + $this->language = array_merge($this->language, $lang); + unset($lang); + + log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Fetch a single line of text from the language array + * + * @access public + * @param string $line the language line + * @return string + */ + function line($line = '') + { + $value = ($line == '' OR ! isset($this->language[$line])) ? FALSE : $this->language[$line]; + + // Because killer robots like unicorns! + if ($value === FALSE) + { + log_message('error', 'Could not find the language line "'.$line.'"'); + } + + return $value; + } + +} +// END Language Class + +/* End of file Lang.php */ +/* Location: ./system/core/Lang.php */ diff --git a/api/system/core/Loader.php b/api/system/core/Loader.php new file mode 100644 index 0000000..6b7ee0c --- /dev/null +++ b/api/system/core/Loader.php @@ -0,0 +1,1248 @@ + 'unit', + 'user_agent' => 'agent'); + + /** + * Constructor + * + * Sets the path to the view files and gets the initial output buffering level + */ + public function __construct() + { + $this->_ci_ob_level = ob_get_level(); + $this->_ci_library_paths = array(APPPATH, BASEPATH); + $this->_ci_helper_paths = array(APPPATH, BASEPATH); + $this->_ci_model_paths = array(APPPATH); + $this->_ci_view_paths = array(APPPATH.'views/' => TRUE); + + log_message('debug', "Loader Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Initialize the Loader + * + * This method is called once in CI_Controller. + * + * @param array + * @return object + */ + public function initialize() + { + $this->_ci_classes = array(); + $this->_ci_loaded_files = array(); + $this->_ci_models = array(); + $this->_base_classes =& is_loaded(); + + $this->_ci_autoloader(); + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Is Loaded + * + * A utility function to test if a class is in the self::$_ci_classes array. + * This function returns the object name if the class tested for is loaded, + * and returns FALSE if it isn't. + * + * It is mainly used in the form_helper -> _get_validation_object() + * + * @param string class being checked for + * @return mixed class object name on the CI SuperObject or FALSE + */ + public function is_loaded($class) + { + if (isset($this->_ci_classes[$class])) + { + return $this->_ci_classes[$class]; + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Class Loader + * + * This function lets users load and instantiate classes. + * It is designed to be called from a user's app controllers. + * + * @param string the name of the class + * @param mixed the optional parameters + * @param string an optional object name + * @return void + */ + public function library($library = '', $params = NULL, $object_name = NULL) + { + if (is_array($library)) + { + foreach ($library as $class) + { + $this->library($class, $params); + } + + return; + } + + if ($library == '' OR isset($this->_base_classes[$library])) + { + return FALSE; + } + + if ( ! is_null($params) && ! is_array($params)) + { + $params = NULL; + } + + $this->_ci_load_class($library, $params, $object_name); + } + + // -------------------------------------------------------------------- + + /** + * Model Loader + * + * This function lets users load and instantiate models. + * + * @param string the name of the class + * @param string name for the model + * @param bool database connection + * @return void + */ + public function model($model, $name = '', $db_conn = FALSE) + { + if (is_array($model)) + { + foreach ($model as $babe) + { + $this->model($babe); + } + return; + } + + if ($model == '') + { + return; + } + + $path = ''; + + // Is the model in a sub-folder? If so, parse out the filename and path. + if (($last_slash = strrpos($model, '/')) !== FALSE) + { + // The path is in front of the last slash + $path = substr($model, 0, $last_slash + 1); + + // And the model name behind it + $model = substr($model, $last_slash + 1); + } + + if ($name == '') + { + $name = $model; + } + + if (in_array($name, $this->_ci_models, TRUE)) + { + return; + } + + $CI =& get_instance(); + if (isset($CI->$name)) + { + show_error('The model name you are loading is the name of a resource that is already being used: '.$name); + } + + $model = strtolower($model); + + foreach ($this->_ci_model_paths as $mod_path) + { + if ( ! file_exists($mod_path.'models/'.$path.$model.'.php')) + { + continue; + } + + if ($db_conn !== FALSE AND ! class_exists('CI_DB')) + { + if ($db_conn === TRUE) + { + $db_conn = ''; + } + + $CI->load->database($db_conn, FALSE, TRUE); + } + + if ( ! class_exists('CI_Model')) + { + load_class('Model', 'core'); + } + + require_once($mod_path.'models/'.$path.$model.'.php'); + + $model = ucfirst($model); + + $CI->$name = new $model(); + + $this->_ci_models[] = $name; + return; + } + + // couldn't find the model + show_error('Unable to locate the model you have specified: '.$model); + } + + // -------------------------------------------------------------------- + + /** + * Database Loader + * + * @param string the DB credentials + * @param bool whether to return the DB object + * @param bool whether to enable active record (this allows us to override the config setting) + * @return object + */ + public function database($params = '', $return = FALSE, $active_record = NULL) + { + // Grab the super object + $CI =& get_instance(); + + // Do we even need to load the database class? + if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db)) + { + return FALSE; + } + + require_once(BASEPATH.'database/DB.php'); + + if ($return === TRUE) + { + return DB($params, $active_record); + } + + // Initialize the db variable. Needed to prevent + // reference errors with some configurations + $CI->db = ''; + + // Load the DB class + $CI->db =& DB($params, $active_record); + } + + // -------------------------------------------------------------------- + + /** + * Load the Utilities Class + * + * @return string + */ + public function dbutil() + { + if ( ! class_exists('CI_DB')) + { + $this->database(); + } + + $CI =& get_instance(); + + // for backwards compatibility, load dbforge so we can extend dbutils off it + // this use is deprecated and strongly discouraged + $CI->load->dbforge(); + + require_once(BASEPATH.'database/DB_utility.php'); + require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility.php'); + $class = 'CI_DB_'.$CI->db->dbdriver.'_utility'; + + $CI->dbutil = new $class(); + } + + // -------------------------------------------------------------------- + + /** + * Load the Database Forge Class + * + * @return string + */ + public function dbforge() + { + if ( ! class_exists('CI_DB')) + { + $this->database(); + } + + $CI =& get_instance(); + + require_once(BASEPATH.'database/DB_forge.php'); + require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge.php'); + $class = 'CI_DB_'.$CI->db->dbdriver.'_forge'; + + $CI->dbforge = new $class(); + } + + // -------------------------------------------------------------------- + + /** + * Load View + * + * This function is used to load a "view" file. It has three parameters: + * + * 1. The name of the "view" file to be included. + * 2. An associative array of data to be extracted for use in the view. + * 3. TRUE/FALSE - whether to return the data or load it. In + * some cases it's advantageous to be able to return data so that + * a developer can process it in some way. + * + * @param string + * @param array + * @param bool + * @return void + */ + public function view($view, $vars = array(), $return = FALSE) + { + return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return)); + } + + // -------------------------------------------------------------------- + + /** + * Load File + * + * This is a generic file loader + * + * @param string + * @param bool + * @return string + */ + public function file($path, $return = FALSE) + { + return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return)); + } + + // -------------------------------------------------------------------- + + /** + * Set Variables + * + * Once variables are set they become available within + * the controller class and its "view" files. + * + * @param array + * @param string + * @return void + */ + public function vars($vars = array(), $val = '') + { + if ($val != '' AND is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) AND count($vars) > 0) + { + foreach ($vars as $key => $val) + { + $this->_ci_cached_vars[$key] = $val; + } + } + } + + // -------------------------------------------------------------------- + + /** + * Get Variable + * + * Check if a variable is set and retrieve it. + * + * @param array + * @return void + */ + public function get_var($key) + { + return isset($this->_ci_cached_vars[$key]) ? $this->_ci_cached_vars[$key] : NULL; + } + + // -------------------------------------------------------------------- + + /** + * Load Helper + * + * This function loads the specified helper file. + * + * @param mixed + * @return void + */ + public function helper($helpers = array()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + $ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.'.php'; + + // Is this a helper extension request? + if (file_exists($ext_helper)) + { + $base_helper = BASEPATH.'helpers/'.$helper.'.php'; + + if ( ! file_exists($base_helper)) + { + show_error('Unable to load the requested file: helpers/'.$helper.'.php'); + } + + include_once($ext_helper); + include_once($base_helper); + + $this->_ci_helpers[$helper] = TRUE; + log_message('debug', 'Helper loaded: '.$helper); + continue; + } + + // Try to load the helper + foreach ($this->_ci_helper_paths as $path) + { + if (file_exists($path.'helpers/'.$helper.'.php')) + { + include_once($path.'helpers/'.$helper.'.php'); + + $this->_ci_helpers[$helper] = TRUE; + log_message('debug', 'Helper loaded: '.$helper); + break; + } + } + + // unable to load the helper + if ( ! isset($this->_ci_helpers[$helper])) + { + show_error('Unable to load the requested file: helpers/'.$helper.'.php'); + } + } + } + + // -------------------------------------------------------------------- + + /** + * Load Helpers + * + * This is simply an alias to the above function in case the + * user has written the plural form of this function. + * + * @param array + * @return void + */ + public function helpers($helpers = array()) + { + $this->helper($helpers); + } + + // -------------------------------------------------------------------- + + /** + * Loads a language file + * + * @param array + * @param string + * @return void + */ + public function language($file = array(), $lang = '') + { + $CI =& get_instance(); + + if ( ! is_array($file)) + { + $file = array($file); + } + + foreach ($file as $langfile) + { + $CI->lang->load($langfile, $lang); + } + } + + // -------------------------------------------------------------------- + + /** + * Loads a config file + * + * @param string + * @param bool + * @param bool + * @return void + */ + public function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) + { + $CI =& get_instance(); + $CI->config->load($file, $use_sections, $fail_gracefully); + } + + // -------------------------------------------------------------------- + + /** + * Driver + * + * Loads a driver library + * + * @param string the name of the class + * @param mixed the optional parameters + * @param string an optional object name + * @return void + */ + public function driver($library = '', $params = NULL, $object_name = NULL) + { + if ( ! class_exists('CI_Driver_Library')) + { + // we aren't instantiating an object here, that'll be done by the Library itself + require BASEPATH.'libraries/Driver.php'; + } + + if ($library == '') + { + return FALSE; + } + + // We can save the loader some time since Drivers will *always* be in a subfolder, + // and typically identically named to the library + if ( ! strpos($library, '/')) + { + $library = ucfirst($library).'/'.$library; + } + + return $this->library($library, $params, $object_name); + } + + // -------------------------------------------------------------------- + + /** + * Add Package Path + * + * Prepends a parent path to the library, model, helper, and config path arrays + * + * @param string + * @param boolean + * @return void + */ + public function add_package_path($path, $view_cascade=TRUE) + { + $path = rtrim($path, '/').'/'; + + array_unshift($this->_ci_library_paths, $path); + array_unshift($this->_ci_model_paths, $path); + array_unshift($this->_ci_helper_paths, $path); + + $this->_ci_view_paths = array($path.'views/' => $view_cascade) + $this->_ci_view_paths; + + // Add config file path + $config =& $this->_ci_get_component('config'); + array_unshift($config->_config_paths, $path); + } + + // -------------------------------------------------------------------- + + /** + * Get Package Paths + * + * Return a list of all package paths, by default it will ignore BASEPATH. + * + * @param string + * @return void + */ + public function get_package_paths($include_base = FALSE) + { + return $include_base === TRUE ? $this->_ci_library_paths : $this->_ci_model_paths; + } + + // -------------------------------------------------------------------- + + /** + * Remove Package Path + * + * Remove a path from the library, model, and helper path arrays if it exists + * If no path is provided, the most recently added path is removed. + * + * @param type + * @param bool + * @return type + */ + public function remove_package_path($path = '', $remove_config_path = TRUE) + { + $config =& $this->_ci_get_component('config'); + + if ($path == '') + { + $void = array_shift($this->_ci_library_paths); + $void = array_shift($this->_ci_model_paths); + $void = array_shift($this->_ci_helper_paths); + $void = array_shift($this->_ci_view_paths); + $void = array_shift($config->_config_paths); + } + else + { + $path = rtrim($path, '/').'/'; + foreach (array('_ci_library_paths', '_ci_model_paths', '_ci_helper_paths') as $var) + { + if (($key = array_search($path, $this->{$var})) !== FALSE) + { + unset($this->{$var}[$key]); + } + } + + if (isset($this->_ci_view_paths[$path.'views/'])) + { + unset($this->_ci_view_paths[$path.'views/']); + } + + if (($key = array_search($path, $config->_config_paths)) !== FALSE) + { + unset($config->_config_paths[$key]); + } + } + + // make sure the application default paths are still in the array + $this->_ci_library_paths = array_unique(array_merge($this->_ci_library_paths, array(APPPATH, BASEPATH))); + $this->_ci_helper_paths = array_unique(array_merge($this->_ci_helper_paths, array(APPPATH, BASEPATH))); + $this->_ci_model_paths = array_unique(array_merge($this->_ci_model_paths, array(APPPATH))); + $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(APPPATH.'views/' => TRUE)); + $config->_config_paths = array_unique(array_merge($config->_config_paths, array(APPPATH))); + } + + // -------------------------------------------------------------------- + + /** + * Loader + * + * This function is used to load views and files. + * Variables are prefixed with _ci_ to avoid symbol collision with + * variables made available to view files + * + * @param array + * @return void + */ + protected function _ci_load($_ci_data) + { + // Set the default data variables + foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val) + { + $$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val]; + } + + $file_exists = FALSE; + + // Set the path to the requested file + if ($_ci_path != '') + { + $_ci_x = explode('/', $_ci_path); + $_ci_file = end($_ci_x); + } + else + { + $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION); + $_ci_file = ($_ci_ext == '') ? $_ci_view.'.php' : $_ci_view; + + foreach ($this->_ci_view_paths as $view_file => $cascade) + { + if (file_exists($view_file.$_ci_file)) + { + $_ci_path = $view_file.$_ci_file; + $file_exists = TRUE; + break; + } + + if ( ! $cascade) + { + break; + } + } + } + + if ( ! $file_exists && ! file_exists($_ci_path)) + { + show_error('Unable to load the requested file: '.$_ci_file); + } + + // This allows anything loaded using $this->load (views, files, etc.) + // to become accessible from within the Controller and Model functions. + + $_ci_CI =& get_instance(); + foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var) + { + if ( ! isset($this->$_ci_key)) + { + $this->$_ci_key =& $_ci_CI->$_ci_key; + } + } + + /* + * Extract and cache variables + * + * You can either set variables using the dedicated $this->load_vars() + * function or via the second parameter of this function. We'll merge + * the two types and cache them so that views that are embedded within + * other views can have access to these variables. + */ + if (is_array($_ci_vars)) + { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); + } + extract($this->_ci_cached_vars); + + /* + * Buffer the output + * + * We buffer the output for two reasons: + * 1. Speed. You get a significant speed boost. + * 2. So that the final rendered template can be + * post-processed by the output class. Why do we + * need post processing? For one thing, in order to + * show the elapsed page load time. Unless we + * can intercept the content right before it's sent to + * the browser and then stop the timer it won't be accurate. + */ + ob_start(); + + // If the PHP installation does not support short tags we'll + // do a little string replacement, changing the short tags + // to standard PHP echo statements. + + if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE) + { + echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace(' $this->_ci_ob_level + 1) + { + ob_end_flush(); + } + else + { + $_ci_CI->output->append_output(ob_get_contents()); + @ob_end_clean(); + } + } + + // -------------------------------------------------------------------- + + /** + * Load class + * + * This function loads the requested class. + * + * @param string the item that is being loaded + * @param mixed any additional parameters + * @param string an optional object name + * @return void + */ + protected function _ci_load_class($class, $params = NULL, $object_name = NULL) + { + // Get the class name, and while we're at it trim any slashes. + // The directory path can be included as part of the class name, + // but we don't want a leading slash + $class = str_replace('.php', '', trim($class, '/')); + + // Was the path included with the class name? + // We look for a slash to determine this + $subdir = ''; + if (($last_slash = strrpos($class, '/')) !== FALSE) + { + // Extract the path + $subdir = substr($class, 0, $last_slash + 1); + + // Get the filename from the path + $class = substr($class, $last_slash + 1); + } + + // We'll test for both lowercase and capitalized versions of the file name + foreach (array(ucfirst($class), strtolower($class)) as $class) + { + $subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php'; + + // Is this a class extension request? + if (file_exists($subclass)) + { + $baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php'; + + if ( ! file_exists($baseclass)) + { + log_message('error', "Unable to load the requested class: ".$class); + show_error("Unable to load the requested class: ".$class); + } + + // Safety: Was the class already loaded by a previous call? + if (in_array($subclass, $this->_ci_loaded_files)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ( ! is_null($object_name)) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); + } + } + + $is_duplicate = TRUE; + log_message('debug', $class." class already loaded. Second attempt ignored."); + return; + } + + include_once($baseclass); + include_once($subclass); + $this->_ci_loaded_files[] = $subclass; + + return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); + } + + // Lets search for the requested library file and load it. + $is_duplicate = FALSE; + foreach ($this->_ci_library_paths as $path) + { + $filepath = $path.'libraries/'.$subdir.$class.'.php'; + + // Does the file exist? No? Bummer... + if ( ! file_exists($filepath)) + { + continue; + } + + // Safety: Was the class already loaded by a previous call? + if (in_array($filepath, $this->_ci_loaded_files)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ( ! is_null($object_name)) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_class($class, '', $params, $object_name); + } + } + + $is_duplicate = TRUE; + log_message('debug', $class." class already loaded. Second attempt ignored."); + return; + } + + include_once($filepath); + $this->_ci_loaded_files[] = $filepath; + return $this->_ci_init_class($class, '', $params, $object_name); + } + + } // END FOREACH + + // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified? + if ($subdir == '') + { + $path = strtolower($class).'/'.$class; + return $this->_ci_load_class($path, $params); + } + + // If we got this far we were unable to find the requested class. + // We do not issue errors if the load call failed due to a duplicate request + if ($is_duplicate == FALSE) + { + log_message('error', "Unable to load the requested class: ".$class); + show_error("Unable to load the requested class: ".$class); + } + } + + // -------------------------------------------------------------------- + + /** + * Instantiates a class + * + * @param string + * @param string + * @param bool + * @param string an optional object name + * @return null + */ + protected function _ci_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL) + { + // Is there an associated config file for this class? Note: these should always be lowercase + if ($config === NULL) + { + // Fetch the config paths containing any package paths + $config_component = $this->_ci_get_component('config'); + + if (is_array($config_component->_config_paths)) + { + // Break on the first found file, thus package files + // are not overridden by default paths + foreach ($config_component->_config_paths as $path) + { + // We test for both uppercase and lowercase, for servers that + // are case-sensitive with regard to file names. Check for environment + // first, global next + if (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php')) + { + include($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'); + break; + } + elseif (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php')) + { + include($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'); + break; + } + elseif (file_exists($path .'config/'.strtolower($class).'.php')) + { + include($path .'config/'.strtolower($class).'.php'); + break; + } + elseif (file_exists($path .'config/'.ucfirst(strtolower($class)).'.php')) + { + include($path .'config/'.ucfirst(strtolower($class)).'.php'); + break; + } + } + } + } + + if ($prefix == '') + { + if (class_exists('CI_'.$class)) + { + $name = 'CI_'.$class; + } + elseif (class_exists(config_item('subclass_prefix').$class)) + { + $name = config_item('subclass_prefix').$class; + } + else + { + $name = $class; + } + } + else + { + $name = $prefix.$class; + } + + // Is the class name valid? + if ( ! class_exists($name)) + { + log_message('error', "Non-existent class: ".$name); + show_error("Non-existent class: ".$class); + } + + // Set the variable name we will assign the class to + // Was a custom class name supplied? If so we'll use it + $class = strtolower($class); + + if (is_null($object_name)) + { + $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class]; + } + else + { + $classvar = $object_name; + } + + // Save the class name and object name + $this->_ci_classes[$class] = $classvar; + + // Instantiate the class + $CI =& get_instance(); + if ($config !== NULL) + { + $CI->$classvar = new $name($config); + } + else + { + $CI->$classvar = new $name; + } + } + + // -------------------------------------------------------------------- + + /** + * Autoloader + * + * The config/autoload.php file contains an array that permits sub-systems, + * libraries, and helpers to be loaded automatically. + * + * @param array + * @return void + */ + private function _ci_autoloader() + { + if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'); + } + else + { + include(APPPATH.'config/autoload.php'); + } + + if ( ! isset($autoload)) + { + return FALSE; + } + + // Autoload packages + if (isset($autoload['packages'])) + { + foreach ($autoload['packages'] as $package_path) + { + $this->add_package_path($package_path); + } + } + + // Load any custom config file + if (count($autoload['config']) > 0) + { + $CI =& get_instance(); + foreach ($autoload['config'] as $key => $val) + { + $CI->config->load($val); + } + } + + // Autoload helpers and languages + foreach (array('helper', 'language') as $type) + { + if (isset($autoload[$type]) AND count($autoload[$type]) > 0) + { + $this->$type($autoload[$type]); + } + } + + // A little tweak to remain backward compatible + // The $autoload['core'] item was deprecated + if ( ! isset($autoload['libraries']) AND isset($autoload['core'])) + { + $autoload['libraries'] = $autoload['core']; + } + + // Load libraries + if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0) + { + // Load the database driver. + if (in_array('database', $autoload['libraries'])) + { + $this->database(); + $autoload['libraries'] = array_diff($autoload['libraries'], array('database')); + } + + // Load all other libraries + foreach ($autoload['libraries'] as $item) + { + $this->library($item); + } + } + + // Autoload models + if (isset($autoload['model'])) + { + $this->model($autoload['model']); + } + } + + // -------------------------------------------------------------------- + + /** + * Object to Array + * + * Takes an object as input and converts the class variables to array key/vals + * + * @param object + * @return array + */ + protected function _ci_object_to_array($object) + { + return (is_object($object)) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * Get a reference to a specific library or model + * + * @param string + * @return bool + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function preps the name of various items to make loading them more reliable. + * + * @param mixed + * @param string + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace('.php', '', str_replace($extension, '', $val)).$extension); + } + + return $filename; + } + } +} + +/* End of file Loader.php */ +/* Location: ./system/core/Loader.php */ \ No newline at end of file diff --git a/api/system/core/Model.php b/api/system/core/Model.php new file mode 100644 index 0000000..e15ffbe --- /dev/null +++ b/api/system/core/Model.php @@ -0,0 +1,57 @@ +$key; + } +} +// END Model Class + +/* End of file Model.php */ +/* Location: ./system/core/Model.php */ \ No newline at end of file diff --git a/api/system/core/Output.php b/api/system/core/Output.php new file mode 100644 index 0000000..ccecafd --- /dev/null +++ b/api/system/core/Output.php @@ -0,0 +1,574 @@ +_zlib_oc = @ini_get('zlib.output_compression'); + + // Get mime types for later + if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) + { + include APPPATH.'config/'.ENVIRONMENT.'/mimes.php'; + } + else + { + include APPPATH.'config/mimes.php'; + } + + + $this->mime_types = $mimes; + + log_message('debug', "Output Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Get Output + * + * Returns the current output string + * + * @access public + * @return string + */ + function get_output() + { + return $this->final_output; + } + + // -------------------------------------------------------------------- + + /** + * Set Output + * + * Sets the output string + * + * @access public + * @param string + * @return void + */ + function set_output($output) + { + $this->final_output = $output; + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Append Output + * + * Appends data onto the output string + * + * @access public + * @param string + * @return void + */ + function append_output($output) + { + if ($this->final_output == '') + { + $this->final_output = $output; + } + else + { + $this->final_output .= $output; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Header + * + * Lets you set a server header which will be outputted with the final display. + * + * Note: If a file is cached, headers will not be sent. We need to figure out + * how to permit header data to be saved with the cache data... + * + * @access public + * @param string + * @param bool + * @return void + */ + function set_header($header, $replace = TRUE) + { + // If zlib.output_compression is enabled it will compress the output, + // but it will not modify the content-length header to compensate for + // the reduction, causing the browser to hang waiting for more data. + // We'll just skip content-length in those cases. + + if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0) + { + return; + } + + $this->headers[] = array($header, $replace); + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Content Type Header + * + * @access public + * @param string extension of the file we're outputting + * @return void + */ + function set_content_type($mime_type) + { + if (strpos($mime_type, '/') === FALSE) + { + $extension = ltrim($mime_type, '.'); + + // Is this extension supported? + if (isset($this->mime_types[$extension])) + { + $mime_type =& $this->mime_types[$extension]; + + if (is_array($mime_type)) + { + $mime_type = current($mime_type); + } + } + } + + $header = 'Content-Type: '.$mime_type; + + $this->headers[] = array($header, TRUE); + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set HTTP Status Header + * moved to Common procedural functions in 1.7.2 + * + * @access public + * @param int the status code + * @param string + * @return void + */ + function set_status_header($code = 200, $text = '') + { + set_status_header($code, $text); + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Enable/disable Profiler + * + * @access public + * @param bool + * @return void + */ + function enable_profiler($val = TRUE) + { + $this->enable_profiler = (is_bool($val)) ? $val : TRUE; + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Profiler Sections + * + * Allows override of default / config settings for Profiler section display + * + * @access public + * @param array + * @return void + */ + function set_profiler_sections($sections) + { + foreach ($sections as $section => $enable) + { + $this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Cache + * + * @access public + * @param integer + * @return void + */ + function cache($time) + { + $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time; + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display Output + * + * All "view" data is automatically put into this variable by the controller class: + * + * $this->final_output + * + * This function sends the finalized output data to the browser along + * with any server headers and profile data. It also stops the + * benchmark timer so the page rendering speed and memory usage can be shown. + * + * @access public + * @param string + * @return mixed + */ + function _display($output = '') + { + // Note: We use globals because we can't use $CI =& get_instance() + // since this function is sometimes called by the caching mechanism, + // which happens before the CI super object is available. + global $BM, $CFG; + + // Grab the super object if we can. + if (class_exists('CI_Controller')) + { + $CI =& get_instance(); + } + + // -------------------------------------------------------------------- + + // Set the output data + if ($output == '') + { + $output =& $this->final_output; + } + + // -------------------------------------------------------------------- + + // Do we need to write a cache file? Only if the controller does not have its + // own _output() method and we are not dealing with a cache file, which we + // can determine by the existence of the $CI object above + if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output')) + { + $this->_write_cache($output); + } + + // -------------------------------------------------------------------- + + // Parse out the elapsed time and memory usage, + // then swap the pseudo-variables with the data + + $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end'); + + if ($this->parse_exec_vars === TRUE) + { + $memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB'; + + $output = str_replace('{elapsed_time}', $elapsed, $output); + $output = str_replace('{memory_usage}', $memory, $output); + } + + // -------------------------------------------------------------------- + + // Is compression requested? + if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE) + { + if (extension_loaded('zlib')) + { + if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) + { + ob_start('ob_gzhandler'); + } + } + } + + // -------------------------------------------------------------------- + + // Are there any server headers to send? + if (count($this->headers) > 0) + { + foreach ($this->headers as $header) + { + @header($header[0], $header[1]); + } + } + + // -------------------------------------------------------------------- + + // Does the $CI object exist? + // If not we know we are dealing with a cache file so we'll + // simply echo out the data and exit. + if ( ! isset($CI)) + { + echo $output; + log_message('debug', "Final output sent to browser"); + log_message('debug', "Total execution time: ".$elapsed); + return TRUE; + } + + // -------------------------------------------------------------------- + + // Do we need to generate profile data? + // If so, load the Profile class and run it. + if ($this->enable_profiler == TRUE) + { + $CI->load->library('profiler'); + + if ( ! empty($this->_profiler_sections)) + { + $CI->profiler->set_sections($this->_profiler_sections); + } + + // If the output data contains closing and tags + // we will remove them and add them back after we insert the profile data + if (preg_match("|.*?|is", $output)) + { + $output = preg_replace("|.*?|is", '', $output); + $output .= $CI->profiler->run(); + $output .= ''; + } + else + { + $output .= $CI->profiler->run(); + } + } + + // -------------------------------------------------------------------- + + // Does the controller contain a function named _output()? + // If so send the output there. Otherwise, echo it. + if (method_exists($CI, '_output')) + { + $CI->_output($output); + } + else + { + echo $output; // Send it to the browser! + } + + log_message('debug', "Final output sent to browser"); + log_message('debug', "Total execution time: ".$elapsed); + } + + // -------------------------------------------------------------------- + + /** + * Write a Cache File + * + * @access public + * @param string + * @return void + */ + function _write_cache($output) + { + $CI =& get_instance(); + $path = $CI->config->item('cache_path'); + + $cache_path = ($path == '') ? APPPATH.'cache/' : $path; + + if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path)) + { + log_message('error', "Unable to write cache file: ".$cache_path); + return; + } + + $uri = $CI->config->item('base_url'). + $CI->config->item('index_page'). + $CI->uri->uri_string(); + + $cache_path .= md5($uri); + + if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE)) + { + log_message('error', "Unable to write cache file: ".$cache_path); + return; + } + + $expire = time() + ($this->cache_expiration * 60); + + if (flock($fp, LOCK_EX)) + { + fwrite($fp, $expire.'TS--->'.$output); + flock($fp, LOCK_UN); + } + else + { + log_message('error', "Unable to secure a file lock for file at: ".$cache_path); + return; + } + fclose($fp); + @chmod($cache_path, FILE_WRITE_MODE); + + log_message('debug', "Cache file written: ".$cache_path); + } + + // -------------------------------------------------------------------- + + /** + * Update/serve a cached file + * + * @access public + * @param object config class + * @param object uri class + * @return void + */ + function _display_cache(&$CFG, &$URI) + { + $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path'); + + // Build the file path. The file name is an MD5 hash of the full URI + $uri = $CFG->item('base_url'). + $CFG->item('index_page'). + $URI->uri_string; + + $filepath = $cache_path.md5($uri); + + if ( ! @file_exists($filepath)) + { + return FALSE; + } + + if ( ! $fp = @fopen($filepath, FOPEN_READ)) + { + return FALSE; + } + + flock($fp, LOCK_SH); + + $cache = ''; + if (filesize($filepath) > 0) + { + $cache = fread($fp, filesize($filepath)); + } + + flock($fp, LOCK_UN); + fclose($fp); + + // Strip out the embedded timestamp + if ( ! preg_match("/(\d+TS--->)/", $cache, $match)) + { + return FALSE; + } + + // Has the file expired? If so we'll delete it. + if (time() >= trim(str_replace('TS--->', '', $match['1']))) + { + if (is_really_writable($cache_path)) + { + @unlink($filepath); + log_message('debug', "Cache file has expired. File deleted"); + return FALSE; + } + } + + // Display the cache + $this->_display(str_replace($match['0'], '', $cache)); + log_message('debug', "Cache file is current. Sending it to browser."); + return TRUE; + } + + +} +// END Output Class + +/* End of file Output.php */ +/* Location: ./system/core/Output.php */ \ No newline at end of file diff --git a/api/system/core/Router.php b/api/system/core/Router.php new file mode 100644 index 0000000..6da6674 --- /dev/null +++ b/api/system/core/Router.php @@ -0,0 +1,522 @@ +config =& load_class('Config', 'core'); + $this->uri =& load_class('URI', 'core'); + log_message('debug', "Router Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Set the route mapping + * + * This function determines what should be served based on the URI request, + * as well as any "routes" that have been set in the routing config file. + * + * @access private + * @return void + */ + function _set_routing() + { + // Are query strings enabled in the config file? Normally CI doesn't utilize query strings + // since URI segments are more search-engine friendly, but they can optionally be used. + // If this feature is enabled, we will gather the directory/class/method a little differently + $segments = array(); + if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')])) + { + if (isset($_GET[$this->config->item('directory_trigger')])) + { + $this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')]))); + $segments[] = $this->fetch_directory(); + } + + if (isset($_GET[$this->config->item('controller_trigger')])) + { + $this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')]))); + $segments[] = $this->fetch_class(); + } + + if (isset($_GET[$this->config->item('function_trigger')])) + { + $this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')]))); + $segments[] = $this->fetch_method(); + } + } + + // Load the routes.php file. + if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); + } + elseif (is_file(APPPATH.'config/routes.php')) + { + include(APPPATH.'config/routes.php'); + } + + $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route; + unset($route); + + // Set the default controller so we can display it in the event + // the URI doesn't correlated to a valid controller. + $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']); + + // Were there any query string segments? If so, we'll validate them and bail out since we're done. + if (count($segments) > 0) + { + return $this->_validate_request($segments); + } + + // Fetch the complete URI string + $this->uri->_fetch_uri_string(); + + // Is there a URI string? If not, the default controller specified in the "routes" file will be shown. + if ($this->uri->uri_string == '') + { + return $this->_set_default_controller(); + } + + // Do we need to remove the URL suffix? + $this->uri->_remove_url_suffix(); + + // Compile the segments into an array + $this->uri->_explode_segments(); + + // Parse any custom routing that may exist + $this->_parse_routes(); + + // Re-index the segment array so that it starts with 1 rather than 0 + $this->uri->_reindex_segments(); + } + + // -------------------------------------------------------------------- + + /** + * Set the default controller + * + * @access private + * @return void + */ + function _set_default_controller() + { + if ($this->default_controller === FALSE) + { + show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file."); + } + // Is the method being specified? + if (strpos($this->default_controller, '/') !== FALSE) + { + $x = explode('/', $this->default_controller); + + $this->set_class($x[0]); + $this->set_method($x[1]); + $this->_set_request($x); + } + else + { + $this->set_class($this->default_controller); + $this->set_method('index'); + $this->_set_request(array($this->default_controller, 'index')); + } + + // re-index the routed segments array so it starts with 1 rather than 0 + $this->uri->_reindex_segments(); + + log_message('debug', "No URI present. Default controller set."); + } + + // -------------------------------------------------------------------- + + /** + * Set the Route + * + * This function takes an array of URI segments as + * input, and sets the current class/method + * + * @access private + * @param array + * @param bool + * @return void + */ + function _set_request($segments = array()) + { + $segments = $this->_validate_request($segments); + + if (count($segments) == 0) + { + return $this->_set_default_controller(); + } + + $this->set_class($segments[0]); + + if (isset($segments[1])) + { + // A standard method request + $this->set_method($segments[1]); + } + else + { + // This lets the "routed" segment array identify that the default + // index method is being used. + $segments[1] = 'index'; + } + + // Update our "routed" segment array to contain the segments. + // Note: If there is no custom routing, this array will be + // identical to $this->uri->segments + $this->uri->rsegments = $segments; + } + + // -------------------------------------------------------------------- + + /** + * Validates the supplied segments. Attempts to determine the path to + * the controller. + * + * @access private + * @param array + * @return array + */ + function _validate_request($segments) + { + if (count($segments) == 0) + { + return $segments; + } + + // Does the requested controller exist in the root folder? + if (file_exists(APPPATH.'controllers/'.$segments[0].'.php')) + { + return $segments; + } + + // Is the controller in a sub-folder? + if (is_dir(APPPATH.'controllers/'.$segments[0])) + { + // Set the directory and remove it from the segment array + $this->set_directory($segments[0]); + $segments = array_slice($segments, 1); + + if (count($segments) > 0) + { + // Does the requested controller exist in the sub-folder? + if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php')) + { + if ( ! empty($this->routes['404_override'])) + { + $x = explode('/', $this->routes['404_override']); + + $this->set_directory(''); + $this->set_class($x[0]); + $this->set_method(isset($x[1]) ? $x[1] : 'index'); + + return $x; + } + else + { + show_404($this->fetch_directory().$segments[0]); + } + } + } + else + { + // Is the method being specified in the route? + if (strpos($this->default_controller, '/') !== FALSE) + { + $x = explode('/', $this->default_controller); + + $this->set_class($x[0]); + $this->set_method($x[1]); + } + else + { + $this->set_class($this->default_controller); + $this->set_method('index'); + } + + // Does the default controller exist in the sub-folder? + if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) + { + $this->directory = ''; + return array(); + } + + } + + return $segments; + } + + + // If we've gotten this far it means that the URI does not correlate to a valid + // controller class. We will now see if there is an override + if ( ! empty($this->routes['404_override'])) + { + $x = explode('/', $this->routes['404_override']); + + $this->set_class($x[0]); + $this->set_method(isset($x[1]) ? $x[1] : 'index'); + + return $x; + } + + + // Nothing else to do at this point but show a 404 + show_404($segments[0]); + } + + // -------------------------------------------------------------------- + + /** + * Parse Routes + * + * This function matches any routes that may exist in + * the config/routes.php file against the URI to + * determine if the class/method need to be remapped. + * + * @access private + * @return void + */ + function _parse_routes() + { + // Turn the segment array into a URI string + $uri = implode('/', $this->uri->segments); + + // Is there a literal match? If so we're done + if (isset($this->routes[$uri])) + { + return $this->_set_request(explode('/', $this->routes[$uri])); + } + + // Loop through the route array looking for wild-cards + foreach ($this->routes as $key => $val) + { + // Convert wild-cards to RegEx + $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key)); + + // Does the RegEx match? + if (preg_match('#^'.$key.'$#', $uri)) + { + // Do we have a back-reference? + if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) + { + $val = preg_replace('#^'.$key.'$#', $val, $uri); + } + + return $this->_set_request(explode('/', $val)); + } + } + + // If we got this far it means we didn't encounter a + // matching route so we'll set the site default route + $this->_set_request($this->uri->segments); + } + + // -------------------------------------------------------------------- + + /** + * Set the class name + * + * @access public + * @param string + * @return void + */ + function set_class($class) + { + $this->class = str_replace(array('/', '.'), '', $class); + } + + // -------------------------------------------------------------------- + + /** + * Fetch the current class + * + * @access public + * @return string + */ + function fetch_class() + { + return $this->class; + } + + // -------------------------------------------------------------------- + + /** + * Set the method name + * + * @access public + * @param string + * @return void + */ + function set_method($method) + { + $this->method = $method; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the current method + * + * @access public + * @return string + */ + function fetch_method() + { + if ($this->method == $this->fetch_class()) + { + return 'index'; + } + + return $this->method; + } + + // -------------------------------------------------------------------- + + /** + * Set the directory name + * + * @access public + * @param string + * @return void + */ + function set_directory($dir) + { + $this->directory = str_replace(array('/', '.'), '', $dir).'/'; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the sub-directory (if any) that contains the requested controller class + * + * @access public + * @return string + */ + function fetch_directory() + { + return $this->directory; + } + + // -------------------------------------------------------------------- + + /** + * Set the controller overrides + * + * @access public + * @param array + * @return null + */ + function _set_overrides($routing) + { + if ( ! is_array($routing)) + { + return; + } + + if (isset($routing['directory'])) + { + $this->set_directory($routing['directory']); + } + + if (isset($routing['controller']) AND $routing['controller'] != '') + { + $this->set_class($routing['controller']); + } + + if (isset($routing['function'])) + { + $routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function']; + $this->set_method($routing['function']); + } + } + + +} +// END Router Class + +/* End of file Router.php */ +/* Location: ./system/core/Router.php */ \ No newline at end of file diff --git a/api/system/core/Security.php b/api/system/core/Security.php new file mode 100644 index 0000000..b0d39b9 --- /dev/null +++ b/api/system/core/Security.php @@ -0,0 +1,875 @@ + '[removed]', + 'document.write' => '[removed]', + '.parentNode' => '[removed]', + '.innerHTML' => '[removed]', + 'window.location' => '[removed]', + '-moz-binding' => '[removed]', + '' => '-->', + ' '<![CDATA[', + '' => '<comment>' + ); + + /* never allowed, regex replacement */ + /** + * List of never allowed regex replacement + * + * @var array + * @access protected + */ + protected $_never_allowed_regex = array( + 'javascript\s*:', + 'expression\s*(\(|&\#40;)', // CSS and IE + 'vbscript\s*:', // IE, surprise! + 'Redirect\s+302', + "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?" + ); + + /** + * Constructor + * + * @return void + */ + public function __construct() + { + // Is CSRF protection enabled? + if (config_item('csrf_protection') === TRUE) + { + // CSRF config + foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key) + { + if (FALSE !== ($val = config_item($key))) + { + $this->{'_'.$key} = $val; + } + } + + // Append application specific cookie prefix + if (config_item('cookie_prefix')) + { + $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name; + } + + // Set the CSRF hash + $this->_csrf_set_hash(); + } + + log_message('debug', "Security Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Verify Cross Site Request Forgery Protection + * + * @return object + */ + public function csrf_verify() + { + // If it's not a POST request we will set the CSRF cookie + if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') + { + return $this->csrf_set_cookie(); + } + + // Do the tokens exist in both the _POST and _COOKIE arrays? + if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])) + { + $this->csrf_show_error(); + } + + // Do the tokens match? + if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) + { + $this->csrf_show_error(); + } + + // We kill this since we're done and we don't want to + // polute the _POST array + unset($_POST[$this->_csrf_token_name]); + + // Nothing should last forever + unset($_COOKIE[$this->_csrf_cookie_name]); + $this->_csrf_set_hash(); + $this->csrf_set_cookie(); + + log_message('debug', 'CSRF token verified'); + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Cross Site Request Forgery Protection Cookie + * + * @return object + */ + public function csrf_set_cookie() + { + $expire = time() + $this->_csrf_expire; + $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0; + + if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off')) + { + return FALSE; + } + + setcookie($this->_csrf_cookie_name, $this->_csrf_hash, $expire, config_item('cookie_path'), config_item('cookie_domain'), $secure_cookie); + + log_message('debug', "CRSF cookie Set"); + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Show CSRF Error + * + * @return void + */ + public function csrf_show_error() + { + show_error('The action you have requested is not allowed.'); + } + + // -------------------------------------------------------------------- + + /** + * Get CSRF Hash + * + * Getter Method + * + * @return string self::_csrf_hash + */ + public function get_csrf_hash() + { + return $this->_csrf_hash; + } + + // -------------------------------------------------------------------- + + /** + * Get CSRF Token Name + * + * Getter Method + * + * @return string self::csrf_token_name + */ + public function get_csrf_token_name() + { + return $this->_csrf_token_name; + } + + // -------------------------------------------------------------------- + + /** + * XSS Clean + * + * Sanitizes data so that Cross Site Scripting Hacks can be + * prevented. This function does a fair amount of work but + * it is extremely thorough, designed to prevent even the + * most obscure XSS attempts. Nothing is ever 100% foolproof, + * of course, but I haven't been able to get anything passed + * the filter. + * + * Note: This function should only be used to deal with data + * upon submission. It's not something that should + * be used for general runtime processing. + * + * This function was based in part on some code and ideas I + * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention + * + * To help develop this script I used this great list of + * vulnerabilities along with a few other hacks I've + * harvested from examining vulnerabilities in other programs: + * http://ha.ckers.org/xss.html + * + * @param mixed string or array + * @param bool + * @return string + */ + public function xss_clean($str, $is_image = FALSE) + { + /* + * Is the string an array? + * + */ + if (is_array($str)) + { + while (list($key) = each($str)) + { + $str[$key] = $this->xss_clean($str[$key]); + } + + return $str; + } + + /* + * Remove Invisible Characters + */ + $str = remove_invisible_characters($str); + + // Validate Entities in URLs + $str = $this->_validate_entities($str); + + /* + * URL Decode + * + * Just in case stuff like this is submitted: + * + * Google + * + * Note: Use rawurldecode() so it does not remove plus signs + * + */ + $str = rawurldecode($str); + + /* + * Convert character entities to ASCII + * + * This permits our tests below to work reliably. + * We only convert entities that are within tags since + * these are the ones that will pose security problems. + * + */ + + $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str); + + $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str); + + /* + * Remove Invisible Characters Again! + */ + $str = remove_invisible_characters($str); + + /* + * Convert all tabs to spaces + * + * This prevents strings like this: ja vascript + * NOTE: we deal with spaces between characters later. + * NOTE: preg_replace was found to be amazingly slow here on + * large blocks of data, so we use str_replace. + */ + + if (strpos($str, "\t") !== FALSE) + { + $str = str_replace("\t", ' ', $str); + } + + /* + * Capture converted string for later comparison + */ + $converted_string = $str; + + // Remove Strings that are never allowed + $str = $this->_do_never_allowed($str); + + /* + * Makes PHP tags safe + * + * Note: XML tags are inadvertently replaced too: + * + * '), array('<?', '?>'), $str); + } + + /* + * Compact any exploded words + * + * This corrects words like: j a v a s c r i p t + * These words are compacted back to their correct state. + */ + $words = array( + 'javascript', 'expression', 'vbscript', 'script', 'base64', + 'applet', 'alert', 'document', 'write', 'cookie', 'window' + ); + + foreach ($words as $word) + { + $temp = ''; + + for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++) + { + $temp .= substr($word, $i, 1)."\s*"; + } + + // We only want to do this when it is followed by a non-word character + // That way valid stuff like "dealer to" does not become "dealerto" + $str = preg_replace_callback('#('.substr($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str); + } + + /* + * Remove disallowed Javascript in links or img tags + * We used to do some version comparisons and use of stripos for PHP5, + * but it is dog slow compared to these simplified non-capturing + * preg_match(), especially if the pattern exists in the string + */ + do + { + $original = $str; + + if (preg_match("/]*?)(>|$)#si", array($this, '_js_link_removal'), $str); + } + + if (preg_match("/]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str); + } + + if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str)) + { + $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str); + } + } + while($original != $str); + + unset($original); + + // Remove evil attributes such as style, onclick and xmlns + $str = $this->_remove_evil_attributes($str, $is_image); + + /* + * Sanitize naughty HTML elements + * + * If a tag containing any of the words in the list + * below is found, the tag gets converted to entities. + * + * So this: + * Becomes: <blink> + */ + $naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss'; + $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str); + + /* + * Sanitize naughty scripting elements + * + * Similar to above, only instead of looking for + * tags it looks for PHP and JavaScript commands + * that are disallowed. Rather than removing the + * code, it simply converts the parenthesis to entities + * rendering the code un-executable. + * + * For example: eval('some code') + * Becomes: eval('some code') + */ + $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str); + + + // Final clean up + // This adds a bit of extra precaution in case + // something got through the above filters + $str = $this->_do_never_allowed($str); + + /* + * Images are Handled in a Special Way + * - Essentially, we want to know that after all of the character + * conversion is done whether any unwanted, likely XSS, code was found. + * If not, we return TRUE, as the image is clean. + * However, if the string post-conversion does not matched the + * string post-removal of XSS, then it fails, as there was unwanted XSS + * code found and removed/changed during processing. + */ + + if ($is_image === TRUE) + { + return ($str == $converted_string) ? TRUE: FALSE; + } + + log_message('debug', "XSS Filtering completed"); + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Random Hash for protecting URLs + * + * @return string + */ + public function xss_hash() + { + if ($this->_xss_hash == '') + { + mt_srand(); + $this->_xss_hash = md5(time() + mt_rand(0, 1999999999)); + } + + return $this->_xss_hash; + } + + // -------------------------------------------------------------------- + + /** + * HTML Entities Decode + * + * This function is a replacement for html_entity_decode() + * + * The reason we are not using html_entity_decode() by itself is because + * while it is not technically correct to leave out the semicolon + * at the end of an entity most browsers will still interpret the entity + * correctly. html_entity_decode() does not convert entities without + * semicolons, so we are left with our own little solution here. Bummer. + * + * @param string + * @param string + * @return string + */ + public function entity_decode($str, $charset='UTF-8') + { + if (stristr($str, '&') === FALSE) + { + return $str; + } + + $str = html_entity_decode($str, ENT_COMPAT, $charset); + $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str); + return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str); + } + + // -------------------------------------------------------------------- + + /** + * Filename Security + * + * @param string + * @param bool + * @return string + */ + public function sanitize_filename($str, $relative_path = FALSE) + { + $bad = array( + "../", + "", + "<", + ">", + "'", + '"', + '&', + '$', + '#', + '{', + '}', + '[', + ']', + '=', + ';', + '?', + "%20", + "%22", + "%3c", // < + "%253c", // < + "%3e", // > + "%0e", // > + "%28", // ( + "%29", // ) + "%2528", // ( + "%26", // & + "%24", // $ + "%3f", // ? + "%3b", // ; + "%3d" // = + ); + + if ( ! $relative_path) + { + $bad[] = './'; + $bad[] = '/'; + } + + $str = remove_invisible_characters($str, FALSE); + return stripslashes(str_replace($bad, '', $str)); + } + + // ---------------------------------------------------------------- + + /** + * Compact Exploded Words + * + * Callback function for xss_clean() to remove whitespace from + * things like j a v a s c r i p t + * + * @param type + * @return type + */ + protected function _compact_exploded_words($matches) + { + return preg_replace('/\s+/s', '', $matches[1]).$matches[2]; + } + + // -------------------------------------------------------------------- + + /* + * Remove Evil HTML Attributes (like evenhandlers and style) + * + * It removes the evil attribute and either: + * - Everything up until a space + * For example, everything between the pipes: + * + * - Everything inside the quotes + * For example, everything between the pipes: + * + * + * @param string $str The string to check + * @param boolean $is_image TRUE if this is an image + * @return string The string with the evil attributes removed + */ + protected function _remove_evil_attributes($str, $is_image) + { + // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns + $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction'); + + if ($is_image === TRUE) + { + /* + * Adobe Photoshop puts XML metadata into JFIF images, + * including namespacing, so we have to allow this for images. + */ + unset($evil_attributes[array_search('xmlns', $evil_attributes)]); + } + + do { + $count = 0; + $attribs = array(); + + // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes) + preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is', $str, $matches, PREG_SET_ORDER); + + foreach ($matches as $attr) + { + $attribs[] = preg_quote($attr[0], '/'); + } + + // find occurrences of illegal attribute strings without quotes + preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER); + + foreach ($matches as $attr) + { + $attribs[] = preg_quote($attr[0], '/'); + } + + // replace illegal attribute strings that are inside an html tag + if (count($attribs) > 0) + { + $str = preg_replace('/(<]+?)([^A-Za-z<>\-])(.*?)('.implode('|', $attribs).')(.*?)([\s><]?)([><]*)/i', '$1$2 $4$6$7$8', $str, -1, $count); + } + + } while ($count); + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Sanitize Naughty HTML + * + * Callback function for xss_clean() to remove naughty HTML elements + * + * @param array + * @return string + */ + protected function _sanitize_naughty_html($matches) + { + // encode opening brace + $str = '<'.$matches[1].$matches[2].$matches[3]; + + // encode captured opening or closing brace to prevent recursive vectors + $str .= str_replace(array('>', '<'), array('>', '<'), + $matches[4]); + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * JS Link Removal + * + * Callback function for xss_clean() to sanitize links + * This limits the PCRE backtracks, making it more performance friendly + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in + * PHP 5.2+ on link-heavy strings + * + * @param array + * @return string + */ + protected function _js_link_removal($match) + { + return str_replace( + $match[1], + preg_replace( + '#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>'), '', $match[1])) + ), + $match[0] + ); + } + + // -------------------------------------------------------------------- + + /** + * JS Image Removal + * + * Callback function for xss_clean() to sanitize image tags + * This limits the PCRE backtracks, making it more performance friendly + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in + * PHP 5.2+ on image tag heavy strings + * + * @param array + * @return string + */ + protected function _js_img_removal($match) + { + return str_replace( + $match[1], + preg_replace( + '#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>'), '', $match[1])) + ), + $match[0] + ); + } + + // -------------------------------------------------------------------- + + /** + * Attribute Conversion + * + * Used as a callback for XSS Clean + * + * @param array + * @return string + */ + protected function _convert_attribute($match) + { + return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]); + } + + // -------------------------------------------------------------------- + + /** + * Filter Attributes + * + * Filters tag attributes for consistency and safety + * + * @param string + * @return string + */ + protected function _filter_attributes($str) + { + $out = ''; + + if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches)) + { + foreach ($matches[0] as $match) + { + $out .= preg_replace("#/\*.*?\*/#s", '', $match); + } + } + + return $out; + } + + // -------------------------------------------------------------------- + + /** + * HTML Entity Decode Callback + * + * Used as a callback for XSS Clean + * + * @param array + * @return string + */ + protected function _decode_entity($match) + { + return $this->entity_decode($match[0], strtoupper(config_item('charset'))); + } + + // -------------------------------------------------------------------- + + /** + * Validate URL entities + * + * Called by xss_clean() + * + * @param string + * @return string + */ + protected function _validate_entities($str) + { + /* + * Protect GET variables in URLs + */ + + // 901119URL5918AMP18930PROTECT8198 + + $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str); + + /* + * Validate standard character entities + * + * Add a semicolon if missing. We do this to enable + * the conversion of entities to ASCII later. + * + */ + $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str); + + /* + * Validate UTF16 two byte encoding (x00) + * + * Just as above, adds a semicolon if missing. + * + */ + $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str); + + /* + * Un-Protect GET variables in URLs + */ + $str = str_replace($this->xss_hash(), '&', $str); + + return $str; + } + + // ---------------------------------------------------------------------- + + /** + * Do Never Allowed + * + * A utility function for xss_clean() + * + * @param string + * @return string + */ + protected function _do_never_allowed($str) + { + $str = str_replace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str); + + foreach ($this->_never_allowed_regex as $regex) + { + $str = preg_replace('#'.$regex.'#is', '[removed]', $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Set Cross Site Request Forgery Protection Cookie + * + * @return string + */ + protected function _csrf_set_hash() + { + if ($this->_csrf_hash == '') + { + // If the cookie exists we will use it's value. + // We don't necessarily want to regenerate it with + // each page load since a page could contain embedded + // sub-pages causing this feature to fail + if (isset($_COOKIE[$this->_csrf_cookie_name]) && + preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1) + { + return $this->_csrf_hash = $_COOKIE[$this->_csrf_cookie_name]; + } + + return $this->_csrf_hash = md5(uniqid(rand(), TRUE)); + } + + return $this->_csrf_hash; + } + +} + +/* End of file Security.php */ +/* Location: ./system/libraries/Security.php */ diff --git a/api/system/core/URI.php b/api/system/core/URI.php new file mode 100644 index 0000000..a3ae20c --- /dev/null +++ b/api/system/core/URI.php @@ -0,0 +1,654 @@ +config =& load_class('Config', 'core'); + log_message('debug', "URI Class Initialized"); + } + + + // -------------------------------------------------------------------- + + /** + * Get the URI String + * + * @access private + * @return string + */ + function _fetch_uri_string() + { + if (strtoupper($this->config->item('uri_protocol')) == 'AUTO') + { + // Is the request coming from the command line? + if (php_sapi_name() == 'cli' or defined('STDIN')) + { + $this->_set_uri_string($this->_parse_cli_args()); + return; + } + + // Let's try the REQUEST_URI first, this will work in most situations + if ($uri = $this->_detect_uri()) + { + $this->_set_uri_string($uri); + return; + } + + // Is there a PATH_INFO variable? + // Note: some servers seem to have trouble with getenv() so we'll test it two ways + $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'); + if (trim($path, '/') != '' && $path != "/".SELF) + { + $this->_set_uri_string($path); + return; + } + + // No PATH_INFO?... What about QUERY_STRING? + $path = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING'); + if (trim($path, '/') != '') + { + $this->_set_uri_string($path); + return; + } + + // As a last ditch effort lets try using the $_GET array + if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '') + { + $this->_set_uri_string(key($_GET)); + return; + } + + // We've exhausted all our options... + $this->uri_string = ''; + return; + } + + $uri = strtoupper($this->config->item('uri_protocol')); + + if ($uri == 'REQUEST_URI') + { + $this->_set_uri_string($this->_detect_uri()); + return; + } + elseif ($uri == 'CLI') + { + $this->_set_uri_string($this->_parse_cli_args()); + return; + } + + $path = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri); + $this->_set_uri_string($path); + } + + // -------------------------------------------------------------------- + + /** + * Set the URI String + * + * @access public + * @param string + * @return string + */ + function _set_uri_string($str) + { + // Filter out control characters + $str = remove_invisible_characters($str, FALSE); + + // If the URI contains only a slash we'll kill it + $this->uri_string = ($str == '/') ? '' : $str; + } + + // -------------------------------------------------------------------- + + /** + * Detects the URI + * + * This function will detect the URI automatically and fix the query string + * if necessary. + * + * @access private + * @return string + */ + private function _detect_uri() + { + if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME'])) + { + return ''; + } + + $uri = $_SERVER['REQUEST_URI']; + if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) + { + $uri = substr($uri, strlen($_SERVER['SCRIPT_NAME'])); + } + elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0) + { + $uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME']))); + } + + // This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct + // URI is found, and also fixes the QUERY_STRING server var and $_GET array. + if (strncmp($uri, '?/', 2) === 0) + { + $uri = substr($uri, 2); + } + $parts = preg_split('#\?#i', $uri, 2); + $uri = $parts[0]; + if (isset($parts[1])) + { + $_SERVER['QUERY_STRING'] = $parts[1]; + parse_str($_SERVER['QUERY_STRING'], $_GET); + } + else + { + $_SERVER['QUERY_STRING'] = ''; + $_GET = array(); + } + + if ($uri == '/' || empty($uri)) + { + return '/'; + } + + $uri = parse_url($uri, PHP_URL_PATH); + + // Do some final cleaning of the URI and return it + return str_replace(array('//', '../'), '/', trim($uri, '/')); + } + + // -------------------------------------------------------------------- + + /** + * Parse cli arguments + * + * Take each command line argument and assume it is a URI segment. + * + * @access private + * @return string + */ + private function _parse_cli_args() + { + $args = array_slice($_SERVER['argv'], 1); + + return $args ? '/' . implode('/', $args) : ''; + } + + // -------------------------------------------------------------------- + + /** + * Filter segments for malicious characters + * + * @access private + * @param string + * @return string + */ + function _filter_uri($str) + { + if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE) + { + // preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards + // compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern + if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str)) + { + show_error('The URI you submitted has disallowed characters.', 400); + } + } + + // Convert programatic characters to entities + $bad = array('$', '(', ')', '%28', '%29'); + $good = array('$', '(', ')', '(', ')'); + + return str_replace($bad, $good, $str); + } + + // -------------------------------------------------------------------- + + /** + * Remove the suffix from the URL if needed + * + * @access private + * @return void + */ + function _remove_url_suffix() + { + if ($this->config->item('url_suffix') != "") + { + $this->uri_string = preg_replace("|".preg_quote($this->config->item('url_suffix'))."$|", "", $this->uri_string); + } + } + + // -------------------------------------------------------------------- + + /** + * Explode the URI Segments. The individual segments will + * be stored in the $this->segments array. + * + * @access private + * @return void + */ + function _explode_segments() + { + foreach (explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val) + { + // Filter segments for security + $val = trim($this->_filter_uri($val)); + + if ($val != '') + { + $this->segments[] = $val; + } + } + } + + // -------------------------------------------------------------------- + /** + * Re-index Segments + * + * This function re-indexes the $this->segment array so that it + * starts at 1 rather than 0. Doing so makes it simpler to + * use functions like $this->uri->segment(n) since there is + * a 1:1 relationship between the segment array and the actual segments. + * + * @access private + * @return void + */ + function _reindex_segments() + { + array_unshift($this->segments, NULL); + array_unshift($this->rsegments, NULL); + unset($this->segments[0]); + unset($this->rsegments[0]); + } + + // -------------------------------------------------------------------- + + /** + * Fetch a URI Segment + * + * This function returns the URI segment based on the number provided. + * + * @access public + * @param integer + * @param bool + * @return string + */ + function segment($n, $no_result = FALSE) + { + return ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch a URI "routed" Segment + * + * This function returns the re-routed URI segment (assuming routing rules are used) + * based on the number provided. If there is no routing this function returns the + * same result as $this->segment() + * + * @access public + * @param integer + * @param bool + * @return string + */ + function rsegment($n, $no_result = FALSE) + { + return ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n]; + } + + // -------------------------------------------------------------------- + + /** + * Generate a key value pair from the URI string + * + * This function generates and associative array of URI data starting + * at the supplied segment. For example, if this is your URI: + * + * example.com/user/search/name/joe/location/UK/gender/male + * + * You can use this function to generate an array with this prototype: + * + * array ( + * name => joe + * location => UK + * gender => male + * ) + * + * @access public + * @param integer the starting segment number + * @param array an array of default values + * @return array + */ + function uri_to_assoc($n = 3, $default = array()) + { + return $this->_uri_to_assoc($n, $default, 'segment'); + } + /** + * Identical to above only it uses the re-routed segment array + * + * @access public + * @param integer the starting segment number + * @param array an array of default values + * @return array + * + */ + function ruri_to_assoc($n = 3, $default = array()) + { + return $this->_uri_to_assoc($n, $default, 'rsegment'); + } + + // -------------------------------------------------------------------- + + /** + * Generate a key value pair from the URI string or Re-routed URI string + * + * @access private + * @param integer the starting segment number + * @param array an array of default values + * @param string which array we should use + * @return array + */ + function _uri_to_assoc($n = 3, $default = array(), $which = 'segment') + { + if ($which == 'segment') + { + $total_segments = 'total_segments'; + $segment_array = 'segment_array'; + } + else + { + $total_segments = 'total_rsegments'; + $segment_array = 'rsegment_array'; + } + + if ( ! is_numeric($n)) + { + return $default; + } + + if (isset($this->keyval[$n])) + { + return $this->keyval[$n]; + } + + if ($this->$total_segments() < $n) + { + if (count($default) == 0) + { + return array(); + } + + $retval = array(); + foreach ($default as $val) + { + $retval[$val] = FALSE; + } + return $retval; + } + + $segments = array_slice($this->$segment_array(), ($n - 1)); + + $i = 0; + $lastval = ''; + $retval = array(); + foreach ($segments as $seg) + { + if ($i % 2) + { + $retval[$lastval] = $seg; + } + else + { + $retval[$seg] = FALSE; + $lastval = $seg; + } + + $i++; + } + + if (count($default) > 0) + { + foreach ($default as $val) + { + if ( ! array_key_exists($val, $retval)) + { + $retval[$val] = FALSE; + } + } + } + + // Cache the array for reuse + $this->keyval[$n] = $retval; + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Generate a URI string from an associative array + * + * + * @access public + * @param array an associative array of key/values + * @return array + */ + function assoc_to_uri($array) + { + $temp = array(); + foreach ((array)$array as $key => $val) + { + $temp[] = $key; + $temp[] = $val; + } + + return implode('/', $temp); + } + + // -------------------------------------------------------------------- + + /** + * Fetch a URI Segment and add a trailing slash + * + * @access public + * @param integer + * @param string + * @return string + */ + function slash_segment($n, $where = 'trailing') + { + return $this->_slash_segment($n, $where, 'segment'); + } + + // -------------------------------------------------------------------- + + /** + * Fetch a URI Segment and add a trailing slash + * + * @access public + * @param integer + * @param string + * @return string + */ + function slash_rsegment($n, $where = 'trailing') + { + return $this->_slash_segment($n, $where, 'rsegment'); + } + + // -------------------------------------------------------------------- + + /** + * Fetch a URI Segment and add a trailing slash - helper function + * + * @access private + * @param integer + * @param string + * @param string + * @return string + */ + function _slash_segment($n, $where = 'trailing', $which = 'segment') + { + $leading = '/'; + $trailing = '/'; + + if ($where == 'trailing') + { + $leading = ''; + } + elseif ($where == 'leading') + { + $trailing = ''; + } + + return $leading.$this->$which($n).$trailing; + } + + // -------------------------------------------------------------------- + + /** + * Segment Array + * + * @access public + * @return array + */ + function segment_array() + { + return $this->segments; + } + + // -------------------------------------------------------------------- + + /** + * Routed Segment Array + * + * @access public + * @return array + */ + function rsegment_array() + { + return $this->rsegments; + } + + // -------------------------------------------------------------------- + + /** + * Total number of segments + * + * @access public + * @return integer + */ + function total_segments() + { + return count($this->segments); + } + + // -------------------------------------------------------------------- + + /** + * Total number of routed segments + * + * @access public + * @return integer + */ + function total_rsegments() + { + return count($this->rsegments); + } + + // -------------------------------------------------------------------- + + /** + * Fetch the entire URI string + * + * @access public + * @return string + */ + function uri_string() + { + return $this->uri_string; + } + + + // -------------------------------------------------------------------- + + /** + * Fetch the entire Re-routed URI string + * + * @access public + * @return string + */ + function ruri_string() + { + return '/'.implode('/', $this->rsegment_array()); + } + +} +// END URI Class + +/* End of file URI.php */ +/* Location: ./system/core/URI.php */ \ No newline at end of file diff --git a/api/system/core/Utf8.php b/api/system/core/Utf8.php new file mode 100644 index 0000000..2a27d1f --- /dev/null +++ b/api/system/core/Utf8.php @@ -0,0 +1,165 @@ +item('charset') == 'UTF-8' // Application charset must be UTF-8 + ) + { + log_message('debug', "UTF-8 Support Enabled"); + + define('UTF8_ENABLED', TRUE); + + // set internal encoding for multibyte string functions if necessary + // and set a flag so we don't have to repeatedly use extension_loaded() + // or function_exists() + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + mb_internal_encoding('UTF-8'); + } + else + { + define('MB_ENABLED', FALSE); + } + } + else + { + log_message('debug', "UTF-8 Support Disabled"); + define('UTF8_ENABLED', FALSE); + } + } + + // -------------------------------------------------------------------- + + /** + * Clean UTF-8 strings + * + * Ensures strings are UTF-8 + * + * @access public + * @param string + * @return string + */ + function clean_string($str) + { + if ($this->_is_ascii($str) === FALSE) + { + $str = @iconv('UTF-8', 'UTF-8//IGNORE', $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Remove ASCII control characters + * + * Removes all ASCII control characters except horizontal tabs, + * line feeds, and carriage returns, as all others can cause + * problems in XML + * + * @access public + * @param string + * @return string + */ + function safe_ascii_for_xml($str) + { + return remove_invisible_characters($str, FALSE); + } + + // -------------------------------------------------------------------- + + /** + * Convert to UTF-8 + * + * Attempts to convert a string to UTF-8 + * + * @access public + * @param string + * @param string - input encoding + * @return string + */ + function convert_to_utf8($str, $encoding) + { + if (function_exists('iconv')) + { + $str = @iconv($encoding, 'UTF-8', $str); + } + elseif (function_exists('mb_convert_encoding')) + { + $str = @mb_convert_encoding($str, 'UTF-8', $encoding); + } + else + { + return FALSE; + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Is ASCII? + * + * Tests if a string is standard 7-bit ASCII or not + * + * @access public + * @param string + * @return bool + */ + function _is_ascii($str) + { + return (preg_match('/[^\x00-\x7F]/S', $str) == 0); + } + + // -------------------------------------------------------------------- + +} +// End Utf8 Class + +/* End of file Utf8.php */ +/* Location: ./system/core/Utf8.php */ \ No newline at end of file diff --git a/api/system/core/index.html b/api/system/core/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/core/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/DB.php b/api/system/database/DB.php new file mode 100644 index 0000000..8314d3b --- /dev/null +++ b/api/system/database/DB.php @@ -0,0 +1,162 @@ + $dns['scheme'], + 'hostname' => (isset($dns['host'])) ? rawurldecode($dns['host']) : '', + 'username' => (isset($dns['user'])) ? rawurldecode($dns['user']) : '', + 'password' => (isset($dns['pass'])) ? rawurldecode($dns['pass']) : '', + 'database' => (isset($dns['path'])) ? rawurldecode(substr($dns['path'], 1)) : '' + ); + + // were additional config items set? + if (isset($dns['query'])) + { + parse_str($dns['query'], $extra); + + foreach ($extra as $key => $val) + { + // booleans please + if (strtoupper($val) == "TRUE") + { + $val = TRUE; + } + elseif (strtoupper($val) == "FALSE") + { + $val = FALSE; + } + + $params[$key] = $val; + } + } + } + + // No DB specified yet? Beat them senseless... + if ( ! isset($params['dbdriver']) OR $params['dbdriver'] == '') + { + show_error('You have not selected a database type to connect to.'); + } + + // Load the DB classes. Note: Since the active record class is optional + // we need to dynamically create a class that extends proper parent class + // based on whether we're using the active record class or not. + // Kudos to Paul for discovering this clever use of eval() + + if ($active_record_override !== NULL) + { + $active_record = $active_record_override; + } + + require_once(BASEPATH.'database/DB_driver.php'); + + if ( ! isset($active_record) OR $active_record == TRUE) + { + require_once(BASEPATH.'database/DB_active_rec.php'); + + if ( ! class_exists('CI_DB')) + { + eval('class CI_DB extends CI_DB_active_record { }'); + } + } + else + { + if ( ! class_exists('CI_DB')) + { + eval('class CI_DB extends CI_DB_driver { }'); + } + } + + require_once(BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php'); + + // Instantiate the DB adapter + $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; + $DB = new $driver($params); + + if ($DB->autoinit == TRUE) + { + $DB->initialize(); + } + + if (isset($params['stricton']) && $params['stricton'] == TRUE) + { + $DB->query('SET SESSION sql_mode="STRICT_ALL_TABLES"'); + } + + return $DB; +} + + + +/* End of file DB.php */ +/* Location: ./system/database/DB.php */ \ No newline at end of file diff --git a/api/system/database/DB_active_rec.php b/api/system/database/DB_active_rec.php new file mode 100644 index 0000000..129eaa7 --- /dev/null +++ b/api/system/database/DB_active_rec.php @@ -0,0 +1,2045 @@ +ar_select[] = $val; + $this->ar_no_escape[] = $escape; + + if ($this->ar_caching === TRUE) + { + $this->ar_cache_select[] = $val; + $this->ar_cache_exists[] = 'select'; + $this->ar_cache_no_escape[] = $escape; + } + } + } + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Select Max + * + * Generates a SELECT MAX(field) portion of a query + * + * @param string the field + * @param string an alias + * @return object + */ + public function select_max($select = '', $alias = '') + { + return $this->_max_min_avg_sum($select, $alias, 'MAX'); + } + + // -------------------------------------------------------------------- + + /** + * Select Min + * + * Generates a SELECT MIN(field) portion of a query + * + * @param string the field + * @param string an alias + * @return object + */ + public function select_min($select = '', $alias = '') + { + return $this->_max_min_avg_sum($select, $alias, 'MIN'); + } + + // -------------------------------------------------------------------- + + /** + * Select Average + * + * Generates a SELECT AVG(field) portion of a query + * + * @param string the field + * @param string an alias + * @return object + */ + public function select_avg($select = '', $alias = '') + { + return $this->_max_min_avg_sum($select, $alias, 'AVG'); + } + + // -------------------------------------------------------------------- + + /** + * Select Sum + * + * Generates a SELECT SUM(field) portion of a query + * + * @param string the field + * @param string an alias + * @return object + */ + public function select_sum($select = '', $alias = '') + { + return $this->_max_min_avg_sum($select, $alias, 'SUM'); + } + + // -------------------------------------------------------------------- + + /** + * Processing Function for the four functions above: + * + * select_max() + * select_min() + * select_avg() + * select_sum() + * + * @param string the field + * @param string an alias + * @return object + */ + protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX') + { + if ( ! is_string($select) OR $select == '') + { + $this->display_error('db_invalid_query'); + } + + $type = strtoupper($type); + + if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM'))) + { + show_error('Invalid function type: '.$type); + } + + if ($alias == '') + { + $alias = $this->_create_alias_from_table(trim($select)); + } + + $sql = $type.'('.$this->_protect_identifiers(trim($select)).') AS '.$alias; + + $this->ar_select[] = $sql; + + if ($this->ar_caching === TRUE) + { + $this->ar_cache_select[] = $sql; + $this->ar_cache_exists[] = 'select'; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Determines the alias name based on the table + * + * @param string + * @return string + */ + protected function _create_alias_from_table($item) + { + if (strpos($item, '.') !== FALSE) + { + return end(explode('.', $item)); + } + + return $item; + } + + // -------------------------------------------------------------------- + + /** + * DISTINCT + * + * Sets a flag which tells the query string compiler to add DISTINCT + * + * @param bool + * @return object + */ + public function distinct($val = TRUE) + { + $this->ar_distinct = (is_bool($val)) ? $val : TRUE; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * From + * + * Generates the FROM portion of the query + * + * @param mixed can be a string or array + * @return object + */ + public function from($from) + { + foreach ((array) $from as $val) + { + if (strpos($val, ',') !== FALSE) + { + foreach (explode(',', $val) as $v) + { + $v = trim($v); + $this->_track_aliases($v); + + $this->ar_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE); + + if ($this->ar_caching === TRUE) + { + $this->ar_cache_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE); + $this->ar_cache_exists[] = 'from'; + } + } + + } + else + { + $val = trim($val); + + // Extract any aliases that might exist. We use this information + // in the _protect_identifiers to know whether to add a table prefix + $this->_track_aliases($val); + + $this->ar_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE); + + if ($this->ar_caching === TRUE) + { + $this->ar_cache_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE); + $this->ar_cache_exists[] = 'from'; + } + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Join + * + * Generates the JOIN portion of the query + * + * @param string + * @param string the join condition + * @param string the type of join + * @return object + */ + public function join($table, $cond, $type = '') + { + if ($type != '') + { + $type = strtoupper(trim($type)); + + if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'))) + { + $type = ''; + } + else + { + $type .= ' '; + } + } + + // Extract any aliases that might exist. We use this information + // in the _protect_identifiers to know whether to add a table prefix + $this->_track_aliases($table); + + // Strip apart the condition and protect the identifiers + if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match)) + { + $match[1] = $this->_protect_identifiers($match[1]); + $match[3] = $this->_protect_identifiers($match[3]); + + $cond = $match[1].$match[2].$match[3]; + } + + // Assemble the JOIN statement + $join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond; + + $this->ar_join[] = $join; + if ($this->ar_caching === TRUE) + { + $this->ar_cache_join[] = $join; + $this->ar_cache_exists[] = 'join'; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Where + * + * Generates the WHERE portion of the query. Separates + * multiple calls with AND + * + * @param mixed + * @param mixed + * @return object + */ + public function where($key, $value = NULL, $escape = TRUE) + { + return $this->_where($key, $value, 'AND ', $escape); + } + + // -------------------------------------------------------------------- + + /** + * OR Where + * + * Generates the WHERE portion of the query. Separates + * multiple calls with OR + * + * @param mixed + * @param mixed + * @return object + */ + public function or_where($key, $value = NULL, $escape = TRUE) + { + return $this->_where($key, $value, 'OR ', $escape); + } + + // -------------------------------------------------------------------- + + /** + * Where + * + * Called by where() or or_where() + * + * @param mixed + * @param mixed + * @param string + * @return object + */ + protected function _where($key, $value = NULL, $type = 'AND ', $escape = NULL) + { + if ( ! is_array($key)) + { + $key = array($key => $value); + } + + // If the escape value was not set will will base it on the global setting + if ( ! is_bool($escape)) + { + $escape = $this->_protect_identifiers; + } + + foreach ($key as $k => $v) + { + $prefix = (count($this->ar_where) == 0 AND count($this->ar_cache_where) == 0) ? '' : $type; + + if (is_null($v) && ! $this->_has_operator($k)) + { + // value appears not to have been set, assign the test to IS NULL + $k .= ' IS NULL'; + } + + if ( ! is_null($v)) + { + if ($escape === TRUE) + { + $k = $this->_protect_identifiers($k, FALSE, $escape); + + $v = ' '.$this->escape($v); + } + + if ( ! $this->_has_operator($k)) + { + $k .= ' = '; + } + } + else + { + $k = $this->_protect_identifiers($k, FALSE, $escape); + } + + $this->ar_where[] = $prefix.$k.$v; + + if ($this->ar_caching === TRUE) + { + $this->ar_cache_where[] = $prefix.$k.$v; + $this->ar_cache_exists[] = 'where'; + } + + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Where_in + * + * Generates a WHERE field IN ('item', 'item') SQL query joined with + * AND if appropriate + * + * @param string The field to search + * @param array The values searched on + * @return object + */ + public function where_in($key = NULL, $values = NULL) + { + return $this->_where_in($key, $values); + } + + // -------------------------------------------------------------------- + + /** + * Where_in_or + * + * Generates a WHERE field IN ('item', 'item') SQL query joined with + * OR if appropriate + * + * @param string The field to search + * @param array The values searched on + * @return object + */ + public function or_where_in($key = NULL, $values = NULL) + { + return $this->_where_in($key, $values, FALSE, 'OR '); + } + + // -------------------------------------------------------------------- + + /** + * Where_not_in + * + * Generates a WHERE field NOT IN ('item', 'item') SQL query joined + * with AND if appropriate + * + * @param string The field to search + * @param array The values searched on + * @return object + */ + public function where_not_in($key = NULL, $values = NULL) + { + return $this->_where_in($key, $values, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Where_not_in_or + * + * Generates a WHERE field NOT IN ('item', 'item') SQL query joined + * with OR if appropriate + * + * @param string The field to search + * @param array The values searched on + * @return object + */ + public function or_where_not_in($key = NULL, $values = NULL) + { + return $this->_where_in($key, $values, TRUE, 'OR '); + } + + // -------------------------------------------------------------------- + + /** + * Where_in + * + * Called by where_in, where_in_or, where_not_in, where_not_in_or + * + * @param string The field to search + * @param array The values searched on + * @param boolean If the statement would be IN or NOT IN + * @param string + * @return object + */ + protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ') + { + if ($key === NULL OR $values === NULL) + { + return; + } + + if ( ! is_array($values)) + { + $values = array($values); + } + + $not = ($not) ? ' NOT' : ''; + + foreach ($values as $value) + { + $this->ar_wherein[] = $this->escape($value); + } + + $prefix = (count($this->ar_where) == 0) ? '' : $type; + + $where_in = $prefix . $this->_protect_identifiers($key) . $not . " IN (" . implode(", ", $this->ar_wherein) . ") "; + + $this->ar_where[] = $where_in; + if ($this->ar_caching === TRUE) + { + $this->ar_cache_where[] = $where_in; + $this->ar_cache_exists[] = 'where'; + } + + // reset the array for multiple calls + $this->ar_wherein = array(); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Like + * + * Generates a %LIKE% portion of the query. Separates + * multiple calls with AND + * + * @param mixed + * @param mixed + * @return object + */ + public function like($field, $match = '', $side = 'both') + { + return $this->_like($field, $match, 'AND ', $side); + } + + // -------------------------------------------------------------------- + + /** + * Not Like + * + * Generates a NOT LIKE portion of the query. Separates + * multiple calls with AND + * + * @param mixed + * @param mixed + * @return object + */ + public function not_like($field, $match = '', $side = 'both') + { + return $this->_like($field, $match, 'AND ', $side, 'NOT'); + } + + // -------------------------------------------------------------------- + + /** + * OR Like + * + * Generates a %LIKE% portion of the query. Separates + * multiple calls with OR + * + * @param mixed + * @param mixed + * @return object + */ + public function or_like($field, $match = '', $side = 'both') + { + return $this->_like($field, $match, 'OR ', $side); + } + + // -------------------------------------------------------------------- + + /** + * OR Not Like + * + * Generates a NOT LIKE portion of the query. Separates + * multiple calls with OR + * + * @param mixed + * @param mixed + * @return object + */ + public function or_not_like($field, $match = '', $side = 'both') + { + return $this->_like($field, $match, 'OR ', $side, 'NOT'); + } + + // -------------------------------------------------------------------- + + /** + * Like + * + * Called by like() or orlike() + * + * @param mixed + * @param mixed + * @param string + * @return object + */ + protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '') + { + if ( ! is_array($field)) + { + $field = array($field => $match); + } + + foreach ($field as $k => $v) + { + $k = $this->_protect_identifiers($k); + + $prefix = (count($this->ar_like) == 0) ? '' : $type; + + $v = $this->escape_like_str($v); + + if ($side == 'none') + { + $like_statement = $prefix." $k $not LIKE '{$v}'"; + } + elseif ($side == 'before') + { + $like_statement = $prefix." $k $not LIKE '%{$v}'"; + } + elseif ($side == 'after') + { + $like_statement = $prefix." $k $not LIKE '{$v}%'"; + } + else + { + $like_statement = $prefix." $k $not LIKE '%{$v}%'"; + } + + // some platforms require an escape sequence definition for LIKE wildcards + if ($this->_like_escape_str != '') + { + $like_statement = $like_statement.sprintf($this->_like_escape_str, $this->_like_escape_chr); + } + + $this->ar_like[] = $like_statement; + if ($this->ar_caching === TRUE) + { + $this->ar_cache_like[] = $like_statement; + $this->ar_cache_exists[] = 'like'; + } + + } + return $this; + } + + // -------------------------------------------------------------------- + + /** + * GROUP BY + * + * @param string + * @return object + */ + public function group_by($by) + { + if (is_string($by)) + { + $by = explode(',', $by); + } + + foreach ($by as $val) + { + $val = trim($val); + + if ($val != '') + { + $this->ar_groupby[] = $this->_protect_identifiers($val); + + if ($this->ar_caching === TRUE) + { + $this->ar_cache_groupby[] = $this->_protect_identifiers($val); + $this->ar_cache_exists[] = 'groupby'; + } + } + } + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Sets the HAVING value + * + * Separates multiple calls with AND + * + * @param string + * @param string + * @return object + */ + public function having($key, $value = '', $escape = TRUE) + { + return $this->_having($key, $value, 'AND ', $escape); + } + + // -------------------------------------------------------------------- + + /** + * Sets the OR HAVING value + * + * Separates multiple calls with OR + * + * @param string + * @param string + * @return object + */ + public function or_having($key, $value = '', $escape = TRUE) + { + return $this->_having($key, $value, 'OR ', $escape); + } + + // -------------------------------------------------------------------- + + /** + * Sets the HAVING values + * + * Called by having() or or_having() + * + * @param string + * @param string + * @return object + */ + protected function _having($key, $value = '', $type = 'AND ', $escape = TRUE) + { + if ( ! is_array($key)) + { + $key = array($key => $value); + } + + foreach ($key as $k => $v) + { + $prefix = (count($this->ar_having) == 0) ? '' : $type; + + if ($escape === TRUE) + { + $k = $this->_protect_identifiers($k); + } + + if ( ! $this->_has_operator($k)) + { + $k .= ' = '; + } + + if ($v != '') + { + $v = ' '.$this->escape($v); + } + + $this->ar_having[] = $prefix.$k.$v; + if ($this->ar_caching === TRUE) + { + $this->ar_cache_having[] = $prefix.$k.$v; + $this->ar_cache_exists[] = 'having'; + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Sets the ORDER BY value + * + * @param string + * @param string direction: asc or desc + * @return object + */ + public function order_by($orderby, $direction = '') + { + if (strtolower($direction) == 'random') + { + $orderby = ''; // Random results want or don't need a field name + $direction = $this->_random_keyword; + } + elseif (trim($direction) != '') + { + $direction = (in_array(strtoupper(trim($direction)), array('ASC', 'DESC'), TRUE)) ? ' '.$direction : ' ASC'; + } + + + if (strpos($orderby, ',') !== FALSE) + { + $temp = array(); + foreach (explode(',', $orderby) as $part) + { + $part = trim($part); + if ( ! in_array($part, $this->ar_aliased_tables)) + { + $part = $this->_protect_identifiers(trim($part)); + } + + $temp[] = $part; + } + + $orderby = implode(', ', $temp); + } + else if ($direction != $this->_random_keyword) + { + $orderby = $this->_protect_identifiers($orderby); + } + + $orderby_statement = $orderby.$direction; + + $this->ar_orderby[] = $orderby_statement; + if ($this->ar_caching === TRUE) + { + $this->ar_cache_orderby[] = $orderby_statement; + $this->ar_cache_exists[] = 'orderby'; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Sets the LIMIT value + * + * @param integer the limit value + * @param integer the offset value + * @return object + */ + public function limit($value, $offset = '') + { + $this->ar_limit = (int) $value; + + if ($offset != '') + { + $this->ar_offset = (int) $offset; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Sets the OFFSET value + * + * @param integer the offset value + * @return object + */ + public function offset($offset) + { + $this->ar_offset = $offset; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * The "set" function. Allows key/value pairs to be set for inserting or updating + * + * @param mixed + * @param string + * @param boolean + * @return object + */ + public function set($key, $value = '', $escape = TRUE) + { + $key = $this->_object_to_array($key); + + if ( ! is_array($key)) + { + $key = array($key => $value); + } + + foreach ($key as $k => $v) + { + if ($escape === FALSE) + { + $this->ar_set[$this->_protect_identifiers($k)] = $v; + } + else + { + $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v); + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Get + * + * Compiles the select statement based on the other functions called + * and runs the query + * + * @param string the table + * @param string the limit clause + * @param string the offset clause + * @return object + */ + public function get($table = '', $limit = null, $offset = null) + { + if ($table != '') + { + $this->_track_aliases($table); + $this->from($table); + } + + if ( ! is_null($limit)) + { + $this->limit($limit, $offset); + } + + $sql = $this->_compile_select(); + + $result = $this->query($sql); + $this->_reset_select(); + return $result; + } + + /** + * "Count All Results" query + * + * Generates a platform-specific query string that counts all records + * returned by an Active Record query. + * + * @param string + * @return string + */ + public function count_all_results($table = '') + { + if ($table != '') + { + $this->_track_aliases($table); + $this->from($table); + } + + $sql = $this->_compile_select($this->_count_string . $this->_protect_identifiers('numrows')); + + $query = $this->query($sql); + $this->_reset_select(); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * Get_Where + * + * Allows the where clause, limit and offset to be added directly + * + * @param string the where clause + * @param string the limit clause + * @param string the offset clause + * @return object + */ + public function get_where($table = '', $where = null, $limit = null, $offset = null) + { + if ($table != '') + { + $this->from($table); + } + + if ( ! is_null($where)) + { + $this->where($where); + } + + if ( ! is_null($limit)) + { + $this->limit($limit, $offset); + } + + $sql = $this->_compile_select(); + + $result = $this->query($sql); + $this->_reset_select(); + return $result; + } + + // -------------------------------------------------------------------- + + /** + * Insert_Batch + * + * Compiles batch insert strings and runs the queries + * + * @param string the table to retrieve the results from + * @param array an associative array of insert values + * @return object + */ + public function insert_batch($table = '', $set = NULL) + { + if ( ! is_null($set)) + { + $this->set_insert_batch($set); + } + + if (count($this->ar_set) == 0) + { + if ($this->db_debug) + { + //No valid data array. Folds in cases where keys and values did not match up + return $this->display_error('db_must_use_set'); + } + return FALSE; + } + + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + + // Batch this baby + for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100) + { + + $sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100)); + + //echo $sql; + + $this->query($sql); + } + + $this->_reset_write(); + + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts + * + * @param mixed + * @param string + * @param boolean + * @return object + */ + public function set_insert_batch($key, $value = '', $escape = TRUE) + { + $key = $this->_object_to_array_batch($key); + + if ( ! is_array($key)) + { + $key = array($key => $value); + } + + $keys = array_keys(current($key)); + sort($keys); + + foreach ($key as $row) + { + if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0) + { + // batch function above returns an error on an empty array + $this->ar_set[] = array(); + return; + } + + ksort($row); // puts $row in the same order as our keys + + if ($escape === FALSE) + { + $this->ar_set[] = '('.implode(',', $row).')'; + } + else + { + $clean = array(); + + foreach ($row as $value) + { + $clean[] = $this->escape($value); + } + + $this->ar_set[] = '('.implode(',', $clean).')'; + } + } + + foreach ($keys as $k) + { + $this->ar_keys[] = $this->_protect_identifiers($k); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Insert + * + * Compiles an insert string and runs the query + * + * @param string the table to insert data into + * @param array an associative array of insert values + * @return object + */ + function insert($table = '', $set = NULL) + { + if ( ! is_null($set)) + { + $this->set($set); + } + + if (count($this->ar_set) == 0) + { + if ($this->db_debug) + { + return $this->display_error('db_must_use_set'); + } + return FALSE; + } + + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + + $sql = $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set)); + + $this->_reset_write(); + return $this->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Replace + * + * Compiles an replace into string and runs the query + * + * @param string the table to replace data into + * @param array an associative array of insert values + * @return object + */ + public function replace($table = '', $set = NULL) + { + if ( ! is_null($set)) + { + $this->set($set); + } + + if (count($this->ar_set) == 0) + { + if ($this->db_debug) + { + return $this->display_error('db_must_use_set'); + } + return FALSE; + } + + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + + $sql = $this->_replace($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set)); + + $this->_reset_write(); + return $this->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Update + * + * Compiles an update string and runs the query + * + * @param string the table to retrieve the results from + * @param array an associative array of update values + * @param mixed the where clause + * @return object + */ + public function update($table = '', $set = NULL, $where = NULL, $limit = NULL) + { + // Combine any cached components with the current statements + $this->_merge_cache(); + + if ( ! is_null($set)) + { + $this->set($set); + } + + if (count($this->ar_set) == 0) + { + if ($this->db_debug) + { + return $this->display_error('db_must_use_set'); + } + return FALSE; + } + + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + + if ($where != NULL) + { + $this->where($where); + } + + if ($limit != NULL) + { + $this->limit($limit); + } + + $sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit); + + $this->_reset_write(); + return $this->query($sql); + } + + + // -------------------------------------------------------------------- + + /** + * Update_Batch + * + * Compiles an update string and runs the query + * + * @param string the table to retrieve the results from + * @param array an associative array of update values + * @param string the where key + * @return object + */ + public function update_batch($table = '', $set = NULL, $index = NULL) + { + // Combine any cached components with the current statements + $this->_merge_cache(); + + if (is_null($index)) + { + if ($this->db_debug) + { + return $this->display_error('db_must_use_index'); + } + + return FALSE; + } + + if ( ! is_null($set)) + { + $this->set_update_batch($set, $index); + } + + if (count($this->ar_set) == 0) + { + if ($this->db_debug) + { + return $this->display_error('db_must_use_set'); + } + + return FALSE; + } + + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + + // Batch this baby + for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100) + { + $sql = $this->_update_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->ar_set, $i, 100), $this->_protect_identifiers($index), $this->ar_where); + + $this->query($sql); + } + + $this->_reset_write(); + } + + // -------------------------------------------------------------------- + + /** + * The "set_update_batch" function. Allows key/value pairs to be set for batch updating + * + * @param array + * @param string + * @param boolean + * @return object + */ + public function set_update_batch($key, $index = '', $escape = TRUE) + { + $key = $this->_object_to_array_batch($key); + + if ( ! is_array($key)) + { + // @todo error + } + + foreach ($key as $k => $v) + { + $index_set = FALSE; + $clean = array(); + + foreach ($v as $k2 => $v2) + { + if ($k2 == $index) + { + $index_set = TRUE; + } + else + { + $not[] = $k2.'-'.$v2; + } + + if ($escape === FALSE) + { + $clean[$this->_protect_identifiers($k2)] = $v2; + } + else + { + $clean[$this->_protect_identifiers($k2)] = $this->escape($v2); + } + } + + if ($index_set == FALSE) + { + return $this->display_error('db_batch_missing_index'); + } + + $this->ar_set[] = $clean; + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Empty Table + * + * Compiles a delete string and runs "DELETE FROM table" + * + * @param string the table to empty + * @return object + */ + public function empty_table($table = '') + { + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + else + { + $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE); + } + + $sql = $this->_delete($table); + + $this->_reset_write(); + + return $this->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Truncate + * + * Compiles a truncate string and runs the query + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @param string the table to truncate + * @return object + */ + public function truncate($table = '') + { + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + else + { + $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE); + } + + $sql = $this->_truncate($table); + + $this->_reset_write(); + + return $this->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Delete + * + * Compiles a delete string and runs the query + * + * @param mixed the table(s) to delete from. String or array + * @param mixed the where clause + * @param mixed the limit clause + * @param boolean + * @return object + */ + public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE) + { + // Combine any cached components with the current statements + $this->_merge_cache(); + + if ($table == '') + { + if ( ! isset($this->ar_from[0])) + { + if ($this->db_debug) + { + return $this->display_error('db_must_set_table'); + } + return FALSE; + } + + $table = $this->ar_from[0]; + } + elseif (is_array($table)) + { + foreach ($table as $single_table) + { + $this->delete($single_table, $where, $limit, FALSE); + } + + $this->_reset_write(); + return; + } + else + { + $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE); + } + + if ($where != '') + { + $this->where($where); + } + + if ($limit != NULL) + { + $this->limit($limit); + } + + if (count($this->ar_where) == 0 && count($this->ar_wherein) == 0 && count($this->ar_like) == 0) + { + if ($this->db_debug) + { + return $this->display_error('db_del_must_use_where'); + } + + return FALSE; + } + + $sql = $this->_delete($table, $this->ar_where, $this->ar_like, $this->ar_limit); + + if ($reset_data) + { + $this->_reset_write(); + } + + return $this->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * DB Prefix + * + * Prepends a database prefix if one exists in configuration + * + * @param string the table + * @return string + */ + public function dbprefix($table = '') + { + if ($table == '') + { + $this->display_error('db_table_name_required'); + } + + return $this->dbprefix.$table; + } + + // -------------------------------------------------------------------- + + /** + * Set DB Prefix + * + * Set's the DB Prefix to something new without needing to reconnect + * + * @param string the prefix + * @return string + */ + public function set_dbprefix($prefix = '') + { + return $this->dbprefix = $prefix; + } + + // -------------------------------------------------------------------- + + /** + * Track Aliases + * + * Used to track SQL statements written with aliased tables. + * + * @param string The table to inspect + * @return string + */ + protected function _track_aliases($table) + { + if (is_array($table)) + { + foreach ($table as $t) + { + $this->_track_aliases($t); + } + return; + } + + // Does the string contain a comma? If so, we need to separate + // the string into discreet statements + if (strpos($table, ',') !== FALSE) + { + return $this->_track_aliases(explode(',', $table)); + } + + // if a table alias is used we can recognize it by a space + if (strpos($table, " ") !== FALSE) + { + // if the alias is written with the AS keyword, remove it + $table = preg_replace('/\s+AS\s+/i', ' ', $table); + + // Grab the alias + $table = trim(strrchr($table, " ")); + + // Store the alias, if it doesn't already exist + if ( ! in_array($table, $this->ar_aliased_tables)) + { + $this->ar_aliased_tables[] = $table; + } + } + } + + // -------------------------------------------------------------------- + + /** + * Compile the SELECT statement + * + * Generates a query string based on which functions were used. + * Should not be called directly. The get() function calls it. + * + * @return string + */ + protected function _compile_select($select_override = FALSE) + { + // Combine any cached components with the current statements + $this->_merge_cache(); + + // ---------------------------------------------------------------- + + // Write the "select" portion of the query + + if ($select_override !== FALSE) + { + $sql = $select_override; + } + else + { + $sql = ( ! $this->ar_distinct) ? 'SELECT ' : 'SELECT DISTINCT '; + + if (count($this->ar_select) == 0) + { + $sql .= '*'; + } + else + { + // Cycle through the "select" portion of the query and prep each column name. + // The reason we protect identifiers here rather then in the select() function + // is because until the user calls the from() function we don't know if there are aliases + foreach ($this->ar_select as $key => $val) + { + $no_escape = isset($this->ar_no_escape[$key]) ? $this->ar_no_escape[$key] : NULL; + $this->ar_select[$key] = $this->_protect_identifiers($val, FALSE, $no_escape); + } + + $sql .= implode(', ', $this->ar_select); + } + } + + // ---------------------------------------------------------------- + + // Write the "FROM" portion of the query + + if (count($this->ar_from) > 0) + { + $sql .= "\nFROM "; + + $sql .= $this->_from_tables($this->ar_from); + } + + // ---------------------------------------------------------------- + + // Write the "JOIN" portion of the query + + if (count($this->ar_join) > 0) + { + $sql .= "\n"; + + $sql .= implode("\n", $this->ar_join); + } + + // ---------------------------------------------------------------- + + // Write the "WHERE" portion of the query + + if (count($this->ar_where) > 0 OR count($this->ar_like) > 0) + { + $sql .= "\nWHERE "; + } + + $sql .= implode("\n", $this->ar_where); + + // ---------------------------------------------------------------- + + // Write the "LIKE" portion of the query + + if (count($this->ar_like) > 0) + { + if (count($this->ar_where) > 0) + { + $sql .= "\nAND "; + } + + $sql .= implode("\n", $this->ar_like); + } + + // ---------------------------------------------------------------- + + // Write the "GROUP BY" portion of the query + + if (count($this->ar_groupby) > 0) + { + $sql .= "\nGROUP BY "; + + $sql .= implode(', ', $this->ar_groupby); + } + + // ---------------------------------------------------------------- + + // Write the "HAVING" portion of the query + + if (count($this->ar_having) > 0) + { + $sql .= "\nHAVING "; + $sql .= implode("\n", $this->ar_having); + } + + // ---------------------------------------------------------------- + + // Write the "ORDER BY" portion of the query + + if (count($this->ar_orderby) > 0) + { + $sql .= "\nORDER BY "; + $sql .= implode(', ', $this->ar_orderby); + + if ($this->ar_order !== FALSE) + { + $sql .= ($this->ar_order == 'desc') ? ' DESC' : ' ASC'; + } + } + + // ---------------------------------------------------------------- + + // Write the "LIMIT" portion of the query + + if (is_numeric($this->ar_limit)) + { + $sql .= "\n"; + $sql = $this->_limit($sql, $this->ar_limit, $this->ar_offset); + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Object to Array + * + * Takes an object as input and converts the class variables to array key/vals + * + * @param object + * @return array + */ + public function _object_to_array($object) + { + if ( ! is_object($object)) + { + return $object; + } + + $array = array(); + foreach (get_object_vars($object) as $key => $val) + { + // There are some built in keys we need to ignore for this conversion + if ( ! is_object($val) && ! is_array($val) && $key != '_parent_name') + { + $array[$key] = $val; + } + } + + return $array; + } + + // -------------------------------------------------------------------- + + /** + * Object to Array + * + * Takes an object as input and converts the class variables to array key/vals + * + * @param object + * @return array + */ + public function _object_to_array_batch($object) + { + if ( ! is_object($object)) + { + return $object; + } + + $array = array(); + $out = get_object_vars($object); + $fields = array_keys($out); + + foreach ($fields as $val) + { + // There are some built in keys we need to ignore for this conversion + if ($val != '_parent_name') + { + + $i = 0; + foreach ($out[$val] as $data) + { + $array[$i][$val] = $data; + $i++; + } + } + } + + return $array; + } + + // -------------------------------------------------------------------- + + /** + * Start Cache + * + * Starts AR caching + * + * @return void + */ + public function start_cache() + { + $this->ar_caching = TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Stop Cache + * + * Stops AR caching + * + * @return void + */ + public function stop_cache() + { + $this->ar_caching = FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Flush Cache + * + * Empties the AR cache + * + * @access public + * @return void + */ + public function flush_cache() + { + $this->_reset_run(array( + 'ar_cache_select' => array(), + 'ar_cache_from' => array(), + 'ar_cache_join' => array(), + 'ar_cache_where' => array(), + 'ar_cache_like' => array(), + 'ar_cache_groupby' => array(), + 'ar_cache_having' => array(), + 'ar_cache_orderby' => array(), + 'ar_cache_set' => array(), + 'ar_cache_exists' => array(), + 'ar_cache_no_escape' => array() + )); + } + + // -------------------------------------------------------------------- + + /** + * Merge Cache + * + * When called, this function merges any cached AR arrays with + * locally called ones. + * + * @return void + */ + protected function _merge_cache() + { + if (count($this->ar_cache_exists) == 0) + { + return; + } + + foreach ($this->ar_cache_exists as $val) + { + $ar_variable = 'ar_'.$val; + $ar_cache_var = 'ar_cache_'.$val; + + if (count($this->$ar_cache_var) == 0) + { + continue; + } + + $this->$ar_variable = array_unique(array_merge($this->$ar_cache_var, $this->$ar_variable)); + } + + // If we are "protecting identifiers" we need to examine the "from" + // portion of the query to determine if there are any aliases + if ($this->_protect_identifiers === TRUE AND count($this->ar_cache_from) > 0) + { + $this->_track_aliases($this->ar_from); + } + + $this->ar_no_escape = $this->ar_cache_no_escape; + } + + // -------------------------------------------------------------------- + + /** + * Resets the active record values. Called by the get() function + * + * @param array An array of fields to reset + * @return void + */ + protected function _reset_run($ar_reset_items) + { + foreach ($ar_reset_items as $item => $default_value) + { + if ( ! in_array($item, $this->ar_store_array)) + { + $this->$item = $default_value; + } + } + } + + // -------------------------------------------------------------------- + + /** + * Resets the active record values. Called by the get() function + * + * @return void + */ + protected function _reset_select() + { + $ar_reset_items = array( + 'ar_select' => array(), + 'ar_from' => array(), + 'ar_join' => array(), + 'ar_where' => array(), + 'ar_like' => array(), + 'ar_groupby' => array(), + 'ar_having' => array(), + 'ar_orderby' => array(), + 'ar_wherein' => array(), + 'ar_aliased_tables' => array(), + 'ar_no_escape' => array(), + 'ar_distinct' => FALSE, + 'ar_limit' => FALSE, + 'ar_offset' => FALSE, + 'ar_order' => FALSE, + ); + + $this->_reset_run($ar_reset_items); + } + + // -------------------------------------------------------------------- + + /** + * Resets the active record "write" values. + * + * Called by the insert() update() insert_batch() update_batch() and delete() functions + * + * @return void + */ + protected function _reset_write() + { + $ar_reset_items = array( + 'ar_set' => array(), + 'ar_from' => array(), + 'ar_where' => array(), + 'ar_like' => array(), + 'ar_orderby' => array(), + 'ar_keys' => array(), + 'ar_limit' => FALSE, + 'ar_order' => FALSE + ); + + $this->_reset_run($ar_reset_items); + } +} + +/* End of file DB_active_rec.php */ +/* Location: ./system/database/DB_active_rec.php */ \ No newline at end of file diff --git a/api/system/database/DB_cache.php b/api/system/database/DB_cache.php new file mode 100644 index 0000000..ad1c28d --- /dev/null +++ b/api/system/database/DB_cache.php @@ -0,0 +1,195 @@ +CI + // and load the file helper since we use it a lot + $this->CI =& get_instance(); + $this->db =& $db; + $this->CI->load->helper('file'); + } + + // -------------------------------------------------------------------- + + /** + * Set Cache Directory Path + * + * @access public + * @param string the path to the cache directory + * @return bool + */ + function check_path($path = '') + { + if ($path == '') + { + if ($this->db->cachedir == '') + { + return $this->db->cache_off(); + } + + $path = $this->db->cachedir; + } + + // Add a trailing slash to the path if needed + $path = preg_replace("/(.+?)\/*$/", "\\1/", $path); + + if ( ! is_dir($path) OR ! is_really_writable($path)) + { + // If the path is wrong we'll turn off caching + return $this->db->cache_off(); + } + + $this->db->cachedir = $path; + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Retrieve a cached query + * + * The URI being requested will become the name of the cache sub-folder. + * An MD5 hash of the SQL statement will become the cache file name + * + * @access public + * @return string + */ + function read($sql) + { + if ( ! $this->check_path()) + { + return $this->db->cache_off(); + } + + $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); + + $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); + + $filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql); + + if (FALSE === ($cachedata = read_file($filepath))) + { + return FALSE; + } + + return unserialize($cachedata); + } + + // -------------------------------------------------------------------- + + /** + * Write a query to a cache file + * + * @access public + * @return bool + */ + function write($sql, $object) + { + if ( ! $this->check_path()) + { + return $this->db->cache_off(); + } + + $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); + + $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); + + $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; + + $filename = md5($sql); + + if ( ! @is_dir($dir_path)) + { + if ( ! @mkdir($dir_path, DIR_WRITE_MODE)) + { + return FALSE; + } + + @chmod($dir_path, DIR_WRITE_MODE); + } + + if (write_file($dir_path.$filename, serialize($object)) === FALSE) + { + return FALSE; + } + + @chmod($dir_path.$filename, FILE_WRITE_MODE); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Delete cache files within a particular directory + * + * @access public + * @return bool + */ + function delete($segment_one = '', $segment_two = '') + { + if ($segment_one == '') + { + $segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1); + } + + if ($segment_two == '') + { + $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); + } + + $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; + + delete_files($dir_path, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Delete all existing cache files + * + * @access public + * @return bool + */ + function delete_all() + { + delete_files($this->db->cachedir, TRUE); + } + +} + + +/* End of file DB_cache.php */ +/* Location: ./system/database/DB_cache.php */ \ No newline at end of file diff --git a/api/system/database/DB_driver.php b/api/system/database/DB_driver.php new file mode 100644 index 0000000..775fd33 --- /dev/null +++ b/api/system/database/DB_driver.php @@ -0,0 +1,1410 @@ + $val) + { + $this->$key = $val; + } + } + + log_message('debug', 'Database Driver Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize Database Settings + * + * @access private Called by the constructor + * @param mixed + * @return void + */ + function initialize() + { + // If an existing connection resource is available + // there is no need to connect and select the database + if (is_resource($this->conn_id) OR is_object($this->conn_id)) + { + return TRUE; + } + + // ---------------------------------------------------------------- + + // Connect to the database and set the connection ID + $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect(); + + // No connection resource? Throw an error + if ( ! $this->conn_id) + { + log_message('error', 'Unable to connect to the database'); + + if ($this->db_debug) + { + $this->display_error('db_unable_to_connect'); + } + return FALSE; + } + + // ---------------------------------------------------------------- + + // Select the DB... assuming a database name is specified in the config file + if ($this->database != '') + { + if ( ! $this->db_select()) + { + log_message('error', 'Unable to select database: '.$this->database); + + if ($this->db_debug) + { + $this->display_error('db_unable_to_select', $this->database); + } + return FALSE; + } + else + { + // We've selected the DB. Now we set the character set + if ( ! $this->db_set_charset($this->char_set, $this->dbcollat)) + { + return FALSE; + } + + return TRUE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat)) + { + log_message('error', 'Unable to set database connection charset: '.$this->char_set); + + if ($this->db_debug) + { + $this->display_error('db_unable_to_set_charset', $this->char_set); + } + + return FALSE; + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * The name of the platform in use (mysql, mssql, etc...) + * + * @access public + * @return string + */ + function platform() + { + return $this->dbdriver; + } + + // -------------------------------------------------------------------- + + /** + * Database Version Number. Returns a string containing the + * version of the database being used + * + * @access public + * @return string + */ + function version() + { + if (FALSE === ($sql = $this->_version())) + { + if ($this->db_debug) + { + return $this->display_error('db_unsupported_function'); + } + return FALSE; + } + + // Some DBs have functions that return the version, and don't run special + // SQL queries per se. In these instances, just return the result. + $driver_version_exceptions = array('oci8', 'sqlite', 'cubrid'); + + if (in_array($this->dbdriver, $driver_version_exceptions)) + { + return $sql; + } + else + { + $query = $this->query($sql); + return $query->row('ver'); + } + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * Accepts an SQL string as input and returns a result object upon + * successful execution of a "read" type query. Returns boolean TRUE + * upon successful execution of a "write" type query. Returns boolean + * FALSE upon failure, and if the $db_debug variable is set to TRUE + * will raise an error. + * + * @access public + * @param string An SQL query string + * @param array An array of binding data + * @return mixed + */ + function query($sql, $binds = FALSE, $return_object = TRUE) + { + if ($sql == '') + { + if ($this->db_debug) + { + log_message('error', 'Invalid query: '.$sql); + return $this->display_error('db_invalid_query'); + } + return FALSE; + } + + // Verify table prefix and replace if necessary + if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) ) + { + $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql); + } + + // Compile binds if needed + if ($binds !== FALSE) + { + $sql = $this->compile_binds($sql, $binds); + } + + // Is query caching enabled? If the query is a "read type" + // we will load the caching class and return the previously + // cached query if it exists + if ($this->cache_on == TRUE AND stristr($sql, 'SELECT')) + { + if ($this->_cache_init()) + { + $this->load_rdriver(); + if (FALSE !== ($cache = $this->CACHE->read($sql))) + { + return $cache; + } + } + } + + // Save the query for debugging + if ($this->save_queries == TRUE) + { + $this->queries[] = $sql; + } + + // Start the Query Timer + $time_start = list($sm, $ss) = explode(' ', microtime()); + + // Run the Query + if (FALSE === ($this->result_id = $this->simple_query($sql))) + { + if ($this->save_queries == TRUE) + { + $this->query_times[] = 0; + } + + // This will trigger a rollback if transactions are being used + $this->_trans_status = FALSE; + + if ($this->db_debug) + { + // grab the error number and message now, as we might run some + // additional queries before displaying the error + $error_no = $this->_error_number(); + $error_msg = $this->_error_message(); + + // We call this function in order to roll-back queries + // if transactions are enabled. If we don't call this here + // the error message will trigger an exit, causing the + // transactions to remain in limbo. + $this->trans_complete(); + + // Log and display errors + log_message('error', 'Query error: '.$error_msg); + return $this->display_error( + array( + 'Error Number: '.$error_no, + $error_msg, + $sql + ) + ); + } + + return FALSE; + } + + // Stop and aggregate the query time results + $time_end = list($em, $es) = explode(' ', microtime()); + $this->benchmark += ($em + $es) - ($sm + $ss); + + if ($this->save_queries == TRUE) + { + $this->query_times[] = ($em + $es) - ($sm + $ss); + } + + // Increment the query counter + $this->query_count++; + + // Was the query a "write" type? + // If so we'll simply return true + if ($this->is_write_type($sql) === TRUE) + { + // If caching is enabled we'll auto-cleanup any + // existing files related to this particular URI + if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init()) + { + $this->CACHE->delete(); + } + + return TRUE; + } + + // Return TRUE if we don't need to create a result object + // Currently only the Oracle driver uses this when stored + // procedures are used + if ($return_object !== TRUE) + { + return TRUE; + } + + // Load and instantiate the result driver + + $driver = $this->load_rdriver(); + $RES = new $driver(); + $RES->conn_id = $this->conn_id; + $RES->result_id = $this->result_id; + + if ($this->dbdriver == 'oci8') + { + $RES->stmt_id = $this->stmt_id; + $RES->curs_id = NULL; + $RES->limit_used = $this->limit_used; + $this->stmt_id = FALSE; + } + + // oci8 vars must be set before calling this + $RES->num_rows = $RES->num_rows(); + + // Is query caching enabled? If so, we'll serialize the + // result object and save it to a cache file. + if ($this->cache_on == TRUE AND $this->_cache_init()) + { + // We'll create a new instance of the result object + // only without the platform specific driver since + // we can't use it with cached data (the query result + // resource ID won't be any good once we've cached the + // result object, so we'll have to compile the data + // and save it) + $CR = new CI_DB_result(); + $CR->num_rows = $RES->num_rows(); + $CR->result_object = $RES->result_object(); + $CR->result_array = $RES->result_array(); + + // Reset these since cached objects can not utilize resource IDs. + $CR->conn_id = NULL; + $CR->result_id = NULL; + + $this->CACHE->write($sql, $CR); + } + + return $RES; + } + + // -------------------------------------------------------------------- + + /** + * Load the result drivers + * + * @access public + * @return string the name of the result class + */ + function load_rdriver() + { + $driver = 'CI_DB_'.$this->dbdriver.'_result'; + + if ( ! class_exists($driver)) + { + include_once(BASEPATH.'database/DB_result.php'); + include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php'); + } + + return $driver; + } + + // -------------------------------------------------------------------- + + /** + * Simple Query + * This is a simplified version of the query() function. Internally + * we only use it when running transaction commands since they do + * not require all the features of the main query() function. + * + * @access public + * @param string the sql query + * @return mixed + */ + function simple_query($sql) + { + if ( ! $this->conn_id) + { + $this->initialize(); + } + + return $this->_execute($sql); + } + + // -------------------------------------------------------------------- + + /** + * Disable Transactions + * This permits transactions to be disabled at run-time. + * + * @access public + * @return void + */ + function trans_off() + { + $this->trans_enabled = FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Enable/disable Transaction Strict Mode + * When strict mode is enabled, if you are running multiple groups of + * transactions, if one group fails all groups will be rolled back. + * If strict mode is disabled, each group is treated autonomously, meaning + * a failure of one group will not affect any others + * + * @access public + * @return void + */ + function trans_strict($mode = TRUE) + { + $this->trans_strict = is_bool($mode) ? $mode : TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Start Transaction + * + * @access public + * @return void + */ + function trans_start($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return FALSE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + $this->_trans_depth += 1; + return; + } + + $this->trans_begin($test_mode); + } + + // -------------------------------------------------------------------- + + /** + * Complete Transaction + * + * @access public + * @return bool + */ + function trans_complete() + { + if ( ! $this->trans_enabled) + { + return FALSE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 1) + { + $this->_trans_depth -= 1; + return TRUE; + } + + // The query() function will set this flag to FALSE in the event that a query failed + if ($this->_trans_status === FALSE) + { + $this->trans_rollback(); + + // If we are NOT running in strict mode, we will reset + // the _trans_status flag so that subsequent groups of transactions + // will be permitted. + if ($this->trans_strict === FALSE) + { + $this->_trans_status = TRUE; + } + + log_message('debug', 'DB Transaction Failure'); + return FALSE; + } + + $this->trans_commit(); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Lets you retrieve the transaction flag to determine if it has failed + * + * @access public + * @return bool + */ + function trans_status() + { + return $this->_trans_status; + } + + // -------------------------------------------------------------------- + + /** + * Compile Bindings + * + * @access public + * @param string the sql statement + * @param array an array of bind data + * @return string + */ + function compile_binds($sql, $binds) + { + if (strpos($sql, $this->bind_marker) === FALSE) + { + return $sql; + } + + if ( ! is_array($binds)) + { + $binds = array($binds); + } + + // Get the sql segments around the bind markers + $segments = explode($this->bind_marker, $sql); + + // The count of bind should be 1 less then the count of segments + // If there are more bind arguments trim it down + if (count($binds) >= count($segments)) { + $binds = array_slice($binds, 0, count($segments)-1); + } + + // Construct the binded query + $result = $segments[0]; + $i = 0; + foreach ($binds as $bind) + { + $result .= $this->escape($bind); + $result .= $segments[++$i]; + } + + return $result; + } + + // -------------------------------------------------------------------- + + /** + * Determines if a query is a "write" type. + * + * @access public + * @param string An SQL query string + * @return boolean + */ + function is_write_type($sql) + { + if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql)) + { + return FALSE; + } + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Calculate the aggregate query elapsed time + * + * @access public + * @param integer The number of decimal places + * @return integer + */ + function elapsed_time($decimals = 6) + { + return number_format($this->benchmark, $decimals); + } + + // -------------------------------------------------------------------- + + /** + * Returns the total number of queries + * + * @access public + * @return integer + */ + function total_queries() + { + return $this->query_count; + } + + // -------------------------------------------------------------------- + + /** + * Returns the last query that was executed + * + * @access public + * @return void + */ + function last_query() + { + return end($this->queries); + } + + // -------------------------------------------------------------------- + + /** + * "Smart" Escape String + * + * Escapes data based on type + * Sets boolean and null types + * + * @access public + * @param string + * @return mixed + */ + function escape($str) + { + if (is_string($str)) + { + $str = "'".$this->escape_str($str)."'"; + } + elseif (is_bool($str)) + { + $str = ($str === FALSE) ? 0 : 1; + } + elseif (is_null($str)) + { + $str = 'NULL'; + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Escape LIKE String + * + * Calls the individual driver for platform + * specific escaping for LIKE conditions + * + * @access public + * @param string + * @return mixed + */ + function escape_like_str($str) + { + return $this->escape_str($str, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Primary + * + * Retrieves the primary key. It assumes that the row in the first + * position is the primary key + * + * @access public + * @param string the table name + * @return string + */ + function primary($table = '') + { + $fields = $this->list_fields($table); + + if ( ! is_array($fields)) + { + return FALSE; + } + + return current($fields); + } + + // -------------------------------------------------------------------- + + /** + * Returns an array of table names + * + * @access public + * @return array + */ + function list_tables($constrain_by_prefix = FALSE) + { + // Is there a cached result? + if (isset($this->data_cache['table_names'])) + { + return $this->data_cache['table_names']; + } + + if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix))) + { + if ($this->db_debug) + { + return $this->display_error('db_unsupported_function'); + } + return FALSE; + } + + $retval = array(); + $query = $this->query($sql); + + if ($query->num_rows() > 0) + { + foreach ($query->result_array() as $row) + { + if (isset($row['TABLE_NAME'])) + { + $retval[] = $row['TABLE_NAME']; + } + else + { + $retval[] = array_shift($row); + } + } + } + + $this->data_cache['table_names'] = $retval; + return $this->data_cache['table_names']; + } + + // -------------------------------------------------------------------- + + /** + * Determine if a particular table exists + * @access public + * @return boolean + */ + function table_exists($table_name) + { + return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Fetch MySQL Field Names + * + * @access public + * @param string the table name + * @return array + */ + function list_fields($table = '') + { + // Is there a cached result? + if (isset($this->data_cache['field_names'][$table])) + { + return $this->data_cache['field_names'][$table]; + } + + if ($table == '') + { + if ($this->db_debug) + { + return $this->display_error('db_field_param_missing'); + } + return FALSE; + } + + if (FALSE === ($sql = $this->_list_columns($table))) + { + if ($this->db_debug) + { + return $this->display_error('db_unsupported_function'); + } + return FALSE; + } + + $query = $this->query($sql); + + $retval = array(); + foreach ($query->result_array() as $row) + { + if (isset($row['COLUMN_NAME'])) + { + $retval[] = $row['COLUMN_NAME']; + } + else + { + $retval[] = current($row); + } + } + + $this->data_cache['field_names'][$table] = $retval; + return $this->data_cache['field_names'][$table]; + } + + // -------------------------------------------------------------------- + + /** + * Determine if a particular field exists + * @access public + * @param string + * @param string + * @return boolean + */ + function field_exists($field_name, $table_name) + { + return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Returns an object with field data + * + * @access public + * @param string the table name + * @return object + */ + function field_data($table = '') + { + if ($table == '') + { + if ($this->db_debug) + { + return $this->display_error('db_field_param_missing'); + } + return FALSE; + } + + $query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE))); + + return $query->field_data(); + } + + // -------------------------------------------------------------------- + + /** + * Generate an insert string + * + * @access public + * @param string the table upon which the query will be performed + * @param array an associative array data of key/values + * @return string + */ + function insert_string($table, $data) + { + $fields = array(); + $values = array(); + + foreach ($data as $key => $val) + { + $fields[] = $this->_escape_identifiers($key); + $values[] = $this->escape($val); + } + + return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values); + } + + // -------------------------------------------------------------------- + + /** + * Generate an update string + * + * @access public + * @param string the table upon which the query will be performed + * @param array an associative array data of key/values + * @param mixed the "where" statement + * @return string + */ + function update_string($table, $data, $where) + { + if ($where == '') + { + return false; + } + + $fields = array(); + foreach ($data as $key => $val) + { + $fields[$this->_protect_identifiers($key)] = $this->escape($val); + } + + if ( ! is_array($where)) + { + $dest = array($where); + } + else + { + $dest = array(); + foreach ($where as $key => $val) + { + $prefix = (count($dest) == 0) ? '' : ' AND '; + + if ($val !== '') + { + if ( ! $this->_has_operator($key)) + { + $key .= ' ='; + } + + $val = ' '.$this->escape($val); + } + + $dest[] = $prefix.$key.$val; + } + } + + return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest); + } + + // -------------------------------------------------------------------- + + /** + * Tests whether the string has an SQL operator + * + * @access private + * @param string + * @return bool + */ + function _has_operator($str) + { + $str = trim($str); + if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str)) + { + return FALSE; + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Enables a native PHP function to be run, using a platform agnostic wrapper. + * + * @access public + * @param string the function name + * @param mixed any parameters needed by the function + * @return mixed + */ + function call_function($function) + { + $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_'; + + if (FALSE === strpos($driver, $function)) + { + $function = $driver.$function; + } + + if ( ! function_exists($function)) + { + if ($this->db_debug) + { + return $this->display_error('db_unsupported_function'); + } + return FALSE; + } + else + { + $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null; + if (is_null($args)) + { + return call_user_func($function); + } + else + { + return call_user_func_array($function, $args); + } + } + } + + // -------------------------------------------------------------------- + + /** + * Set Cache Directory Path + * + * @access public + * @param string the path to the cache directory + * @return void + */ + function cache_set_path($path = '') + { + $this->cachedir = $path; + } + + // -------------------------------------------------------------------- + + /** + * Enable Query Caching + * + * @access public + * @return void + */ + function cache_on() + { + $this->cache_on = TRUE; + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Disable Query Caching + * + * @access public + * @return void + */ + function cache_off() + { + $this->cache_on = FALSE; + return FALSE; + } + + + // -------------------------------------------------------------------- + + /** + * Delete the cache files associated with a particular URI + * + * @access public + * @return void + */ + function cache_delete($segment_one = '', $segment_two = '') + { + if ( ! $this->_cache_init()) + { + return FALSE; + } + return $this->CACHE->delete($segment_one, $segment_two); + } + + // -------------------------------------------------------------------- + + /** + * Delete All cache files + * + * @access public + * @return void + */ + function cache_delete_all() + { + if ( ! $this->_cache_init()) + { + return FALSE; + } + + return $this->CACHE->delete_all(); + } + + // -------------------------------------------------------------------- + + /** + * Initialize the Cache Class + * + * @access private + * @return void + */ + function _cache_init() + { + if (is_object($this->CACHE) AND class_exists('CI_DB_Cache')) + { + return TRUE; + } + + if ( ! class_exists('CI_DB_Cache')) + { + if ( ! @include(BASEPATH.'database/DB_cache.php')) + { + return $this->cache_off(); + } + } + + $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @return void + */ + function close() + { + if (is_resource($this->conn_id) OR is_object($this->conn_id)) + { + $this->_close($this->conn_id); + } + $this->conn_id = FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Display an error message + * + * @access public + * @param string the error message + * @param string any "swap" values + * @param boolean whether to localize the message + * @return string sends the application/error_db.php template + */ + function display_error($error = '', $swap = '', $native = FALSE) + { + $LANG =& load_class('Lang', 'core'); + $LANG->load('db'); + + $heading = $LANG->line('db_error_heading'); + + if ($native == TRUE) + { + $message = $error; + } + else + { + $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error; + } + + // Find the most likely culprit of the error by going through + // the backtrace until the source file is no longer in the + // database folder. + + $trace = debug_backtrace(); + + foreach ($trace as $call) + { + if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE) + { + // Found it - use a relative path for safety + $message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']); + $message[] = 'Line Number: '.$call['line']; + + break; + } + } + + $error =& load_class('Exceptions', 'core'); + echo $error->show_error($heading, $message, 'error_db'); + exit; + } + + // -------------------------------------------------------------------- + + /** + * Protect Identifiers + * + * This function adds backticks if appropriate based on db type + * + * @access private + * @param mixed the item to escape + * @return mixed the item with backticks + */ + function protect_identifiers($item, $prefix_single = FALSE) + { + return $this->_protect_identifiers($item, $prefix_single); + } + + // -------------------------------------------------------------------- + + /** + * Protect Identifiers + * + * This function is used extensively by the Active Record class, and by + * a couple functions in this class. + * It takes a column or table name (optionally with an alias) and inserts + * the table prefix onto it. Some logic is necessary in order to deal with + * column names that include the path. Consider a query like this: + * + * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table + * + * Or a query with aliasing: + * + * SELECT m.member_id, m.member_name FROM members AS m + * + * Since the column name can include up to four segments (host, DB, table, column) + * or also have an alias prefix, we need to do a bit of work to figure this out and + * insert the table prefix (if it exists) in the proper position, and escape only + * the correct identifiers. + * + * @access private + * @param string + * @param bool + * @param mixed + * @param bool + * @return string + */ + function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE) + { + if ( ! is_bool($protect_identifiers)) + { + $protect_identifiers = $this->_protect_identifiers; + } + + if (is_array($item)) + { + $escaped_array = array(); + + foreach ($item as $k => $v) + { + $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v); + } + + return $escaped_array; + } + + // Convert tabs or multiple spaces into single spaces + $item = preg_replace('/[\t ]+/', ' ', $item); + + // If the item has an alias declaration we remove it and set it aside. + // Basically we remove everything to the right of the first space + if (strpos($item, ' ') !== FALSE) + { + $alias = strstr($item, ' '); + $item = substr($item, 0, - strlen($alias)); + } + else + { + $alias = ''; + } + + // This is basically a bug fix for queries that use MAX, MIN, etc. + // If a parenthesis is found we know that we do not need to + // escape the data or add a prefix. There's probably a more graceful + // way to deal with this, but I'm not thinking of it -- Rick + if (strpos($item, '(') !== FALSE) + { + return $item.$alias; + } + + // Break the string apart if it contains periods, then insert the table prefix + // in the correct location, assuming the period doesn't indicate that we're dealing + // with an alias. While we're at it, we will escape the components + if (strpos($item, '.') !== FALSE) + { + $parts = explode('.', $item); + + // Does the first segment of the exploded item match + // one of the aliases previously identified? If so, + // we have nothing more to do other than escape the item + if (in_array($parts[0], $this->ar_aliased_tables)) + { + if ($protect_identifiers === TRUE) + { + foreach ($parts as $key => $val) + { + if ( ! in_array($val, $this->_reserved_identifiers)) + { + $parts[$key] = $this->_escape_identifiers($val); + } + } + + $item = implode('.', $parts); + } + return $item.$alias; + } + + // Is there a table prefix defined in the config file? If not, no need to do anything + if ($this->dbprefix != '') + { + // We now add the table prefix based on some logic. + // Do we have 4 segments (hostname.database.table.column)? + // If so, we add the table prefix to the column name in the 3rd segment. + if (isset($parts[3])) + { + $i = 2; + } + // Do we have 3 segments (database.table.column)? + // If so, we add the table prefix to the column name in 2nd position + elseif (isset($parts[2])) + { + $i = 1; + } + // Do we have 2 segments (table.column)? + // If so, we add the table prefix to the column name in 1st segment + else + { + $i = 0; + } + + // This flag is set when the supplied $item does not contain a field name. + // This can happen when this function is being called from a JOIN. + if ($field_exists == FALSE) + { + $i++; + } + + // Verify table prefix and replace if necessary + if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0) + { + $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]); + } + + // We only add the table prefix if it does not already exist + if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix) + { + $parts[$i] = $this->dbprefix.$parts[$i]; + } + + // Put the parts back together + $item = implode('.', $parts); + } + + if ($protect_identifiers === TRUE) + { + $item = $this->_escape_identifiers($item); + } + + return $item.$alias; + } + + // Is there a table prefix? If not, no need to insert it + if ($this->dbprefix != '') + { + // Verify table prefix and replace if necessary + if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0) + { + $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item); + } + + // Do we prefix an item with no segments? + if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix) + { + $item = $this->dbprefix.$item; + } + } + + if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers)) + { + $item = $this->_escape_identifiers($item); + } + + return $item.$alias; + } + + // -------------------------------------------------------------------- + + /** + * Dummy method that allows Active Record class to be disabled + * + * This function is used extensively by every db driver. + * + * @return void + */ + protected function _reset_select() + { + } + +} + +/* End of file DB_driver.php */ +/* Location: ./system/database/DB_driver.php */ \ No newline at end of file diff --git a/api/system/database/DB_forge.php b/api/system/database/DB_forge.php new file mode 100644 index 0000000..6bc4041 --- /dev/null +++ b/api/system/database/DB_forge.php @@ -0,0 +1,382 @@ +db + $CI =& get_instance(); + $this->db =& $CI->db; + log_message('debug', "Database Forge Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Create database + * + * @access public + * @param string the database name + * @return bool + */ + function create_database($db_name) + { + $sql = $this->_create_database($db_name); + + if (is_bool($sql)) + { + return $sql; + } + + return $this->db->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Drop database + * + * @access public + * @param string the database name + * @return bool + */ + function drop_database($db_name) + { + $sql = $this->_drop_database($db_name); + + if (is_bool($sql)) + { + return $sql; + } + + return $this->db->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Add Key + * + * @access public + * @param string key + * @param string type + * @return void + */ + function add_key($key = '', $primary = FALSE) + { + if (is_array($key)) + { + foreach ($key as $one) + { + $this->add_key($one, $primary); + } + + return; + } + + if ($key == '') + { + show_error('Key information is required for that operation.'); + } + + if ($primary === TRUE) + { + $this->primary_keys[] = $key; + } + else + { + $this->keys[] = $key; + } + } + + // -------------------------------------------------------------------- + + /** + * Add Field + * + * @access public + * @param string collation + * @return void + */ + function add_field($field = '') + { + if ($field == '') + { + show_error('Field information is required.'); + } + + if (is_string($field)) + { + if ($field == 'id') + { + $this->add_field(array( + 'id' => array( + 'type' => 'INT', + 'constraint' => 9, + 'auto_increment' => TRUE + ) + )); + $this->add_key('id', TRUE); + } + else + { + if (strpos($field, ' ') === FALSE) + { + show_error('Field information is required for that operation.'); + } + + $this->fields[] = $field; + } + } + + if (is_array($field)) + { + $this->fields = array_merge($this->fields, $field); + } + + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access public + * @param string the table name + * @return bool + */ + function create_table($table = '', $if_not_exists = FALSE) + { + if ($table == '') + { + show_error('A table name is required for that operation.'); + } + + if (count($this->fields) == 0) + { + show_error('Field information is required.'); + } + + $sql = $this->_create_table($this->db->dbprefix.$table, $this->fields, $this->primary_keys, $this->keys, $if_not_exists); + + $this->_reset(); + return $this->db->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access public + * @param string the table name + * @return bool + */ + function drop_table($table_name) + { + $sql = $this->_drop_table($this->db->dbprefix.$table_name); + + if (is_bool($sql)) + { + return $sql; + } + + return $this->db->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Rename Table + * + * @access public + * @param string the old table name + * @param string the new table name + * @return bool + */ + function rename_table($table_name, $new_table_name) + { + if ($table_name == '' OR $new_table_name == '') + { + show_error('A table name is required for that operation.'); + } + + $sql = $this->_rename_table($this->db->dbprefix.$table_name, $this->db->dbprefix.$new_table_name); + return $this->db->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Column Add + * + * @access public + * @param string the table name + * @param string the column name + * @param string the column definition + * @return bool + */ + function add_column($table = '', $field = array(), $after_field = '') + { + if ($table == '') + { + show_error('A table name is required for that operation.'); + } + + // add field info into field array, but we can only do one at a time + // so we cycle through + + foreach ($field as $k => $v) + { + $this->add_field(array($k => $field[$k])); + + if (count($this->fields) == 0) + { + show_error('Field information is required.'); + } + + $sql = $this->_alter_table('ADD', $this->db->dbprefix.$table, $this->fields, $after_field); + + $this->_reset(); + + if ($this->db->query($sql) === FALSE) + { + return FALSE; + } + } + + return TRUE; + + } + + // -------------------------------------------------------------------- + + /** + * Column Drop + * + * @access public + * @param string the table name + * @param string the column name + * @return bool + */ + function drop_column($table = '', $column_name = '') + { + + if ($table == '') + { + show_error('A table name is required for that operation.'); + } + + if ($column_name == '') + { + show_error('A column name is required for that operation.'); + } + + $sql = $this->_alter_table('DROP', $this->db->dbprefix.$table, $column_name); + + return $this->db->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Column Modify + * + * @access public + * @param string the table name + * @param string the column name + * @param string the column definition + * @return bool + */ + function modify_column($table = '', $field = array()) + { + if ($table == '') + { + show_error('A table name is required for that operation.'); + } + + // add field info into field array, but we can only do one at a time + // so we cycle through + + foreach ($field as $k => $v) + { + // If no name provided, use the current name + if ( ! isset($field[$k]['name'])) + { + $field[$k]['name'] = $k; + } + + $this->add_field(array($k => $field[$k])); + + if (count($this->fields) == 0) + { + show_error('Field information is required.'); + } + + $sql = $this->_alter_table('CHANGE', $this->db->dbprefix.$table, $this->fields); + + $this->_reset(); + + if ($this->db->query($sql) === FALSE) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Reset + * + * Resets table creation vars + * + * @access private + * @return void + */ + function _reset() + { + $this->fields = array(); + $this->keys = array(); + $this->primary_keys = array(); + } + +} + +/* End of file DB_forge.php */ +/* Location: ./system/database/DB_forge.php */ \ No newline at end of file diff --git a/api/system/database/DB_result.php b/api/system/database/DB_result.php new file mode 100644 index 0000000..48d66c8 --- /dev/null +++ b/api/system/database/DB_result.php @@ -0,0 +1,410 @@ +result_array(); + else if ($type == 'object') return $this->result_object(); + else return $this->custom_result_object($type); + } + + // -------------------------------------------------------------------- + + /** + * Custom query result. + * + * @param class_name A string that represents the type of object you want back + * @return array of objects + */ + public function custom_result_object($class_name) + { + if (array_key_exists($class_name, $this->custom_result_object)) + { + return $this->custom_result_object[$class_name]; + } + + if ($this->result_id === FALSE OR $this->num_rows() == 0) + { + return array(); + } + + // add the data to the object + $this->_data_seek(0); + $result_object = array(); + + while ($row = $this->_fetch_object()) + { + $object = new $class_name(); + + foreach ($row as $key => $value) + { + $object->$key = $value; + } + + $result_object[] = $object; + } + + // return the array + return $this->custom_result_object[$class_name] = $result_object; + } + + // -------------------------------------------------------------------- + + /** + * Query result. "object" version. + * + * @access public + * @return object + */ + public function result_object() + { + if (count($this->result_object) > 0) + { + return $this->result_object; + } + + // In the event that query caching is on the result_id variable + // will return FALSE since there isn't a valid SQL resource so + // we'll simply return an empty array. + if ($this->result_id === FALSE OR $this->num_rows() == 0) + { + return array(); + } + + $this->_data_seek(0); + while ($row = $this->_fetch_object()) + { + $this->result_object[] = $row; + } + + return $this->result_object; + } + + // -------------------------------------------------------------------- + + /** + * Query result. "array" version. + * + * @access public + * @return array + */ + public function result_array() + { + if (count($this->result_array) > 0) + { + return $this->result_array; + } + + // In the event that query caching is on the result_id variable + // will return FALSE since there isn't a valid SQL resource so + // we'll simply return an empty array. + if ($this->result_id === FALSE OR $this->num_rows() == 0) + { + return array(); + } + + $this->_data_seek(0); + while ($row = $this->_fetch_assoc()) + { + $this->result_array[] = $row; + } + + return $this->result_array; + } + + // -------------------------------------------------------------------- + + /** + * Query result. Acts as a wrapper function for the following functions. + * + * @access public + * @param string + * @param string can be "object" or "array" + * @return mixed either a result object or array + */ + public function row($n = 0, $type = 'object') + { + if ( ! is_numeric($n)) + { + // We cache the row data for subsequent uses + if ( ! is_array($this->row_data)) + { + $this->row_data = $this->row_array(0); + } + + // array_key_exists() instead of isset() to allow for MySQL NULL values + if (array_key_exists($n, $this->row_data)) + { + return $this->row_data[$n]; + } + // reset the $n variable if the result was not achieved + $n = 0; + } + + if ($type == 'object') return $this->row_object($n); + else if ($type == 'array') return $this->row_array($n); + else return $this->custom_row_object($n, $type); + } + + // -------------------------------------------------------------------- + + /** + * Assigns an item into a particular column slot + * + * @access public + * @return object + */ + public function set_row($key, $value = NULL) + { + // We cache the row data for subsequent uses + if ( ! is_array($this->row_data)) + { + $this->row_data = $this->row_array(0); + } + + if (is_array($key)) + { + foreach ($key as $k => $v) + { + $this->row_data[$k] = $v; + } + + return; + } + + if ($key != '' AND ! is_null($value)) + { + $this->row_data[$key] = $value; + } + } + + // -------------------------------------------------------------------- + + /** + * Returns a single result row - custom object version + * + * @access public + * @return object + */ + public function custom_row_object($n, $type) + { + $result = $this->custom_result_object($type); + + if (count($result) == 0) + { + return $result; + } + + if ($n != $this->current_row AND isset($result[$n])) + { + $this->current_row = $n; + } + + return $result[$this->current_row]; + } + + /** + * Returns a single result row - object version + * + * @access public + * @return object + */ + public function row_object($n = 0) + { + $result = $this->result_object(); + + if (count($result) == 0) + { + return $result; + } + + if ($n != $this->current_row AND isset($result[$n])) + { + $this->current_row = $n; + } + + return $result[$this->current_row]; + } + + // -------------------------------------------------------------------- + + /** + * Returns a single result row - array version + * + * @access public + * @return array + */ + public function row_array($n = 0) + { + $result = $this->result_array(); + + if (count($result) == 0) + { + return $result; + } + + if ($n != $this->current_row AND isset($result[$n])) + { + $this->current_row = $n; + } + + return $result[$this->current_row]; + } + + + // -------------------------------------------------------------------- + + /** + * Returns the "first" row + * + * @access public + * @return object + */ + public function first_row($type = 'object') + { + $result = $this->result($type); + + if (count($result) == 0) + { + return $result; + } + return $result[0]; + } + + // -------------------------------------------------------------------- + + /** + * Returns the "last" row + * + * @access public + * @return object + */ + public function last_row($type = 'object') + { + $result = $this->result($type); + + if (count($result) == 0) + { + return $result; + } + return $result[count($result) -1]; + } + + // -------------------------------------------------------------------- + + /** + * Returns the "next" row + * + * @access public + * @return object + */ + public function next_row($type = 'object') + { + $result = $this->result($type); + + if (count($result) == 0) + { + return $result; + } + + if (isset($result[$this->current_row + 1])) + { + ++$this->current_row; + } + + return $result[$this->current_row]; + } + + // -------------------------------------------------------------------- + + /** + * Returns the "previous" row + * + * @access public + * @return object + */ + public function previous_row($type = 'object') + { + $result = $this->result($type); + + if (count($result) == 0) + { + return $result; + } + + if (isset($result[$this->current_row - 1])) + { + --$this->current_row; + } + return $result[$this->current_row]; + } + + // -------------------------------------------------------------------- + + /** + * The following functions are normally overloaded by the identically named + * methods in the platform-specific driver -- except when query caching + * is used. When caching is enabled we do not load the other driver. + * These functions are primarily here to prevent undefined function errors + * when a cached result object is in use. They are not otherwise fully + * operational due to the unavailability of the database resource IDs with + * cached results. + */ + public function num_rows() { return $this->num_rows; } + public function num_fields() { return 0; } + public function list_fields() { return array(); } + public function field_data() { return array(); } + public function free_result() { return TRUE; } + protected function _data_seek() { return TRUE; } + protected function _fetch_assoc() { return array(); } + protected function _fetch_object() { return array(); } + +} +// END DB_result class + +/* End of file DB_result.php */ +/* Location: ./system/database/DB_result.php */ diff --git a/api/system/database/DB_utility.php b/api/system/database/DB_utility.php new file mode 100644 index 0000000..52196b7 --- /dev/null +++ b/api/system/database/DB_utility.php @@ -0,0 +1,414 @@ +db + $CI =& get_instance(); + $this->db =& $CI->db; + + log_message('debug', "Database Utility Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * List databases + * + * @access public + * @return bool + */ + function list_databases() + { + // Is there a cached result? + if (isset($this->data_cache['db_names'])) + { + return $this->data_cache['db_names']; + } + + $query = $this->db->query($this->_list_databases()); + $dbs = array(); + if ($query->num_rows() > 0) + { + foreach ($query->result_array() as $row) + { + $dbs[] = current($row); + } + } + + $this->data_cache['db_names'] = $dbs; + return $this->data_cache['db_names']; + } + + // -------------------------------------------------------------------- + + /** + * Determine if a particular database exists + * + * @access public + * @param string + * @return boolean + */ + function database_exists($database_name) + { + // Some databases won't have access to the list_databases() function, so + // this is intended to allow them to override with their own functions as + // defined in $driver_utility.php + if (method_exists($this, '_database_exists')) + { + return $this->_database_exists($database_name); + } + else + { + return ( ! in_array($database_name, $this->list_databases())) ? FALSE : TRUE; + } + } + + + // -------------------------------------------------------------------- + + /** + * Optimize Table + * + * @access public + * @param string the table name + * @return bool + */ + function optimize_table($table_name) + { + $sql = $this->_optimize_table($table_name); + + if (is_bool($sql)) + { + show_error('db_must_use_set'); + } + + $query = $this->db->query($sql); + $res = $query->result_array(); + + // Note: Due to a bug in current() that affects some versions + // of PHP we can not pass function call directly into it + return current($res); + } + + // -------------------------------------------------------------------- + + /** + * Optimize Database + * + * @access public + * @return array + */ + function optimize_database() + { + $result = array(); + foreach ($this->db->list_tables() as $table_name) + { + $sql = $this->_optimize_table($table_name); + + if (is_bool($sql)) + { + return $sql; + } + + $query = $this->db->query($sql); + + // Build the result array... + // Note: Due to a bug in current() that affects some versions + // of PHP we can not pass function call directly into it + $res = $query->result_array(); + $res = current($res); + $key = str_replace($this->db->database.'.', '', current($res)); + $keys = array_keys($res); + unset($res[$keys[0]]); + + $result[$key] = $res; + } + + return $result; + } + + // -------------------------------------------------------------------- + + /** + * Repair Table + * + * @access public + * @param string the table name + * @return bool + */ + function repair_table($table_name) + { + $sql = $this->_repair_table($table_name); + + if (is_bool($sql)) + { + return $sql; + } + + $query = $this->db->query($sql); + + // Note: Due to a bug in current() that affects some versions + // of PHP we can not pass function call directly into it + $res = $query->result_array(); + return current($res); + } + + // -------------------------------------------------------------------- + + /** + * Generate CSV from a query result object + * + * @access public + * @param object The query result object + * @param string The delimiter - comma by default + * @param string The newline character - \n by default + * @param string The enclosure - double quote by default + * @return string + */ + function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"') + { + if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) + { + show_error('You must submit a valid result object'); + } + + $out = ''; + + // First generate the headings from the table column names + foreach ($query->list_fields() as $name) + { + $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim; + } + + $out = rtrim($out); + $out .= $newline; + + // Next blast through the result array and build out the rows + foreach ($query->result_array() as $row) + { + foreach ($row as $item) + { + $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim; + } + $out = rtrim($out); + $out .= $newline; + } + + return $out; + } + + // -------------------------------------------------------------------- + + /** + * Generate XML data from a query result object + * + * @access public + * @param object The query result object + * @param array Any preferences + * @return string + */ + function xml_from_result($query, $params = array()) + { + if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) + { + show_error('You must submit a valid result object'); + } + + // Set our default values + foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val) + { + if ( ! isset($params[$key])) + { + $params[$key] = $val; + } + } + + // Create variables for convenience + extract($params); + + // Load the xml helper + $CI =& get_instance(); + $CI->load->helper('xml'); + + // Generate the result + $xml = "<{$root}>".$newline; + foreach ($query->result_array() as $row) + { + $xml .= $tab."<{$element}>".$newline; + + foreach ($row as $key => $val) + { + $xml .= $tab.$tab."<{$key}>".xml_convert($val)."".$newline; + } + $xml .= $tab."".$newline; + } + $xml .= "".$newline; + + return $xml; + } + + // -------------------------------------------------------------------- + + /** + * Database Backup + * + * @access public + * @return void + */ + function backup($params = array()) + { + // If the parameters have not been submitted as an + // array then we know that it is simply the table + // name, which is a valid short cut. + if (is_string($params)) + { + $params = array('tables' => $params); + } + + // ------------------------------------------------------ + + // Set up our default preferences + $prefs = array( + 'tables' => array(), + 'ignore' => array(), + 'filename' => '', + 'format' => 'gzip', // gzip, zip, txt + 'add_drop' => TRUE, + 'add_insert' => TRUE, + 'newline' => "\n" + ); + + // Did the user submit any preferences? If so set them.... + if (count($params) > 0) + { + foreach ($prefs as $key => $val) + { + if (isset($params[$key])) + { + $prefs[$key] = $params[$key]; + } + } + } + + // ------------------------------------------------------ + + // Are we backing up a complete database or individual tables? + // If no table names were submitted we'll fetch the entire table list + if (count($prefs['tables']) == 0) + { + $prefs['tables'] = $this->db->list_tables(); + } + + // ------------------------------------------------------ + + // Validate the format + if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE)) + { + $prefs['format'] = 'txt'; + } + + // ------------------------------------------------------ + + // Is the encoder supported? If not, we'll either issue an + // error or use plain text depending on the debug settings + if (($prefs['format'] == 'gzip' AND ! @function_exists('gzencode')) + OR ($prefs['format'] == 'zip' AND ! @function_exists('gzcompress'))) + { + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_compression'); + } + + $prefs['format'] = 'txt'; + } + + // ------------------------------------------------------ + + // Set the filename if not provided - Only needed with Zip files + if ($prefs['filename'] == '' AND $prefs['format'] == 'zip') + { + $prefs['filename'] = (count($prefs['tables']) == 1) ? $prefs['tables'] : $this->db->database; + $prefs['filename'] .= '_'.date('Y-m-d_H-i', time()); + } + + // ------------------------------------------------------ + + // Was a Gzip file requested? + if ($prefs['format'] == 'gzip') + { + return gzencode($this->_backup($prefs)); + } + + // ------------------------------------------------------ + + // Was a text file requested? + if ($prefs['format'] == 'txt') + { + return $this->_backup($prefs); + } + + // ------------------------------------------------------ + + // Was a Zip file requested? + if ($prefs['format'] == 'zip') + { + // If they included the .zip file extension we'll remove it + if (preg_match("|.+?\.zip$|", $prefs['filename'])) + { + $prefs['filename'] = str_replace('.zip', '', $prefs['filename']); + } + + // Tack on the ".sql" file extension if needed + if ( ! preg_match("|.+?\.sql$|", $prefs['filename'])) + { + $prefs['filename'] .= '.sql'; + } + + // Load the Zip class and output it + + $CI =& get_instance(); + $CI->load->library('zip'); + $CI->zip->add_data($prefs['filename'], $this->_backup($prefs)); + return $CI->zip->get_zip(); + } + + } + +} + + +/* End of file DB_utility.php */ +/* Location: ./system/database/DB_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/cubrid/cubrid_driver.php b/api/system/database/drivers/cubrid/cubrid_driver.php new file mode 100644 index 0000000..d011404 --- /dev/null +++ b/api/system/database/drivers/cubrid/cubrid_driver.php @@ -0,0 +1,792 @@ +port == '') + { + $this->port = self::DEFAULT_PORT; + } + + $conn = cubrid_connect($this->hostname, $this->port, $this->database, $this->username, $this->password); + + if ($conn) + { + // Check if a user wants to run queries in dry, i.e. run the + // queries but not commit them. + if (isset($this->auto_commit) && ! $this->auto_commit) + { + cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_FALSE); + } + else + { + cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_TRUE); + $this->auto_commit = TRUE; + } + } + + return $conn; + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * In CUBRID persistent DB connection is supported natively in CUBRID + * engine which can be configured in the CUBRID Broker configuration + * file by setting the CCI_PCONNECT parameter to ON. In that case, all + * connections established between the client application and the + * server will become persistent. This is calling the same + * @cubrid_connect function will establish persisten connection + * considering that the CCI_PCONNECT is ON. + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + return $this->db_connect(); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + if (cubrid_ping($this->conn_id) === FALSE) + { + $this->conn_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + // In CUBRID there is no need to select a database as the database + // is chosen at the connection time. + // So, to determine if the database is "selected", all we have to + // do is ping the server and return that value. + return cubrid_ping($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // In CUBRID, there is no need to set charset or collation. + // This is why returning true will allow the application continue + // its normal process. + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + // To obtain the CUBRID Server version, no need to run the SQL query. + // CUBRID PHP API provides a function to determin this value. + // This is why we also need to add 'cubrid' value to the list of + // $driver_version_exceptions array in DB_driver class in + // version() function. + return cubrid_get_server_info($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return @cubrid_query($sql, $this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + // No need to prepare + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + if (cubrid_get_autocommit($this->conn_id)) + { + cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_FALSE); + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + cubrid_commit($this->conn_id); + + if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) + { + cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + cubrid_rollback($this->conn_id); + + if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) + { + cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + if (function_exists('cubrid_real_escape_string') AND is_resource($this->conn_id)) + { + $str = cubrid_real_escape_string($str, $this->conn_id); + } + else + { + $str = addslashes($str); + } + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @cubrid_affected_rows($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id() + { + return @cubrid_insert_id($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified table + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * List table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SHOW TABLES"; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT * FROM ".$table." LIMIT 1"; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return cubrid_error($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return cubrid_errno($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + + /** + * Replace statement + * + * Generates a platform-specific replace string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _replace($table, $keys, $values) + { + return "REPLACE INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert_batch($table, $keys, $values) + { + return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES ".implode(', ', $values); + } + + // -------------------------------------------------------------------- + + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = sprintf('"%s" = %s', $key, $val); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + // -------------------------------------------------------------------- + + + /** + * Update_Batch statement + * + * Generates a platform-specific batch update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @return string + */ + function _update_batch($table, $values, $index, $where = NULL) + { + $ids = array(); + $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; + + foreach ($values as $key => $val) + { + $ids[] = $val[$index]; + + foreach (array_keys($val) as $field) + { + if ($field != $index) + { + $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; + } + } + } + + $sql = "UPDATE ".$table." SET "; + $cases = ''; + + foreach ($final as $k => $v) + { + $cases .= $k.' = CASE '."\n"; + foreach ($v as $row) + { + $cases .= $row."\n"; + } + + $cases .= 'ELSE '.$k.' END, '; + } + + $sql .= substr($cases, 0, -2); + + $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; + + return $sql; + } + + // -------------------------------------------------------------------- + + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return "TRUNCATE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + if ($offset == 0) + { + $offset = ''; + } + else + { + $offset .= ", "; + } + + return $sql."LIMIT ".$offset.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @cubrid_close($conn_id); + } + +} + + +/* End of file cubrid_driver.php */ +/* Location: ./system/database/drivers/cubrid/cubrid_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/cubrid/cubrid_forge.php b/api/system/database/drivers/cubrid/cubrid_forge.php new file mode 100644 index 0000000..bab03f7 --- /dev/null +++ b/api/system/database/drivers/cubrid/cubrid_forge.php @@ -0,0 +1,288 @@ +$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t\"" . $this->db->_protect_identifiers($field) . "\""; + + if (array_key_exists('NAME', $attributes)) + { + $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; + } + + if (array_key_exists('TYPE', $attributes)) + { + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + switch ($attributes['TYPE']) + { + case 'decimal': + case 'float': + case 'numeric': + $sql .= '('.implode(',', $attributes['CONSTRAINT']).')'; + break; + case 'enum': // As of version 8.4.0 CUBRID does not support + // enum data type. + break; + case 'set': + $sql .= '("'.implode('","', $attributes['CONSTRAINT']).'")'; + break; + default: + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + } + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + //$sql .= ' UNSIGNED'; + // As of version 8.4.0 CUBRID does not support UNSIGNED INTEGER data type. + // Will be supported in the next release as a part of MySQL Compatibility. + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + + if (array_key_exists('UNIQUE', $attributes) && $attributes['UNIQUE'] === TRUE) + { + $sql .= ' UNIQUE'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param mixed the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + //$sql .= 'IF NOT EXISTS '; + // As of version 8.4.0 CUBRID does not support this SQL syntax. + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + + $sql .= $this->_process_fields($fields); + + // If there is a PK defined + if (count($primary_keys) > 0) + { + $key_name = "pk_" . $table . "_" . + $this->db->_protect_identifiers(implode('_', $primary_keys)); + + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tCONSTRAINT " . $key_name . " PRIMARY KEY(" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key_name = $this->db->_protect_identifiers(implode('_', $key)); + $key = $this->db->_protect_identifiers($key); + } + else + { + $key_name = $this->db->_protect_identifiers($key); + $key = array($key_name); + } + + $sql .= ",\n\tKEY \"{$key_name}\" (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n);"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return string + */ + function _drop_table($table) + { + return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param array fields + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $fields, $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql.$this->db->_protect_identifiers($fields); + } + + $sql .= $this->_process_fields($fields); + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'RENAME TABLE '.$this->db->_protect_identifiers($table_name)." AS ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + +} + +/* End of file cubrid_forge.php */ +/* Location: ./system/database/drivers/cubrid/cubrid_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/cubrid/cubrid_result.php b/api/system/database/drivers/cubrid/cubrid_result.php new file mode 100644 index 0000000..6f0c2b5 --- /dev/null +++ b/api/system/database/drivers/cubrid/cubrid_result.php @@ -0,0 +1,202 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @cubrid_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + return cubrid_column_names($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + + $tablePrimaryKeys = array(); + + while ($field = cubrid_fetch_field($this->result_id)) + { + $F = new stdClass(); + $F->name = $field->name; + $F->type = $field->type; + $F->default = $field->def; + $F->max_length = $field->max_length; + + // At this moment primary_key property is not returned when + // cubrid_fetch_field is called. The following code will + // provide a patch for it. primary_key property will be added + // in the next release. + + // TODO: later version of CUBRID will provide primary_key + // property. + // When PK is defined in CUBRID, an index is automatically + // created in the db_index system table in the form of + // pk_tblname_fieldname. So the following will count how many + // columns are there which satisfy this format. + // The query will search for exact single columns, thus + // compound PK is not supported. + $res = cubrid_query($this->conn_id, + "SELECT COUNT(*) FROM db_index WHERE class_name = '" . $field->table . + "' AND is_primary_key = 'YES' AND index_name = 'pk_" . + $field->table . "_" . $field->name . "'" + ); + + if ($res) + { + $row = cubrid_fetch_array($res, CUBRID_NUM); + $F->primary_key = ($row[0] > 0 ? 1 : null); + } + else + { + $F->primary_key = null; + } + + if (is_resource($res)) + { + cubrid_close_request($res); + $this->result_id = FALSE; + } + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if(is_resource($this->result_id) || + get_resource_type($this->result_id) == "Unknown" && + preg_match('/Resource id #/', strval($this->result_id))) + { + cubrid_close_request($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return cubrid_data_seek($this->result_id, $n); + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return cubrid_fetch_assoc($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return cubrid_fetch_object($this->result_id); + } + +} + + +/* End of file cubrid_result.php */ +/* Location: ./system/database/drivers/cubrid/cubrid_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/cubrid/cubrid_utility.php b/api/system/database/drivers/cubrid/cubrid_utility.php new file mode 100644 index 0000000..cd16d1e --- /dev/null +++ b/api/system/database/drivers/cubrid/cubrid_utility.php @@ -0,0 +1,108 @@ +conn_id) + { + return "SELECT '" . $this->database . "'"; + } + else + { + return FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Optimize table query + * + * Generates a platform-specific query so that a table can be optimized + * + * @access private + * @param string the table name + * @return object + * @link http://www.cubrid.org/manual/840/en/Optimize%20Database + */ + function _optimize_table($table) + { + // No SQL based support in CUBRID as of version 8.4.0. Database or + // table optimization can be performed using CUBRID Manager + // database administration tool. See the link above for more info. + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Generates a platform-specific query so that a table can be repaired + * + * @access private + * @param string the table name + * @return object + * @link http://www.cubrid.org/manual/840/en/Checking%20Database%20Consistency + */ + function _repair_table($table) + { + // Not supported in CUBRID as of version 8.4.0. Database or + // table consistency can be checked using CUBRID Manager + // database administration tool. See the link above for more info. + return FALSE; + } + + // -------------------------------------------------------------------- + /** + * CUBRID Export + * + * @access private + * @param array Preferences + * @return mixed + */ + function _backup($params = array()) + { + // No SQL based support in CUBRID as of version 8.4.0. Database or + // table backup can be performed using CUBRID Manager + // database administration tool. + return $this->db->display_error('db_unsuported_feature'); + } +} + +/* End of file cubrid_utility.php */ +/* Location: ./system/database/drivers/cubrid/cubrid_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/cubrid/index.html b/api/system/database/drivers/cubrid/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/cubrid/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/index.html b/api/system/database/drivers/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/mssql/index.html b/api/system/database/drivers/mssql/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/mssql/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/mssql/mssql_driver.php b/api/system/database/drivers/mssql/mssql_driver.php new file mode 100644 index 0000000..b39bd93 --- /dev/null +++ b/api/system/database/drivers/mssql/mssql_driver.php @@ -0,0 +1,667 @@ +port != '') + { + $this->hostname .= ','.$this->port; + } + + return @mssql_connect($this->hostname, $this->username, $this->password); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + if ($this->port != '') + { + $this->hostname .= ','.$this->port; + } + + return @mssql_pconnect($this->hostname, $this->username, $this->password); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + // not implemented in MSSQL + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + // Note: The brackets are required in the event that the DB name + // contains reserved characters + return @mssql_select_db('['.$this->database.']', $this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return @mssql_query($sql, $this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + $this->simple_query('BEGIN TRAN'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('COMMIT TRAN'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('ROLLBACK TRAN'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + // Escape single quotes + $str = str_replace("'", "''", remove_invisible_characters($str)); + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace( + array($this->_like_escape_chr, '%', '_'), + array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'), + $str + ); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @mssql_rows_affected($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * Returns the last id created in the Identity column. + * + * @access public + * @return integer + */ + function insert_id() + { + $ver = self::_parse_major_version($this->version()); + $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id"); + $query = $this->query($sql); + $row = $query->row(); + return $row->last_id; + } + + // -------------------------------------------------------------------- + + /** + * Parse major version + * + * Grabs the major version number from the + * database server version string passed in. + * + * @access private + * @param string $version + * @return int16 major version number + */ + function _parse_major_version($version) + { + preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info); + return $ver_info[1]; // return the major version b/c that's all we're interested in. + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return "SELECT @@VERSION AS ver"; + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * List table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name"; + + // for future compatibility + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + return FALSE; // not currently supported + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * List column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access private + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$table."'"; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT TOP 1 * FROM ".$table; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return mssql_get_last_message(); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + // Are error numbers supported? + return ''; + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return implode(', ', $tables); + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return "TRUNCATE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + $i = $limit + $offset; + + return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql); + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @mssql_close($conn_id); + } + +} + + + +/* End of file mssql_driver.php */ +/* Location: ./system/database/drivers/mssql/mssql_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mssql/mssql_forge.php b/api/system/database/drivers/mssql/mssql_forge.php new file mode 100644 index 0000000..70b20ec --- /dev/null +++ b/api/system/database/drivers/mssql/mssql_forge.php @@ -0,0 +1,248 @@ +db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param array the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n)"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + // I think this syntax will work, but can find little documentation on renaming tables in MSSQL + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + +} + +/* End of file mssql_forge.php */ +/* Location: ./system/database/drivers/mssql/mssql_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mssql/mssql_result.php b/api/system/database/drivers/mssql/mssql_result.php new file mode 100644 index 0000000..2897ca5 --- /dev/null +++ b/api/system/database/drivers/mssql/mssql_result.php @@ -0,0 +1,169 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @mssql_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + while ($field = mssql_fetch_field($this->result_id)) + { + $field_names[] = $field->name; + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + while ($field = mssql_fetch_field($this->result_id)) + { + $F = new stdClass(); + $F->name = $field->name; + $F->type = $field->type; + $F->max_length = $field->max_length; + $F->primary_key = 0; + $F->default = ''; + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_resource($this->result_id)) + { + mssql_free_result($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return mssql_data_seek($this->result_id, $n); + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return mssql_fetch_assoc($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return mssql_fetch_object($this->result_id); + } + +} + + +/* End of file mssql_result.php */ +/* Location: ./system/database/drivers/mssql/mssql_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mssql/mssql_utility.php b/api/system/database/drivers/mssql/mssql_utility.php new file mode 100644 index 0000000..48ecbc7 --- /dev/null +++ b/api/system/database/drivers/mssql/mssql_utility.php @@ -0,0 +1,88 @@ +db->display_error('db_unsuported_feature'); + } + +} + +/* End of file mssql_utility.php */ +/* Location: ./system/database/drivers/mssql/mssql_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysql/index.html b/api/system/database/drivers/mysql/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/mysql/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/mysql/mysql_driver.php b/api/system/database/drivers/mysql/mysql_driver.php new file mode 100644 index 0000000..f87cfea --- /dev/null +++ b/api/system/database/drivers/mysql/mysql_driver.php @@ -0,0 +1,779 @@ +port != '') + { + $this->hostname .= ':'.$this->port; + } + + return @mysql_connect($this->hostname, $this->username, $this->password, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + if ($this->port != '') + { + $this->hostname .= ':'.$this->port; + } + + return @mysql_pconnect($this->hostname, $this->username, $this->password); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + if (mysql_ping($this->conn_id) === FALSE) + { + $this->conn_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + return @mysql_select_db($this->database, $this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + if ( ! isset($this->use_set_names)) + { + // mysql_set_charset() requires PHP >= 5.2.3 and MySQL >= 5.0.7, use SET NAMES as fallback + $this->use_set_names = (version_compare(PHP_VERSION, '5.2.3', '>=') && version_compare(mysql_get_server_info(), '5.0.7', '>=')) ? FALSE : TRUE; + } + + if ($this->use_set_names === TRUE) + { + return @mysql_query("SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'", $this->conn_id); + } + else + { + return @mysql_set_charset($charset, $this->conn_id); + } + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return "SELECT version() AS ver"; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return @mysql_query($sql, $this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + // "DELETE FROM TABLE" returns 0 affected rows This hack modifies + // the query so that it returns the number of affected rows + if ($this->delete_hack === TRUE) + { + if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) + { + $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql); + } + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + $this->simple_query('SET AUTOCOMMIT=0'); + $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('COMMIT'); + $this->simple_query('SET AUTOCOMMIT=1'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('ROLLBACK'); + $this->simple_query('SET AUTOCOMMIT=1'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id)) + { + $str = mysql_real_escape_string($str, $this->conn_id); + } + elseif (function_exists('mysql_escape_string')) + { + $str = mysql_escape_string($str); + } + else + { + $str = addslashes($str); + } + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @mysql_affected_rows($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id() + { + return @mysql_insert_id($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * List table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "DESCRIBE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return mysql_error($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return mysql_errno($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + + /** + * Replace statement + * + * Generates a platform-specific replace string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _replace($table, $keys, $values) + { + return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert_batch($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); + } + + // -------------------------------------------------------------------- + + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key . ' = ' . $val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + // -------------------------------------------------------------------- + + + /** + * Update_Batch statement + * + * Generates a platform-specific batch update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @return string + */ + function _update_batch($table, $values, $index, $where = NULL) + { + $ids = array(); + $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; + + foreach ($values as $key => $val) + { + $ids[] = $val[$index]; + + foreach (array_keys($val) as $field) + { + if ($field != $index) + { + $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; + } + } + } + + $sql = "UPDATE ".$table." SET "; + $cases = ''; + + foreach ($final as $k => $v) + { + $cases .= $k.' = CASE '."\n"; + foreach ($v as $row) + { + $cases .= $row."\n"; + } + + $cases .= 'ELSE '.$k.' END, '; + } + + $sql .= substr($cases, 0, -2); + + $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; + + return $sql; + } + + // -------------------------------------------------------------------- + + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return "TRUNCATE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + if ($offset == 0) + { + $offset = ''; + } + else + { + $offset .= ", "; + } + + return $sql."LIMIT ".$offset.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @mysql_close($conn_id); + } + +} + + +/* End of file mysql_driver.php */ +/* Location: ./system/database/drivers/mysql/mysql_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysql/mysql_forge.php b/api/system/database/drivers/mysql/mysql_forge.php new file mode 100644 index 0000000..c1cae13 --- /dev/null +++ b/api/system/database/drivers/mysql/mysql_forge.php @@ -0,0 +1,273 @@ +$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + if (array_key_exists('NAME', $attributes)) + { + $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; + } + + if (array_key_exists('TYPE', $attributes)) + { + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + switch ($attributes['TYPE']) + { + case 'decimal': + case 'float': + case 'numeric': + $sql .= '('.implode(',', $attributes['CONSTRAINT']).')'; + break; + + case 'enum': + case 'set': + $sql .= '("'.implode('","', $attributes['CONSTRAINT']).'")'; + break; + + default: + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + } + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param mixed the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + + $sql .= $this->_process_fields($fields); + + if (count($primary_keys) > 0) + { + $key_name = $this->db->_protect_identifiers(implode('_', $primary_keys)); + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key_name = $this->db->_protect_identifiers(implode('_', $key)); + $key = $this->db->_protect_identifiers($key); + } + else + { + $key_name = $this->db->_protect_identifiers($key); + $key = array($key_name); + } + + $sql .= ",\n\tKEY {$key_name} (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n) DEFAULT CHARACTER SET {$this->db->char_set} COLLATE {$this->db->dbcollat};"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return string + */ + function _drop_table($table) + { + return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param array fields + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $fields, $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql.$this->db->_protect_identifiers($fields); + } + + $sql .= $this->_process_fields($fields); + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + +} + +/* End of file mysql_forge.php */ +/* Location: ./system/database/drivers/mysql/mysql_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysql/mysql_result.php b/api/system/database/drivers/mysql/mysql_result.php new file mode 100644 index 0000000..e1a6e93 --- /dev/null +++ b/api/system/database/drivers/mysql/mysql_result.php @@ -0,0 +1,174 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @mysql_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + while ($field = mysql_fetch_field($this->result_id)) + { + $field_names[] = $field->name; + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + while ($field = mysql_fetch_object($this->result_id)) + { + preg_match('/([a-zA-Z]+)(\(\d+\))?/', $field->Type, $matches); + + $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL; + $length = (array_key_exists(2, $matches)) ? preg_replace('/[^\d]/', '', $matches[2]) : NULL; + + $F = new stdClass(); + $F->name = $field->Field; + $F->type = $type; + $F->default = $field->Default; + $F->max_length = $length; + $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 ); + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_resource($this->result_id)) + { + mysql_free_result($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return mysql_data_seek($this->result_id, $n); + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return mysql_fetch_assoc($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return mysql_fetch_object($this->result_id); + } + +} + + +/* End of file mysql_result.php */ +/* Location: ./system/database/drivers/mysql/mysql_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysql/mysql_utility.php b/api/system/database/drivers/mysql/mysql_utility.php new file mode 100644 index 0000000..48c4d63 --- /dev/null +++ b/api/system/database/drivers/mysql/mysql_utility.php @@ -0,0 +1,210 @@ +db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Generates a platform-specific query so that a table can be repaired + * + * @access private + * @param string the table name + * @return object + */ + function _repair_table($table) + { + return "REPAIR TABLE ".$this->db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + /** + * MySQL Export + * + * @access private + * @param array Preferences + * @return mixed + */ + function _backup($params = array()) + { + if (count($params) == 0) + { + return FALSE; + } + + // Extract the prefs for simplicity + extract($params); + + // Build the output + $output = ''; + foreach ((array)$tables as $table) + { + // Is the table in the "ignore" list? + if (in_array($table, (array)$ignore, TRUE)) + { + continue; + } + + // Get the table schema + $query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.`'.$table.'`'); + + // No result means the table name was invalid + if ($query === FALSE) + { + continue; + } + + // Write out the table schema + $output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline; + + if ($add_drop == TRUE) + { + $output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline; + } + + $i = 0; + $result = $query->result_array(); + foreach ($result[0] as $val) + { + if ($i++ % 2) + { + $output .= $val.';'.$newline.$newline; + } + } + + // If inserts are not needed we're done... + if ($add_insert == FALSE) + { + continue; + } + + // Grab all the data from the current table + $query = $this->db->query("SELECT * FROM $table"); + + if ($query->num_rows() == 0) + { + continue; + } + + // Fetch the field names and determine if the field is an + // integer type. We use this info to decide whether to + // surround the data with quotes or not + + $i = 0; + $field_str = ''; + $is_int = array(); + while ($field = mysql_fetch_field($query->result_id)) + { + // Most versions of MySQL store timestamp as a string + $is_int[$i] = (in_array( + strtolower(mysql_field_type($query->result_id, $i)), + array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'), + TRUE) + ) ? TRUE : FALSE; + + // Create a string of field names + $field_str .= '`'.$field->name.'`, '; + $i++; + } + + // Trim off the end comma + $field_str = preg_replace( "/, $/" , "" , $field_str); + + + // Build the insert string + foreach ($query->result_array() as $row) + { + $val_str = ''; + + $i = 0; + foreach ($row as $v) + { + // Is the value NULL? + if ($v === NULL) + { + $val_str .= 'NULL'; + } + else + { + // Escape the data if it's not an integer + if ($is_int[$i] == FALSE) + { + $val_str .= $this->db->escape($v); + } + else + { + $val_str .= $v; + } + } + + // Append a comma + $val_str .= ', '; + $i++; + } + + // Remove the comma at the end of the string + $val_str = preg_replace( "/, $/" , "" , $val_str); + + // Build the INSERT string + $output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline; + } + + $output .= $newline.$newline; + } + + return $output; + } +} + +/* End of file mysql_utility.php */ +/* Location: ./system/database/drivers/mysql/mysql_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysqli/index.html b/api/system/database/drivers/mysqli/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/mysqli/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/mysqli/mysqli_driver.php b/api/system/database/drivers/mysqli/mysqli_driver.php new file mode 100644 index 0000000..d3200f3 --- /dev/null +++ b/api/system/database/drivers/mysqli/mysqli_driver.php @@ -0,0 +1,776 @@ +port != '') + { + return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database, $this->port); + } + else + { + return @mysqli_connect($this->hostname, $this->username, $this->password, $this->database); + } + + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + return $this->db_connect(); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + if (mysqli_ping($this->conn_id) === FALSE) + { + $this->conn_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + return @mysqli_select_db($this->conn_id, $this->database); + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access private + * @param string + * @param string + * @return resource + */ + function _db_set_charset($charset, $collation) + { + if ( ! isset($this->use_set_names)) + { + // mysqli_set_charset() requires MySQL >= 5.0.7, use SET NAMES as fallback + $this->use_set_names = (version_compare(mysqli_get_server_info($this->conn_id), '5.0.7', '>=')) ? FALSE : TRUE; + } + + if ($this->use_set_names === TRUE) + { + return @mysqli_query($this->conn_id, "SET NAMES '".$this->escape_str($charset)."' COLLATE '".$this->escape_str($collation)."'"); + } + else + { + return @mysqli_set_charset($this->conn_id, $charset); + } + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return "SELECT version() AS ver"; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + $result = @mysqli_query($this->conn_id, $sql); + return $result; + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + // "DELETE FROM TABLE" returns 0 affected rows This hack modifies + // the query so that it returns the number of affected rows + if ($this->delete_hack === TRUE) + { + if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) + { + $sql = preg_replace("/^\s*DELETE\s+FROM\s+(\S+)\s*$/", "DELETE FROM \\1 WHERE 1=1", $sql); + } + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + $this->simple_query('SET AUTOCOMMIT=0'); + $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('COMMIT'); + $this->simple_query('SET AUTOCOMMIT=1'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('ROLLBACK'); + $this->simple_query('SET AUTOCOMMIT=1'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + if (function_exists('mysqli_real_escape_string') AND is_object($this->conn_id)) + { + $str = mysqli_real_escape_string($this->conn_id, $str); + } + elseif (function_exists('mysql_escape_string')) + { + $str = mysql_escape_string($str); + } + else + { + $str = addslashes($str); + } + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @mysqli_affected_rows($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id() + { + return @mysqli_insert_id($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * List table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SHOW TABLES FROM ".$this->_escape_char.$this->database.$this->_escape_char; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'"; + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SHOW COLUMNS FROM ".$this->_protect_identifiers($table, TRUE, NULL, FALSE); + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "DESCRIBE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return mysqli_error($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return mysqli_errno($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert_batch($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); + } + + // -------------------------------------------------------------------- + + + /** + * Replace statement + * + * Generates a platform-specific replace string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _replace($table, $keys, $values) + { + return "REPLACE INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Update_Batch statement + * + * Generates a platform-specific batch update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @return string + */ + function _update_batch($table, $values, $index, $where = NULL) + { + $ids = array(); + $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; + + foreach ($values as $key => $val) + { + $ids[] = $val[$index]; + + foreach (array_keys($val) as $field) + { + if ($field != $index) + { + $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; + } + } + } + + $sql = "UPDATE ".$table." SET "; + $cases = ''; + + foreach ($final as $k => $v) + { + $cases .= $k.' = CASE '."\n"; + foreach ($v as $row) + { + $cases .= $row."\n"; + } + + $cases .= 'ELSE '.$k.' END, '; + } + + $sql .= substr($cases, 0, -2); + + $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return "TRUNCATE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + $sql .= "LIMIT ".$limit; + + if ($offset > 0) + { + $sql .= " OFFSET ".$offset; + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @mysqli_close($conn_id); + } + + +} + + +/* End of file mysqli_driver.php */ +/* Location: ./system/database/drivers/mysqli/mysqli_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysqli/mysqli_forge.php b/api/system/database/drivers/mysqli/mysqli_forge.php new file mode 100644 index 0000000..2605494 --- /dev/null +++ b/api/system/database/drivers/mysqli/mysqli_forge.php @@ -0,0 +1,258 @@ +$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + if (array_key_exists('NAME', $attributes)) + { + $sql .= ' '.$this->db->_protect_identifiers($attributes['NAME']).' '; + } + + if (array_key_exists('TYPE', $attributes)) + { + $sql .= ' '.$attributes['TYPE']; + } + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param mixed the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + + $sql .= $this->_process_fields($fields); + + if (count($primary_keys) > 0) + { + $key_name = $this->db->_protect_identifiers(implode('_', $primary_keys)); + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key_name = $this->db->_protect_identifiers(implode('_', $key)); + $key = $this->db->_protect_identifiers($key); + } + else + { + $key_name = $this->db->_protect_identifiers($key); + $key = array($key_name); + } + + $sql .= ",\n\tKEY {$key_name} (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n) DEFAULT CHARACTER SET {$this->db->char_set} COLLATE {$this->db->dbcollat};"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return string + */ + function _drop_table($table) + { + return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param array fields + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $fields, $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type "; + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql.$this->db->_protect_identifiers($fields); + } + + $sql .= $this->_process_fields($fields); + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + +} + +/* End of file mysqli_forge.php */ +/* Location: ./system/database/drivers/mysqli/mysqli_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysqli/mysqli_result.php b/api/system/database/drivers/mysqli/mysqli_result.php new file mode 100644 index 0000000..124d4e5 --- /dev/null +++ b/api/system/database/drivers/mysqli/mysqli_result.php @@ -0,0 +1,174 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @mysqli_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + while ($field = mysqli_fetch_field($this->result_id)) + { + $field_names[] = $field->name; + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + while ($field = mysqli_fetch_object($this->result_id)) + { + preg_match('/([a-zA-Z]+)(\(\d+\))?/', $field->Type, $matches); + + $type = (array_key_exists(1, $matches)) ? $matches[1] : NULL; + $length = (array_key_exists(2, $matches)) ? preg_replace('/[^\d]/', '', $matches[2]) : NULL; + + $F = new stdClass(); + $F->name = $field->Field; + $F->type = $type; + $F->default = $field->Default; + $F->max_length = $length; + $F->primary_key = ( $field->Key == 'PRI' ? 1 : 0 ); + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_object($this->result_id)) + { + mysqli_free_result($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return mysqli_data_seek($this->result_id, $n); + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return mysqli_fetch_assoc($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return mysqli_fetch_object($this->result_id); + } + +} + + +/* End of file mysqli_result.php */ +/* Location: ./system/database/drivers/mysqli/mysqli_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/mysqli/mysqli_utility.php b/api/system/database/drivers/mysqli/mysqli_utility.php new file mode 100644 index 0000000..e17889b --- /dev/null +++ b/api/system/database/drivers/mysqli/mysqli_utility.php @@ -0,0 +1,87 @@ +db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Generates a platform-specific query so that a table can be repaired + * + * @access private + * @param string the table name + * @return object + */ + function _repair_table($table) + { + return "REPAIR TABLE ".$this->db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * MySQLi Export + * + * @access private + * @param array Preferences + * @return mixed + */ + function _backup($params = array()) + { + // Currently unsupported + return $this->db->display_error('db_unsuported_feature'); + } +} + +/* End of file mysqli_utility.php */ +/* Location: ./system/database/drivers/mysqli/mysqli_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/oci8/index.html b/api/system/database/drivers/oci8/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/oci8/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/oci8/oci8_driver.php b/api/system/database/drivers/oci8/oci8_driver.php new file mode 100644 index 0000000..930177e --- /dev/null +++ b/api/system/database/drivers/oci8/oci8_driver.php @@ -0,0 +1,808 @@ +username, $this->password, $this->hostname, $this->char_set); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + public function db_pconnect() + { + return @oci_pconnect($this->username, $this->password, $this->hostname, $this->char_set); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + public function reconnect() + { + // not implemented in oracle + return; + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + public function db_select() + { + // Not in Oracle - schemas are actually usernames + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + public function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access protected + * @return string + */ + protected function _version() + { + return oci_server_version($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access protected called by the base class + * @param string an SQL query + * @return resource + */ + protected function _execute($sql) + { + // oracle must parse the query before it is run. All of the actions with + // the query are based on the statement id returned by ociparse + $this->stmt_id = FALSE; + $this->_set_stmt_id($sql); + oci_set_prefetch($this->stmt_id, 1000); + return @oci_execute($this->stmt_id, $this->_commit); + } + + /** + * Generate a statement ID + * + * @access private + * @param string an SQL query + * @return none + */ + private function _set_stmt_id($sql) + { + if ( ! is_resource($this->stmt_id)) + { + $this->stmt_id = oci_parse($this->conn_id, $this->_prep_query($sql)); + } + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + private function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * getCursor. Returns a cursor from the datbase + * + * @access public + * @return cursor id + */ + public function get_cursor() + { + $this->curs_id = oci_new_cursor($this->conn_id); + return $this->curs_id; + } + + // -------------------------------------------------------------------- + + /** + * Stored Procedure. Executes a stored procedure + * + * @access public + * @param package package stored procedure is in + * @param procedure stored procedure to execute + * @param params array of parameters + * @return array + * + * params array keys + * + * KEY OPTIONAL NOTES + * name no the name of the parameter should be in : format + * value no the value of the parameter. If this is an OUT or IN OUT parameter, + * this should be a reference to a variable + * type yes the type of the parameter + * length yes the max size of the parameter + */ + public function stored_procedure($package, $procedure, $params) + { + if ($package == '' OR $procedure == '' OR ! is_array($params)) + { + if ($this->db_debug) + { + log_message('error', 'Invalid query: '.$package.'.'.$procedure); + return $this->display_error('db_invalid_query'); + } + return FALSE; + } + + // build the query string + $sql = "begin $package.$procedure("; + + $have_cursor = FALSE; + foreach ($params as $param) + { + $sql .= $param['name'] . ","; + + if (array_key_exists('type', $param) && ($param['type'] === OCI_B_CURSOR)) + { + $have_cursor = TRUE; + } + } + $sql = trim($sql, ",") . "); end;"; + + $this->stmt_id = FALSE; + $this->_set_stmt_id($sql); + $this->_bind_params($params); + $this->query($sql, FALSE, $have_cursor); + } + + // -------------------------------------------------------------------- + + /** + * Bind parameters + * + * @access private + * @return none + */ + private function _bind_params($params) + { + if ( ! is_array($params) OR ! is_resource($this->stmt_id)) + { + return; + } + + foreach ($params as $param) + { + foreach (array('name', 'value', 'type', 'length') as $val) + { + if ( ! isset($param[$val])) + { + $param[$val] = ''; + } + } + + oci_bind_by_name($this->stmt_id, $param['name'], $param['value'], $param['length'], $param['type']); + } + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + public function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + $this->_commit = OCI_DEFAULT; + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + public function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $ret = oci_commit($this->conn_id); + $this->_commit = OCI_COMMIT_ON_SUCCESS; + return $ret; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + public function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $ret = oci_rollback($this->conn_id); + $this->_commit = OCI_COMMIT_ON_SUCCESS; + return $ret; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + public function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + $str = remove_invisible_characters($str); + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace( array('%', '_', $this->_like_escape_chr), + array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), + $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + public function affected_rows() + { + return @oci_num_rows($this->stmt_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + public function insert_id() + { + // not supported in oracle + return $this->display_error('db_unsupported_function'); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + public function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query == FALSE) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * Show table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access protected + * @param boolean + * @return string + */ + protected function _list_tables($prefix_limit = FALSE) + { + $sql = "SELECT TABLE_NAME FROM ALL_TABLES"; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + $sql .= " WHERE TABLE_NAME LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access protected + * @param string the table name + * @return string + */ + protected function _list_columns($table = '') + { + return "SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = '$table'"; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + protected function _field_data($table) + { + return "SELECT * FROM ".$table." where rownum = 1"; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access protected + * @return string + */ + protected function _error_message() + { + // If the error was during connection, no conn_id should be passed + $error = is_resource($this->conn_id) ? oci_error($this->conn_id) : oci_error(); + return $error['message']; + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access protected + * @return integer + */ + protected function _error_number() + { + // Same as _error_message() + $error = is_resource($this->conn_id) ? oci_error($this->conn_id) : oci_error(); + return $error['code']; + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access protected + * @param string + * @return string + */ + protected function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access protected + * @param type + * @return type + */ + protected function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return implode(', ', $tables); + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + protected function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access protected + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + protected function _insert_batch($table, $keys, $values) + { + $keys = implode(', ', $keys); + $sql = "INSERT ALL\n"; + + for ($i = 0, $c = count($values); $i < $c; $i++) + { + $sql .= ' INTO ' . $table . ' (' . $keys . ') VALUES ' . $values[$i] . "\n"; + } + + $sql .= 'SELECT * FROM dual'; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access protected + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access protected + * @param string the table name + * @return string + */ + protected function _truncate($table) + { + return "TRUNCATE TABLE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access protected + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + protected function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access protected + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + protected function _limit($sql, $limit, $offset) + { + $limit = $offset + $limit; + $newsql = "SELECT * FROM (select inner_query.*, rownum rnum FROM ($sql) inner_query WHERE rownum < $limit)"; + + if ($offset != 0) + { + $newsql .= " WHERE rnum >= $offset"; + } + + // remember that we used limits + $this->limit_used = TRUE; + + return $newsql; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access protected + * @param resource + * @return void + */ + protected function _close($conn_id) + { + @oci_close($conn_id); + } + + +} + + + +/* End of file oci8_driver.php */ +/* Location: ./system/database/drivers/oci8/oci8_driver.php */ diff --git a/api/system/database/drivers/oci8/oci8_forge.php b/api/system/database/drivers/oci8/oci8_forge.php new file mode 100644 index 0000000..3cd1758 --- /dev/null +++ b/api/system/database/drivers/oci8/oci8_forge.php @@ -0,0 +1,248 @@ +db->_escape_identifiers($table)." ("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + $sql .= ",\n\tUNIQUE COLUMNS (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n)"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return bool + */ + function _drop_table($table) + { + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + + +} + +/* End of file oci8_forge.php */ +/* Location: ./system/database/drivers/oci8/oci8_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/oci8/oci8_result.php b/api/system/database/drivers/oci8/oci8_result.php new file mode 100644 index 0000000..3421278 --- /dev/null +++ b/api/system/database/drivers/oci8/oci8_result.php @@ -0,0 +1,217 @@ +num_rows === 0 && count($this->result_array()) > 0) + { + $this->num_rows = count($this->result_array()); + @oci_execute($this->stmt_id); + + if ($this->curs_id) + { + @oci_execute($this->curs_id); + } + } + + return $this->num_rows; + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + public function num_fields() + { + $count = @oci_num_fields($this->stmt_id); + + // if we used a limit we subtract it + if ($this->limit_used) + { + $count = $count - 1; + } + + return $count; + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + public function list_fields() + { + $field_names = array(); + for ($c = 1, $fieldCount = $this->num_fields(); $c <= $fieldCount; $c++) + { + $field_names[] = oci_field_name($this->stmt_id, $c); + } + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + public function field_data() + { + $retval = array(); + for ($c = 1, $fieldCount = $this->num_fields(); $c <= $fieldCount; $c++) + { + $F = new stdClass(); + $F->name = oci_field_name($this->stmt_id, $c); + $F->type = oci_field_type($this->stmt_id, $c); + $F->max_length = oci_field_size($this->stmt_id, $c); + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + public function free_result() + { + if (is_resource($this->result_id)) + { + oci_free_statement($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access protected + * @return array + */ + protected function _fetch_assoc() + { + $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; + return oci_fetch_assoc($id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access protected + * @return object + */ + protected function _fetch_object() + { + $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; + return @oci_fetch_object($id); + } + + // -------------------------------------------------------------------- + + /** + * Query result. "array" version. + * + * @access public + * @return array + */ + public function result_array() + { + if (count($this->result_array) > 0) + { + return $this->result_array; + } + + $row = NULL; + while ($row = $this->_fetch_assoc()) + { + $this->result_array[] = $row; + } + + return $this->result_array; + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access protected + * @return array + */ + protected function _data_seek($n = 0) + { + return FALSE; // Not needed + } + +} + + +/* End of file oci8_result.php */ +/* Location: ./system/database/drivers/oci8/oci8_result.php */ diff --git a/api/system/database/drivers/oci8/oci8_utility.php b/api/system/database/drivers/oci8/oci8_utility.php new file mode 100644 index 0000000..854b467 --- /dev/null +++ b/api/system/database/drivers/oci8/oci8_utility.php @@ -0,0 +1,87 @@ +db->display_error('db_unsuported_feature'); + } +} + +/* End of file oci8_utility.php */ +/* Location: ./system/database/drivers/oci8/oci8_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/odbc/index.html b/api/system/database/drivers/odbc/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/odbc/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/odbc/odbc_driver.php b/api/system/database/drivers/odbc/odbc_driver.php new file mode 100644 index 0000000..bcd7937 --- /dev/null +++ b/api/system/database/drivers/odbc/odbc_driver.php @@ -0,0 +1,637 @@ +_random_keyword = ' RND('.time().')'; // database specific random keyword + } + + /** + * Non-persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_connect() + { + return @odbc_connect($this->hostname, $this->username, $this->password); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + return @odbc_pconnect($this->hostname, $this->username, $this->password); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + // not implemented in odbc + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + // Not needed for ODBC + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return "SELECT version() AS ver"; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return @odbc_exec($this->conn_id, $sql); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + return odbc_autocommit($this->conn_id, FALSE); + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $ret = odbc_commit($this->conn_id); + odbc_autocommit($this->conn_id, TRUE); + return $ret; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $ret = odbc_rollback($this->conn_id); + odbc_autocommit($this->conn_id, TRUE); + return $ret; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + // ODBC doesn't require escaping + $str = remove_invisible_characters($str); + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace( array('%', '_', $this->_like_escape_chr), + array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), + $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @odbc_num_rows($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id() + { + return @odbc_insert_id($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * Show table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SHOW TABLES FROM `".$this->database."`"; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + return FALSE; // not currently supported + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SHOW COLUMNS FROM ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT TOP 1 FROM ".$table; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return odbc_errormsg($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return odbc_error($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return $this->_delete($table); + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + // Does ODBC doesn't use the LIMIT clause? + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @odbc_close($conn_id); + } + + +} + + + +/* End of file odbc_driver.php */ +/* Location: ./system/database/drivers/odbc/odbc_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/odbc/odbc_forge.php b/api/system/database/drivers/odbc/odbc_forge.php new file mode 100644 index 0000000..3ec86b4 --- /dev/null +++ b/api/system/database/drivers/odbc/odbc_forge.php @@ -0,0 +1,266 @@ +db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Drop database + * + * @access private + * @param string the database name + * @return bool + */ + function _drop_database($name) + { + // ODBC has no "drop database" command since it's + // designed to connect to an existing database + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param array the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n)"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return bool + */ + function _drop_table($table) + { + // Not a supported ODBC feature + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + + +} + +/* End of file odbc_forge.php */ +/* Location: ./system/database/drivers/odbc/odbc_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/odbc/odbc_result.php b/api/system/database/drivers/odbc/odbc_result.php new file mode 100644 index 0000000..5d64a46 --- /dev/null +++ b/api/system/database/drivers/odbc/odbc_result.php @@ -0,0 +1,228 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @odbc_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + for ($i = 0; $i < $this->num_fields(); $i++) + { + $field_names[] = odbc_field_name($this->result_id, $i); + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + for ($i = 0; $i < $this->num_fields(); $i++) + { + $F = new stdClass(); + $F->name = odbc_field_name($this->result_id, $i); + $F->type = odbc_field_type($this->result_id, $i); + $F->max_length = odbc_field_len($this->result_id, $i); + $F->primary_key = 0; + $F->default = ''; + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_resource($this->result_id)) + { + odbc_free_result($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + if (function_exists('odbc_fetch_object')) + { + return odbc_fetch_array($this->result_id); + } + else + { + return $this->_odbc_fetch_array($this->result_id); + } + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + if (function_exists('odbc_fetch_object')) + { + return odbc_fetch_object($this->result_id); + } + else + { + return $this->_odbc_fetch_object($this->result_id); + } + } + + + /** + * Result - object + * + * subsititutes the odbc_fetch_object function when + * not available (odbc_fetch_object requires unixODBC) + * + * @access private + * @return object + */ + function _odbc_fetch_object(& $odbc_result) { + $rs = array(); + $rs_obj = FALSE; + if (odbc_fetch_into($odbc_result, $rs)) { + foreach ($rs as $k=>$v) { + $field_name= odbc_field_name($odbc_result, $k+1); + $rs_obj->$field_name = $v; + } + } + return $rs_obj; + } + + + /** + * Result - array + * + * subsititutes the odbc_fetch_array function when + * not available (odbc_fetch_array requires unixODBC) + * + * @access private + * @return array + */ + function _odbc_fetch_array(& $odbc_result) { + $rs = array(); + $rs_assoc = FALSE; + if (odbc_fetch_into($odbc_result, $rs)) { + $rs_assoc=array(); + foreach ($rs as $k=>$v) { + $field_name= odbc_field_name($odbc_result, $k+1); + $rs_assoc[$field_name] = $v; + } + } + return $rs_assoc; + } + +} + + +/* End of file odbc_result.php */ +/* Location: ./system/database/drivers/odbc/odbc_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/odbc/odbc_utility.php b/api/system/database/drivers/odbc/odbc_utility.php new file mode 100644 index 0000000..d335bed --- /dev/null +++ b/api/system/database/drivers/odbc/odbc_utility.php @@ -0,0 +1,103 @@ +db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Optimize table query + * + * Generates a platform-specific query so that a table can be optimized + * + * @access private + * @param string the table name + * @return object + */ + function _optimize_table($table) + { + // Not a supported ODBC feature + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Generates a platform-specific query so that a table can be repaired + * + * @access private + * @param string the table name + * @return object + */ + function _repair_table($table) + { + // Not a supported ODBC feature + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * ODBC Export + * + * @access private + * @param array Preferences + * @return mixed + */ + function _backup($params = array()) + { + // Currently unsupported + return $this->db->display_error('db_unsuported_feature'); + } + +} + +/* End of file odbc_utility.php */ +/* Location: ./system/database/drivers/odbc/odbc_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/pdo/index.html b/api/system/database/drivers/pdo/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/pdo/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/pdo/pdo_driver.php b/api/system/database/drivers/pdo/pdo_driver.php new file mode 100644 index 0000000..1ecc90a --- /dev/null +++ b/api/system/database/drivers/pdo/pdo_driver.php @@ -0,0 +1,812 @@ +hostname, 'mysql') !== FALSE) + { + $this->_like_escape_str = ''; + $this->_like_escape_chr = ''; + + //Prior to this version, the charset can't be set in the dsn + if(is_php('5.3.6')) + { + $this->hostname .= ";charset={$this->char_set}"; + } + + //Set the charset with the connection options + $this->options['PDO::MYSQL_ATTR_INIT_COMMAND'] = "SET NAMES {$this->char_set}"; + } + elseif (strpos($this->hostname, 'odbc') !== FALSE) + { + $this->_like_escape_str = " {escape '%s'} "; + $this->_like_escape_chr = '!'; + } + else + { + $this->_like_escape_str = " ESCAPE '%s' "; + $this->_like_escape_chr = '!'; + } + + empty($this->database) OR $this->hostname .= ';dbname='.$this->database; + + $this->trans_enabled = FALSE; + + $this->_random_keyword = ' RND('.time().')'; // database specific random keyword + } + + /** + * Non-persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_connect() + { + $this->options['PDO::ATTR_ERRMODE'] = PDO::ERRMODE_SILENT; + + return new PDO($this->hostname, $this->username, $this->password, $this->options); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + $this->options['PDO::ATTR_ERRMODE'] = PDO::ERRMODE_SILENT; + $this->options['PDO::ATTR_PERSISTENT'] = TRUE; + + return new PDO($this->hostname, $this->username, $this->password, $this->options); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + // Not needed for PDO + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return $this->conn_id->getAttribute(PDO::ATTR_CLIENT_VERSION); + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return object + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + $result_id = $this->conn_id->prepare($sql); + $result_id->execute(); + + if (is_object($result_id)) + { + if (is_numeric(stripos($sql, 'SELECT'))) + { + $this->affect_rows = count($result_id->fetchAll()); + $result_id->execute(); + } + else + { + $this->affect_rows = $result_id->rowCount(); + } + } + else + { + $this->affect_rows = 0; + } + + return $result_id; + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = (bool) ($test_mode === TRUE); + + return $this->conn_id->beginTransaction(); + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $ret = $this->conn->commit(); + return $ret; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $ret = $this->conn_id->rollBack(); + return $ret; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + //Escape the string + $str = $this->conn_id->quote($str); + + //If there are duplicated quotes, trim them away + if (strpos($str, "'") === 0) + { + $str = substr($str, 1, -1); + } + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace( array('%', '_', $this->_like_escape_chr), + array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), + $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return $this->affect_rows; + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id($name=NULL) + { + //Convenience method for postgres insertid + if (strpos($this->hostname, 'pgsql') !== FALSE) + { + $v = $this->_version(); + + $table = func_num_args() > 0 ? func_get_arg(0) : NULL; + + if ($table == NULL && $v >= '8.1') + { + $sql='SELECT LASTVAL() as ins_id'; + } + $query = $this->query($sql); + $row = $query->row(); + return $row->ins_id; + } + else + { + return $this->conn_id->lastInsertId($name); + } + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * Show table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SHOW TABLES FROM `".$this->database."`"; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + return FALSE; // not currently supported + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SHOW COLUMNS FROM ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT TOP 1 FROM ".$table; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + $error_array = $this->conn_id->errorInfo(); + return $error_array[2]; + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return $this->conn_id->errorCode(); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return (count($tables) == 1) ? $tables[0] : '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert_batch($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Update_Batch statement + * + * Generates a platform-specific batch update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @return string + */ + function _update_batch($table, $values, $index, $where = NULL) + { + $ids = array(); + $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : ''; + + foreach ($values as $key => $val) + { + $ids[] = $val[$index]; + + foreach (array_keys($val) as $field) + { + if ($field != $index) + { + $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; + } + } + } + + $sql = "UPDATE ".$table." SET "; + $cases = ''; + + foreach ($final as $k => $v) + { + $cases .= $k.' = CASE '."\n"; + foreach ($v as $row) + { + $cases .= $row."\n"; + } + + $cases .= 'ELSE '.$k.' END, '; + } + + $sql .= substr($cases, 0, -2); + + $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')'; + + return $sql; + } + + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return $this->_delete($table); + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + if (strpos($this->hostname, 'cubrid') !== FALSE || strpos($this->hostname, 'sqlite') !== FALSE) + { + if ($offset == 0) + { + $offset = ''; + } + else + { + $offset .= ", "; + } + + return $sql."LIMIT ".$offset.$limit; + } + else + { + $sql .= "LIMIT ".$limit; + + if ($offset > 0) + { + $sql .= " OFFSET ".$offset; + } + + return $sql; + } + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + $this->conn_id = null; + } + + +} + + + +/* End of file pdo_driver.php */ +/* Location: ./system/database/drivers/pdo/pdo_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/pdo/pdo_forge.php b/api/system/database/drivers/pdo/pdo_forge.php new file mode 100644 index 0000000..9a78220 --- /dev/null +++ b/api/system/database/drivers/pdo/pdo_forge.php @@ -0,0 +1,266 @@ +db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Drop database + * + * @access private + * @param string the database name + * @return bool + */ + function _drop_database($name) + { + // PDO has no "drop database" command since it's + // designed to connect to an existing database + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param array the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n)"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return bool + */ + function _drop_table($table) + { + // Not a supported PDO feature + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + + +} + +/* End of file pdo_forge.php */ +/* Location: ./system/database/drivers/pdo/pdo_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/pdo/pdo_result.php b/api/system/database/drivers/pdo/pdo_result.php new file mode 100644 index 0000000..44fdd6d --- /dev/null +++ b/api/system/database/drivers/pdo/pdo_result.php @@ -0,0 +1,183 @@ +num_rows)) + { + return $this->num_rows; + } + elseif (($this->num_rows = $this->result_id->rowCount()) > 0) + { + return $this->num_rows; + } + + $this->num_rows = count($this->result_id->fetchAll()); + $this->result_id->execute(); + return $this->num_rows; + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return $this->result_id->columnCount(); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $data = array(); + + try + { + for($i = 0; $i < $this->num_fields(); $i++) + { + $data[] = $this->result_id->getColumnMeta($i); + } + + return $data; + } + catch (Exception $e) + { + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_object($this->result_id)) + { + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return $this->result_id->fetch(PDO::FETCH_ASSOC); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return $this->result_id->fetchObject(); + } + +} + + +/* End of file pdo_result.php */ +/* Location: ./system/database/drivers/pdo/pdo_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/pdo/pdo_utility.php b/api/system/database/drivers/pdo/pdo_utility.php new file mode 100644 index 0000000..88ce033 --- /dev/null +++ b/api/system/database/drivers/pdo/pdo_utility.php @@ -0,0 +1,103 @@ +db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Optimize table query + * + * Generates a platform-specific query so that a table can be optimized + * + * @access private + * @param string the table name + * @return object + */ + function _optimize_table($table) + { + // Not a supported PDO feature + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Generates a platform-specific query so that a table can be repaired + * + * @access private + * @param string the table name + * @return object + */ + function _repair_table($table) + { + // Not a supported PDO feature + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * PDO Export + * + * @access private + * @param array Preferences + * @return mixed + */ + function _backup($params = array()) + { + // Currently unsupported + return $this->db->display_error('db_unsuported_feature'); + } + +} + +/* End of file pdo_utility.php */ +/* Location: ./system/database/drivers/pdo/pdo_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/postgre/index.html b/api/system/database/drivers/postgre/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/postgre/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/postgre/postgre_driver.php b/api/system/database/drivers/postgre/postgre_driver.php new file mode 100644 index 0000000..5367f97 --- /dev/null +++ b/api/system/database/drivers/postgre/postgre_driver.php @@ -0,0 +1,703 @@ + 'host', + 'port' => 'port', + 'database' => 'dbname', + 'username' => 'user', + 'password' => 'password' + ); + + $connect_string = ""; + foreach ($components as $key => $val) + { + if (isset($this->$key) && $this->$key != '') + { + $connect_string .= " $val=".$this->$key; + } + } + return trim($connect_string); + } + + // -------------------------------------------------------------------- + + /** + * Non-persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_connect() + { + return @pg_connect($this->_connect_string()); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + return @pg_pconnect($this->_connect_string()); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + if (pg_ping($this->conn_id) === FALSE) + { + $this->conn_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + // Not needed for Postgre so we'll return TRUE + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return "SELECT version() AS ver"; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return @pg_query($this->conn_id, $sql); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + return @pg_exec($this->conn_id, "begin"); + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + return @pg_exec($this->conn_id, "commit"); + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + return @pg_exec($this->conn_id, "rollback"); + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + $str = pg_escape_string($str); + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace( array('%', '_', $this->_like_escape_chr), + array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), + $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @pg_affected_rows($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id() + { + $v = $this->_version(); + $v = $v['server']; + + $table = func_num_args() > 0 ? func_get_arg(0) : NULL; + $column = func_num_args() > 1 ? func_get_arg(1) : NULL; + + if ($table == NULL && $v >= '8.1') + { + $sql='SELECT LASTVAL() as ins_id'; + } + elseif ($table != NULL && $column != NULL && $v >= '8.0') + { + $sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column); + $query = $this->query($sql); + $row = $query->row(); + $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq); + } + elseif ($table != NULL) + { + // seq_name passed in table parameter + $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table); + } + else + { + return pg_last_oid($this->result_id); + } + $query = $this->query($sql); + $row = $query->row(); + return $row->ins_id; + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * Show table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + $sql .= " AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SELECT column_name FROM information_schema.columns WHERE table_name ='".$table."'"; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT * FROM ".$table." LIMIT 1"; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return pg_last_error($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return ''; + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return implode(', ', $tables); + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert_batch($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return "TRUNCATE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + $sql .= "LIMIT ".$limit; + + if ($offset > 0) + { + $sql .= " OFFSET ".$offset; + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @pg_close($conn_id); + } + + +} + + +/* End of file postgre_driver.php */ +/* Location: ./system/database/drivers/postgre/postgre_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/postgre/postgre_forge.php b/api/system/database/drivers/postgre/postgre_forge.php new file mode 100644 index 0000000..91a1c68 --- /dev/null +++ b/api/system/database/drivers/postgre/postgre_forge.php @@ -0,0 +1,299 @@ +db->table_exists($table)) + { + return "SELECT * FROM $table"; // Needs to return innocous but valid SQL statement + } + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $is_unsigned = (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE); + + // Convert datatypes to be PostgreSQL-compatible + switch (strtoupper($attributes['TYPE'])) + { + case 'TINYINT': + $attributes['TYPE'] = 'SMALLINT'; + break; + case 'SMALLINT': + $attributes['TYPE'] = ($is_unsigned) ? 'INTEGER' : 'SMALLINT'; + break; + case 'MEDIUMINT': + $attributes['TYPE'] = 'INTEGER'; + break; + case 'INT': + $attributes['TYPE'] = ($is_unsigned) ? 'BIGINT' : 'INTEGER'; + break; + case 'BIGINT': + $attributes['TYPE'] = ($is_unsigned) ? 'NUMERIC' : 'BIGINT'; + break; + case 'DOUBLE': + $attributes['TYPE'] = 'DOUBLE PRECISION'; + break; + case 'DATETIME': + $attributes['TYPE'] = 'TIMESTAMP'; + break; + case 'LONGTEXT': + $attributes['TYPE'] = 'TEXT'; + break; + case 'BLOB': + $attributes['TYPE'] = 'BYTEA'; + break; + } + + // If this is an auto-incrementing primary key, use the serial data type instead + if (in_array($field, $primary_keys) && array_key_exists('AUTO_INCREMENT', $attributes) + && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' SERIAL'; + } + else + { + $sql .= ' '.$attributes['TYPE']; + } + + // Modified to prevent constraints with integer data types + if (array_key_exists('CONSTRAINT', $attributes) && strpos($attributes['TYPE'], 'INT') === false) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + // Added new attribute to create unqite fields. Also works with MySQL + if (array_key_exists('UNIQUE', $attributes) && $attributes['UNIQUE'] === TRUE) + { + $sql .= ' UNIQUE'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + // Something seems to break when passing an array to _protect_identifiers() + foreach ($primary_keys as $index => $key) + { + $primary_keys[$index] = $this->db->_protect_identifiers($key); + } + + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + $sql .= "\n);"; + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + foreach ($key as $field) + { + $sql .= "CREATE INDEX " . $table . "_" . str_replace(array('"', "'"), '', $field) . "_index ON $table ($field); "; + } + } + } + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @access private + * @return bool + */ + function _drop_table($table) + { + return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table)." CASCADE"; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + + +} + +/* End of file postgre_forge.php */ +/* Location: ./system/database/drivers/postgre/postgre_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/postgre/postgre_result.php b/api/system/database/drivers/postgre/postgre_result.php new file mode 100644 index 0000000..e9a1d16 --- /dev/null +++ b/api/system/database/drivers/postgre/postgre_result.php @@ -0,0 +1,169 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @pg_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + for ($i = 0; $i < $this->num_fields(); $i++) + { + $field_names[] = pg_field_name($this->result_id, $i); + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + for ($i = 0; $i < $this->num_fields(); $i++) + { + $F = new stdClass(); + $F->name = pg_field_name($this->result_id, $i); + $F->type = pg_field_type($this->result_id, $i); + $F->max_length = pg_field_size($this->result_id, $i); + $F->primary_key = 0; + $F->default = ''; + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_resource($this->result_id)) + { + pg_free_result($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return pg_result_seek($this->result_id, $n); + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return pg_fetch_assoc($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return pg_fetch_object($this->result_id); + } + +} + + +/* End of file postgre_result.php */ +/* Location: ./system/database/drivers/postgre/postgre_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/postgre/postgre_utility.php b/api/system/database/drivers/postgre/postgre_utility.php new file mode 100644 index 0000000..741c52e --- /dev/null +++ b/api/system/database/drivers/postgre/postgre_utility.php @@ -0,0 +1,88 @@ +db->display_error('db_unsuported_feature'); + } +} + + +/* End of file postgre_utility.php */ +/* Location: ./system/database/drivers/postgre/postgre_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlite/index.html b/api/system/database/drivers/sqlite/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/sqlite/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/sqlite/sqlite_driver.php b/api/system/database/drivers/sqlite/sqlite_driver.php new file mode 100644 index 0000000..0cc898b --- /dev/null +++ b/api/system/database/drivers/sqlite/sqlite_driver.php @@ -0,0 +1,658 @@ +database, FILE_WRITE_MODE, $error)) + { + log_message('error', $error); + + if ($this->db_debug) + { + $this->display_error($error, '', TRUE); + } + + return FALSE; + } + + return $conn_id; + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + if ( ! $conn_id = @sqlite_popen($this->database, FILE_WRITE_MODE, $error)) + { + log_message('error', $error); + + if ($this->db_debug) + { + $this->display_error($error, '', TRUE); + } + + return FALSE; + } + + return $conn_id; + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + // not implemented in SQLite + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + return sqlite_libversion(); + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return @sqlite_query($this->conn_id, $sql); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + $this->simple_query('BEGIN TRANSACTION'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('COMMIT'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + $this->simple_query('ROLLBACK'); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + $str = sqlite_escape_string($str); + + // escape LIKE condition wildcards + if ($like === TRUE) + { + $str = str_replace( array('%', '_', $this->_like_escape_chr), + array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr), + $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return sqlite_changes($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @access public + * @return integer + */ + function insert_id() + { + return @sqlite_last_insert_rowid($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE)); + + if ($query->num_rows() == 0) + { + return 0; + } + + $row = $query->row(); + $this->_reset_select(); + return (int) $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * List table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + $sql = "SELECT name from sqlite_master WHERE type='table'"; + + if ($prefix_limit !== FALSE AND $this->dbprefix != '') + { + $sql .= " AND 'name' LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + } + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access public + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + // Not supported + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT * FROM ".$table." LIMIT 1"; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + return sqlite_error_string(sqlite_last_error($this->conn_id)); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + return sqlite_last_error($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) + { + $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + } + + if (strpos($item, '.') !== FALSE) + { + $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; + } + else + { + $str = $this->_escape_char.$item.$this->_escape_char; + } + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; + + $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); + + $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; + + $sql .= $orderby.$limit; + + return $sql; + } + + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return $this->_delete($table); + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + + if (count($where) > 0 OR count($like) > 0) + { + $conditions = "\nWHERE "; + $conditions .= implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= " AND "; + } + $conditions .= implode("\n", $like); + } + + $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; + + return "DELETE FROM ".$table.$conditions.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + if ($offset == 0) + { + $offset = ''; + } + else + { + $offset .= ", "; + } + + return $sql."LIMIT ".$offset.$limit; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @sqlite_close($conn_id); + } + + +} + + +/* End of file sqlite_driver.php */ +/* Location: ./system/database/drivers/sqlite/sqlite_driver.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlite/sqlite_forge.php b/api/system/database/drivers/sqlite/sqlite_forge.php new file mode 100644 index 0000000..5690408 --- /dev/null +++ b/api/system/database/drivers/sqlite/sqlite_forge.php @@ -0,0 +1,265 @@ +db->database) OR ! @unlink($this->db->database)) + { + if ($this->db->db_debug) + { + return $this->db->display_error('db_unable_to_drop'); + } + return FALSE; + } + return TRUE; + } + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param array the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + // IF NOT EXISTS added to SQLite in 3.3.0 + if ($if_not_exists === TRUE && version_compare($this->db->_version(), '3.3.0', '>=') === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)."("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + $sql .= ",\n\tUNIQUE (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n)"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * Unsupported feature in SQLite + * + * @access private + * @return bool + */ + function _drop_table($table) + { + if ($this->db->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return array(); + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + // SQLite does not support dropping columns + // http://www.sqlite.org/omitted.html + // http://www.sqlite.org/faq.html#q11 + return FALSE; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } +} + +/* End of file sqlite_forge.php */ +/* Location: ./system/database/drivers/sqlite/sqlite_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlite/sqlite_result.php b/api/system/database/drivers/sqlite/sqlite_result.php new file mode 100644 index 0000000..7bd30db --- /dev/null +++ b/api/system/database/drivers/sqlite/sqlite_result.php @@ -0,0 +1,179 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @sqlite_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + for ($i = 0; $i < $this->num_fields(); $i++) + { + $field_names[] = sqlite_field_name($this->result_id, $i); + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + for ($i = 0; $i < $this->num_fields(); $i++) + { + $F = new stdClass(); + $F->name = sqlite_field_name($this->result_id, $i); + $F->type = 'varchar'; + $F->max_length = 0; + $F->primary_key = 0; + $F->default = ''; + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + // Not implemented in SQLite + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + return sqlite_seek($this->result_id, $n); + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return sqlite_fetch_array($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + if (function_exists('sqlite_fetch_object')) + { + return sqlite_fetch_object($this->result_id); + } + else + { + $arr = sqlite_fetch_array($this->result_id, SQLITE_ASSOC); + if (is_array($arr)) + { + $obj = (object) $arr; + return $obj; + } else { + return NULL; + } + } + } + +} + + +/* End of file sqlite_result.php */ +/* Location: ./system/database/drivers/sqlite/sqlite_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlite/sqlite_utility.php b/api/system/database/drivers/sqlite/sqlite_utility.php new file mode 100644 index 0000000..508023e --- /dev/null +++ b/api/system/database/drivers/sqlite/sqlite_utility.php @@ -0,0 +1,96 @@ +db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + return array(); + } + + // -------------------------------------------------------------------- + + /** + * Optimize table query + * + * Is optimization even supported in SQLite? + * + * @access private + * @param string the table name + * @return object + */ + function _optimize_table($table) + { + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Are table repairs even supported in SQLite? + * + * @access private + * @param string the table name + * @return object + */ + function _repair_table($table) + { + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * SQLite Export + * + * @access private + * @param array Preferences + * @return mixed + */ + function _backup($params = array()) + { + // Currently unsupported + return $this->db->display_error('db_unsuported_feature'); + } +} + +/* End of file sqlite_utility.php */ +/* Location: ./system/database/drivers/sqlite/sqlite_utility.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlsrv/index.html b/api/system/database/drivers/sqlsrv/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/drivers/sqlsrv/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/database/drivers/sqlsrv/sqlsrv_driver.php b/api/system/database/drivers/sqlsrv/sqlsrv_driver.php new file mode 100644 index 0000000..49cfea3 --- /dev/null +++ b/api/system/database/drivers/sqlsrv/sqlsrv_driver.php @@ -0,0 +1,598 @@ +char_set)) ? 'UTF-8' : $this->char_set; + + $connection = array( + 'UID' => empty($this->username) ? '' : $this->username, + 'PWD' => empty($this->password) ? '' : $this->password, + 'Database' => $this->database, + 'ConnectionPooling' => $pooling ? 1 : 0, + 'CharacterSet' => $character_set, + 'ReturnDatesAsStrings' => 1 + ); + + // If the username and password are both empty, assume this is a + // 'Windows Authentication Mode' connection. + if(empty($connection['UID']) && empty($connection['PWD'])) { + unset($connection['UID'], $connection['PWD']); + } + return sqlsrv_connect($this->hostname, $connection); + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @access private called by the base class + * @return resource + */ + function db_pconnect() + { + return $this->db_connect(TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Reconnect + * + * Keep / reestablish the db connection if no queries have been + * sent for a length of time exceeding the server's idle timeout + * + * @access public + * @return void + */ + function reconnect() + { + // not implemented in MSSQL + } + + // -------------------------------------------------------------------- + + /** + * Select the database + * + * @access private called by the base class + * @return resource + */ + function db_select() + { + return $this->_execute('USE ' . $this->database); + } + + // -------------------------------------------------------------------- + + /** + * Set client character set + * + * @access public + * @param string + * @param string + * @return resource + */ + function db_set_charset($charset, $collation) + { + // @todo - add support if needed + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @access private called by the base class + * @param string an SQL query + * @return resource + */ + function _execute($sql) + { + $sql = $this->_prep_query($sql); + return sqlsrv_query($this->conn_id, $sql, null, array( + 'Scrollable' => SQLSRV_CURSOR_STATIC, + 'SendStreamParamsAtExec' => true + )); + } + + // -------------------------------------------------------------------- + + /** + * Prep the query + * + * If needed, each database adapter can prep the query string + * + * @access private called by execute() + * @param string an SQL query + * @return string + */ + function _prep_query($sql) + { + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @access public + * @return bool + */ + function trans_begin($test_mode = FALSE) + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; + + return sqlsrv_begin_transaction($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @access public + * @return bool + */ + function trans_commit() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + return sqlsrv_commit($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @access public + * @return bool + */ + function trans_rollback() + { + if ( ! $this->trans_enabled) + { + return TRUE; + } + + // When transactions are nested we only begin/commit/rollback the outermost ones + if ($this->_trans_depth > 0) + { + return TRUE; + } + + return sqlsrv_rollback($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @access public + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + function escape_str($str, $like = FALSE) + { + // Escape single quotes + return str_replace("'", "''", $str); + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @access public + * @return integer + */ + function affected_rows() + { + return @sqlrv_rows_affected($this->conn_id); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * Returns the last id created in the Identity column. + * + * @access public + * @return integer + */ + function insert_id() + { + return $this->query('select @@IDENTITY as insert_id')->row('insert_id'); + } + + // -------------------------------------------------------------------- + + /** + * Parse major version + * + * Grabs the major version number from the + * database server version string passed in. + * + * @access private + * @param string $version + * @return int16 major version number + */ + function _parse_major_version($version) + { + preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info); + return $ver_info[1]; // return the major version b/c that's all we're interested in. + } + + // -------------------------------------------------------------------- + + /** + * Version number query string + * + * @access public + * @return string + */ + function _version() + { + $info = sqlsrv_server_info($this->conn_id); + return sprintf("select '%s' as ver", $info['SQLServerVersion']); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @access public + * @param string + * @return string + */ + function count_all($table = '') + { + if ($table == '') + return '0'; + + $query = $this->query("SELECT COUNT(*) AS numrows FROM " . $this->dbprefix . $table); + + if ($query->num_rows() == 0) + return '0'; + + $row = $query->row(); + $this->_reset_select(); + return $row->numrows; + } + + // -------------------------------------------------------------------- + + /** + * List table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @access private + * @param boolean + * @return string + */ + function _list_tables($prefix_limit = FALSE) + { + return "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name"; + } + + // -------------------------------------------------------------------- + + /** + * List column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @access private + * @param string the table name + * @return string + */ + function _list_columns($table = '') + { + return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$this->_escape_table($table)."'"; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @access public + * @param string the table name + * @return object + */ + function _field_data($table) + { + return "SELECT TOP 1 * FROM " . $this->_escape_table($table); + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @access private + * @return string + */ + function _error_message() + { + $error = array_shift(sqlsrv_errors()); + return !empty($error['message']) ? $error['message'] : null; + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @access private + * @return integer + */ + function _error_number() + { + $error = array_shift(sqlsrv_errors()); + return isset($error['SQLSTATE']) ? $error['SQLSTATE'] : null; + } + + // -------------------------------------------------------------------- + + /** + * Escape Table Name + * + * This function adds backticks if the table name has a period + * in it. Some DBs will get cranky unless periods are escaped + * + * @access private + * @param string the table name + * @return string + */ + function _escape_table($table) + { + return $table; + } + + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @access private + * @param string + * @return string + */ + function _escape_identifiers($item) + { + return $item; + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @access public + * @param type + * @return type + */ + function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return implode(', ', $tables); + } + + // -------------------------------------------------------------------- + + /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @access public + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + function _insert($table, $keys, $values) + { + return "INSERT INTO ".$this->_escape_table($table)." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + } + + // -------------------------------------------------------------------- + + /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @access public + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + function _update($table, $values, $where) + { + foreach($values as $key => $val) + { + $valstr[] = $key." = ".$val; + } + + return "UPDATE ".$this->_escape_table($table)." SET ".implode(', ', $valstr)." WHERE ".implode(" ", $where); + } + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * If the database does not support the truncate() command + * This function maps to "DELETE FROM table" + * + * @access public + * @param string the table name + * @return string + */ + function _truncate($table) + { + return "TRUNCATE ".$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @access public + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + function _delete($table, $where) + { + return "DELETE FROM ".$this->_escape_table($table)." WHERE ".implode(" ", $where); + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @access public + * @param string the sql query string + * @param integer the number of rows to limit the query to + * @param integer the offset value + * @return string + */ + function _limit($sql, $limit, $offset) + { + $i = $limit + $offset; + + return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql); + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @access public + * @param resource + * @return void + */ + function _close($conn_id) + { + @sqlsrv_close($conn_id); + } + +} + + + +/* End of file mssql_driver.php */ +/* Location: ./system/database/drivers/mssql/mssql_driver.php */ diff --git a/api/system/database/drivers/sqlsrv/sqlsrv_forge.php b/api/system/database/drivers/sqlsrv/sqlsrv_forge.php new file mode 100644 index 0000000..cc88ec5 --- /dev/null +++ b/api/system/database/drivers/sqlsrv/sqlsrv_forge.php @@ -0,0 +1,248 @@ +db->_escape_identifiers($table); + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @access private + * @param string the table name + * @param array the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param boolean should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + if ($if_not_exists === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->_escape_identifiers($table)." ("; + $current_field_count = 0; + + foreach ($fields as $field=>$attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t$attributes"; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->_protect_identifiers($field); + + $sql .= ' '.$attributes['TYPE']; + + if (array_key_exists('CONSTRAINT', $attributes)) + { + $sql .= '('.$attributes['CONSTRAINT'].')'; + } + + if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE) + { + $sql .= ' UNSIGNED'; + } + + if (array_key_exists('DEFAULT', $attributes)) + { + $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\''; + } + + if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE) + { + $sql .= ' AUTO_INCREMENT'; + } + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->_protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")"; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->_protect_identifiers($key); + } + else + { + $key = array($this->db->_protect_identifiers($key)); + } + + $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")"; + } + } + + $sql .= "\n)"; + + return $sql; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @access private + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param boolean should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return object + */ + function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table)." $alter_type ".$this->db->_protect_identifiers($column_name); + + // DROP has everything it needs now. + if ($alter_type == 'DROP') + { + return $sql; + } + + $sql .= " $column_definition"; + + if ($default_value != '') + { + $sql .= " DEFAULT \"$default_value\""; + } + + if ($null === NULL) + { + $sql .= ' NULL'; + } + else + { + $sql .= ' NOT NULL'; + } + + if ($after_field != '') + { + $sql .= ' AFTER ' . $this->db->_protect_identifiers($after_field); + } + + return $sql; + + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @access private + * @param string the old table name + * @param string the new table name + * @return string + */ + function _rename_table($table_name, $new_table_name) + { + // I think this syntax will work, but can find little documentation on renaming tables in MSSQL + $sql = 'ALTER TABLE '.$this->db->_protect_identifiers($table_name)." RENAME TO ".$this->db->_protect_identifiers($new_table_name); + return $sql; + } + +} + +/* End of file mssql_forge.php */ +/* Location: ./system/database/drivers/mssql/mssql_forge.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlsrv/sqlsrv_result.php b/api/system/database/drivers/sqlsrv/sqlsrv_result.php new file mode 100644 index 0000000..bf0abd1 --- /dev/null +++ b/api/system/database/drivers/sqlsrv/sqlsrv_result.php @@ -0,0 +1,169 @@ +result_id); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @access public + * @return integer + */ + function num_fields() + { + return @sqlsrv_num_fields($this->result_id); + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @access public + * @return array + */ + function list_fields() + { + $field_names = array(); + foreach(sqlsrv_field_metadata($this->result_id) as $offset => $field) + { + $field_names[] = $field['Name']; + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @access public + * @return array + */ + function field_data() + { + $retval = array(); + foreach(sqlsrv_field_metadata($this->result_id) as $offset => $field) + { + $F = new stdClass(); + $F->name = $field['Name']; + $F->type = $field['Type']; + $F->max_length = $field['Size']; + $F->primary_key = 0; + $F->default = ''; + + $retval[] = $F; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return null + */ + function free_result() + { + if (is_resource($this->result_id)) + { + sqlsrv_free_stmt($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @access private + * @return array + */ + function _data_seek($n = 0) + { + // Not implemented + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @access private + * @return array + */ + function _fetch_assoc() + { + return sqlsrv_fetch_array($this->result_id, SQLSRV_FETCH_ASSOC); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @access private + * @return object + */ + function _fetch_object() + { + return sqlsrv_fetch_object($this->result_id); + } + +} + + +/* End of file mssql_result.php */ +/* Location: ./system/database/drivers/mssql/mssql_result.php */ \ No newline at end of file diff --git a/api/system/database/drivers/sqlsrv/sqlsrv_utility.php b/api/system/database/drivers/sqlsrv/sqlsrv_utility.php new file mode 100644 index 0000000..13a1850 --- /dev/null +++ b/api/system/database/drivers/sqlsrv/sqlsrv_utility.php @@ -0,0 +1,88 @@ +db->display_error('db_unsuported_feature'); + } + +} + +/* End of file mssql_utility.php */ +/* Location: ./system/database/drivers/mssql/mssql_utility.php */ \ No newline at end of file diff --git a/api/system/database/index.html b/api/system/database/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/database/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/fonts/index.html b/api/system/fonts/index.html new file mode 100644 index 0000000..c942a79 --- /dev/null +++ b/api/system/fonts/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/api/system/fonts/texb.ttf b/api/system/fonts/texb.ttf new file mode 100644 index 0000000..383c88b Binary files /dev/null and b/api/system/fonts/texb.ttf differ diff --git a/api/system/helpers/array_helper.php b/api/system/helpers/array_helper.php new file mode 100644 index 0000000..075a31f --- /dev/null +++ b/api/system/helpers/array_helper.php @@ -0,0 +1,119 @@ + '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200); + + foreach ($defaults as $key => $val) + { + if ( ! is_array($data)) + { + if ( ! isset($$key) OR $$key == '') + { + $$key = $val; + } + } + else + { + $$key = ( ! isset($data[$key])) ? $val : $data[$key]; + } + } + + if ($img_path == '' OR $img_url == '') + { + return FALSE; + } + + if ( ! @is_dir($img_path)) + { + return FALSE; + } + + if ( ! is_writable($img_path)) + { + return FALSE; + } + + if ( ! extension_loaded('gd')) + { + return FALSE; + } + + // ----------------------------------- + // Remove old images + // ----------------------------------- + + list($usec, $sec) = explode(" ", microtime()); + $now = ((float)$usec + (float)$sec); + + $current_dir = @opendir($img_path); + + while ($filename = @readdir($current_dir)) + { + if ($filename != "." and $filename != ".." and $filename != "index.html") + { + $name = str_replace(".jpg", "", $filename); + + if (($name + $expiration) < $now) + { + @unlink($img_path.$filename); + } + } + } + + @closedir($current_dir); + + // ----------------------------------- + // Do we have a "word" yet? + // ----------------------------------- + + if ($word == '') + { + $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + + $str = ''; + for ($i = 0; $i < 8; $i++) + { + $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); + } + + $word = $str; + } + + // ----------------------------------- + // Determine angle and position + // ----------------------------------- + + $length = strlen($word); + $angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0; + $x_axis = rand(6, (360/$length)-16); + $y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height); + + // ----------------------------------- + // Create image + // ----------------------------------- + + // PHP.net recommends imagecreatetruecolor(), but it isn't always available + if (function_exists('imagecreatetruecolor')) + { + $im = imagecreatetruecolor($img_width, $img_height); + } + else + { + $im = imagecreate($img_width, $img_height); + } + + // ----------------------------------- + // Assign colors + // ----------------------------------- + + $bg_color = imagecolorallocate ($im, 255, 255, 255); + $border_color = imagecolorallocate ($im, 153, 102, 102); + $text_color = imagecolorallocate ($im, 204, 153, 153); + $grid_color = imagecolorallocate($im, 255, 182, 182); + $shadow_color = imagecolorallocate($im, 255, 240, 240); + + // ----------------------------------- + // Create the rectangle + // ----------------------------------- + + ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color); + + // ----------------------------------- + // Create the spiral pattern + // ----------------------------------- + + $theta = 1; + $thetac = 7; + $radius = 16; + $circles = 20; + $points = 32; + + for ($i = 0; $i < ($circles * $points) - 1; $i++) + { + $theta = $theta + $thetac; + $rad = $radius * ($i / $points ); + $x = ($rad * cos($theta)) + $x_axis; + $y = ($rad * sin($theta)) + $y_axis; + $theta = $theta + $thetac; + $rad1 = $radius * (($i + 1) / $points); + $x1 = ($rad1 * cos($theta)) + $x_axis; + $y1 = ($rad1 * sin($theta )) + $y_axis; + imageline($im, $x, $y, $x1, $y1, $grid_color); + $theta = $theta - $thetac; + } + + // ----------------------------------- + // Write the text + // ----------------------------------- + + $use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE; + + if ($use_font == FALSE) + { + $font_size = 5; + $x = rand(0, $img_width/($length/3)); + $y = 0; + } + else + { + $font_size = 16; + $x = rand(0, $img_width/($length/1.5)); + $y = $font_size+2; + } + + for ($i = 0; $i < strlen($word); $i++) + { + if ($use_font == FALSE) + { + $y = rand(0 , $img_height/2); + imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color); + $x += ($font_size*2); + } + else + { + $y = rand($img_height/2, $img_height-3); + imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1)); + $x += $font_size; + } + } + + + // ----------------------------------- + // Create the border + // ----------------------------------- + + imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color); + + // ----------------------------------- + // Generate the image + // ----------------------------------- + + $img_name = $now.'.jpg'; + + ImageJPEG($im, $img_path.$img_name); + + $img = "\""; + + ImageDestroy($im); + + return array('word' => $word, 'time' => $now, 'image' => $img); + } +} + +// ------------------------------------------------------------------------ + +/* End of file captcha_helper.php */ +/* Location: ./system/heleprs/captcha_helper.php */ \ No newline at end of file diff --git a/api/system/helpers/cookie_helper.php b/api/system/helpers/cookie_helper.php new file mode 100644 index 0000000..7cee028 --- /dev/null +++ b/api/system/helpers/cookie_helper.php @@ -0,0 +1,103 @@ +input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); + } +} + +// -------------------------------------------------------------------- + +/** + * Fetch an item from the COOKIE array + * + * @access public + * @param string + * @param bool + * @return mixed + */ +if ( ! function_exists('get_cookie')) +{ + function get_cookie($index = '', $xss_clean = FALSE) + { + $CI =& get_instance(); + + $prefix = ''; + + if ( ! isset($_COOKIE[$index]) && config_item('cookie_prefix') != '') + { + $prefix = config_item('cookie_prefix'); + } + + return $CI->input->cookie($prefix.$index, $xss_clean); + } +} + +// -------------------------------------------------------------------- + +/** + * Delete a COOKIE + * + * @param mixed + * @param string the cookie domain. Usually: .yourdomain.com + * @param string the cookie path + * @param string the cookie prefix + * @return void + */ +if ( ! function_exists('delete_cookie')) +{ + function delete_cookie($name = '', $domain = '', $path = '/', $prefix = '') + { + set_cookie($name, '', '', $domain, $path, $prefix); + } +} + + +/* End of file cookie_helper.php */ +/* Location: ./system/helpers/cookie_helper.php */ \ No newline at end of file diff --git a/api/system/helpers/date_helper.php b/api/system/helpers/date_helper.php new file mode 100644 index 0000000..0aeb7fa --- /dev/null +++ b/api/system/helpers/date_helper.php @@ -0,0 +1,611 @@ +config->item('time_reference')) == 'gmt') + { + $now = time(); + $system_time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now)); + + if (strlen($system_time) < 10) + { + $system_time = time(); + log_message('error', 'The Date class could not set a proper GMT timestamp so the local time() value was used.'); + } + + return $system_time; + } + else + { + return time(); + } + } +} + +// ------------------------------------------------------------------------ + +/** + * Convert MySQL Style Datecodes + * + * This function is identical to PHPs date() function, + * except that it allows date codes to be formatted using + * the MySQL style, where each code letter is preceded + * with a percent sign: %Y %m %d etc... + * + * The benefit of doing dates this way is that you don't + * have to worry about escaping your text letters that + * match the date codes. + * + * @access public + * @param string + * @param integer + * @return integer + */ +if ( ! function_exists('mdate')) +{ + function mdate($datestr = '', $time = '') + { + if ($datestr == '') + return ''; + + if ($time == '') + $time = now(); + + $datestr = str_replace('%\\', '', preg_replace("/([a-z]+?){1}/i", "\\\\\\1", $datestr)); + return date($datestr, $time); + } +} + +// ------------------------------------------------------------------------ + +/** + * Standard Date + * + * Returns a date formatted according to the submitted standard. + * + * @access public + * @param string the chosen format + * @param integer Unix timestamp + * @return string + */ +if ( ! function_exists('standard_date')) +{ + function standard_date($fmt = 'DATE_RFC822', $time = '') + { + $formats = array( + 'DATE_ATOM' => '%Y-%m-%dT%H:%i:%s%Q', + 'DATE_COOKIE' => '%l, %d-%M-%y %H:%i:%s UTC', + 'DATE_ISO8601' => '%Y-%m-%dT%H:%i:%s%Q', + 'DATE_RFC822' => '%D, %d %M %y %H:%i:%s %O', + 'DATE_RFC850' => '%l, %d-%M-%y %H:%i:%s UTC', + 'DATE_RFC1036' => '%D, %d %M %y %H:%i:%s %O', + 'DATE_RFC1123' => '%D, %d %M %Y %H:%i:%s %O', + 'DATE_RSS' => '%D, %d %M %Y %H:%i:%s %O', + 'DATE_W3C' => '%Y-%m-%dT%H:%i:%s%Q' + ); + + if ( ! isset($formats[$fmt])) + { + return FALSE; + } + + return mdate($formats[$fmt], $time); + } +} + +// ------------------------------------------------------------------------ + +/** + * Timespan + * + * Returns a span of seconds in this format: + * 10 days 14 hours 36 minutes 47 seconds + * + * @access public + * @param integer a number of seconds + * @param integer Unix timestamp + * @return integer + */ +if ( ! function_exists('timespan')) +{ + function timespan($seconds = 1, $time = '') + { + $CI =& get_instance(); + $CI->lang->load('date'); + + if ( ! is_numeric($seconds)) + { + $seconds = 1; + } + + if ( ! is_numeric($time)) + { + $time = time(); + } + + if ($time <= $seconds) + { + $seconds = 1; + } + else + { + $seconds = $time - $seconds; + } + + $str = ''; + $years = floor($seconds / 31536000); + + if ($years > 0) + { + $str .= $years.' '.$CI->lang->line((($years > 1) ? 'date_years' : 'date_year')).', '; + } + + $seconds -= $years * 31536000; + $months = floor($seconds / 2628000); + + if ($years > 0 OR $months > 0) + { + if ($months > 0) + { + $str .= $months.' '.$CI->lang->line((($months > 1) ? 'date_months' : 'date_month')).', '; + } + + $seconds -= $months * 2628000; + } + + $weeks = floor($seconds / 604800); + + if ($years > 0 OR $months > 0 OR $weeks > 0) + { + if ($weeks > 0) + { + $str .= $weeks.' '.$CI->lang->line((($weeks > 1) ? 'date_weeks' : 'date_week')).', '; + } + + $seconds -= $weeks * 604800; + } + + $days = floor($seconds / 86400); + + if ($months > 0 OR $weeks > 0 OR $days > 0) + { + if ($days > 0) + { + $str .= $days.' '.$CI->lang->line((($days > 1) ? 'date_days' : 'date_day')).', '; + } + + $seconds -= $days * 86400; + } + + $hours = floor($seconds / 3600); + + if ($days > 0 OR $hours > 0) + { + if ($hours > 0) + { + $str .= $hours.' '.$CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')).', '; + } + + $seconds -= $hours * 3600; + } + + $minutes = floor($seconds / 60); + + if ($days > 0 OR $hours > 0 OR $minutes > 0) + { + if ($minutes > 0) + { + $str .= $minutes.' '.$CI->lang->line((($minutes > 1) ? 'date_minutes' : 'date_minute')).', '; + } + + $seconds -= $minutes * 60; + } + + if ($str == '') + { + $str .= $seconds.' '.$CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')).', '; + } + + return substr(trim($str), 0, -1); + } +} + +// ------------------------------------------------------------------------ + +/** + * Number of days in a month + * + * Takes a month/year as input and returns the number of days + * for the given month/year. Takes leap years into consideration. + * + * @access public + * @param integer a numeric month + * @param integer a numeric year + * @return integer + */ +if ( ! function_exists('days_in_month')) +{ + function days_in_month($month = 0, $year = '') + { + if ($month < 1 OR $month > 12) + { + return 0; + } + + if ( ! is_numeric($year) OR strlen($year) != 4) + { + $year = date('Y'); + } + + if ($month == 2) + { + if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0)) + { + return 29; + } + } + + $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); + return $days_in_month[$month - 1]; + } +} + +// ------------------------------------------------------------------------ + +/** + * Converts a local Unix timestamp to GMT + * + * @access public + * @param integer Unix timestamp + * @return integer + */ +if ( ! function_exists('local_to_gmt')) +{ + function local_to_gmt($time = '') + { + if ($time == '') + $time = time(); + + return mktime( gmdate("H", $time), gmdate("i", $time), gmdate("s", $time), gmdate("m", $time), gmdate("d", $time), gmdate("Y", $time)); + } +} + +// ------------------------------------------------------------------------ + +/** + * Converts GMT time to a localized value + * + * Takes a Unix timestamp (in GMT) as input, and returns + * at the local value based on the timezone and DST setting + * submitted + * + * @access public + * @param integer Unix timestamp + * @param string timezone + * @param bool whether DST is active + * @return integer + */ +if ( ! function_exists('gmt_to_local')) +{ + function gmt_to_local($time = '', $timezone = 'UTC', $dst = FALSE) + { + if ($time == '') + { + return now(); + } + + $time += timezones($timezone) * 3600; + + if ($dst == TRUE) + { + $time += 3600; + } + + return $time; + } +} + +// ------------------------------------------------------------------------ + +/** + * Converts a MySQL Timestamp to Unix + * + * @access public + * @param integer Unix timestamp + * @return integer + */ +if ( ! function_exists('mysql_to_unix')) +{ + function mysql_to_unix($time = '') + { + // We'll remove certain characters for backward compatibility + // since the formatting changed with MySQL 4.1 + // YYYY-MM-DD HH:MM:SS + + $time = str_replace('-', '', $time); + $time = str_replace(':', '', $time); + $time = str_replace(' ', '', $time); + + // YYYYMMDDHHMMSS + return mktime( + substr($time, 8, 2), + substr($time, 10, 2), + substr($time, 12, 2), + substr($time, 4, 2), + substr($time, 6, 2), + substr($time, 0, 4) + ); + } +} + +// ------------------------------------------------------------------------ + +/** + * Unix to "Human" + * + * Formats Unix timestamp to the following prototype: 2006-08-21 11:35 PM + * + * @access public + * @param integer Unix timestamp + * @param bool whether to show seconds + * @param string format: us or euro + * @return string + */ +if ( ! function_exists('unix_to_human')) +{ + function unix_to_human($time = '', $seconds = FALSE, $fmt = 'us') + { + $r = date('Y', $time).'-'.date('m', $time).'-'.date('d', $time).' '; + + if ($fmt == 'us') + { + $r .= date('h', $time).':'.date('i', $time); + } + else + { + $r .= date('H', $time).':'.date('i', $time); + } + + if ($seconds) + { + $r .= ':'.date('s', $time); + } + + if ($fmt == 'us') + { + $r .= ' '.date('A', $time); + } + + return $r; + } +} + +// ------------------------------------------------------------------------ + +/** + * Convert "human" date to GMT + * + * Reverses the above process + * + * @access public + * @param string format: us or euro + * @return integer + */ +if ( ! function_exists('human_to_unix')) +{ + function human_to_unix($datestr = '') + { + if ($datestr == '') + { + return FALSE; + } + + $datestr = trim($datestr); + $datestr = preg_replace("/\040+/", ' ', $datestr); + + if ( ! preg_match('/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}(?::[0-9]{1,2})?(?:\s[AP]M)?$/i', $datestr)) + { + return FALSE; + } + + $split = explode(' ', $datestr); + + $ex = explode("-", $split['0']); + + $year = (strlen($ex['0']) == 2) ? '20'.$ex['0'] : $ex['0']; + $month = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1']; + $day = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2']; + + $ex = explode(":", $split['1']); + + $hour = (strlen($ex['0']) == 1) ? '0'.$ex['0'] : $ex['0']; + $min = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1']; + + if (isset($ex['2']) && preg_match('/[0-9]{1,2}/', $ex['2'])) + { + $sec = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2']; + } + else + { + // Unless specified, seconds get set to zero. + $sec = '00'; + } + + if (isset($split['2'])) + { + $ampm = strtolower($split['2']); + + if (substr($ampm, 0, 1) == 'p' AND $hour < 12) + $hour = $hour + 12; + + if (substr($ampm, 0, 1) == 'a' AND $hour == 12) + $hour = '00'; + + if (strlen($hour) == 1) + $hour = '0'.$hour; + } + + return mktime($hour, $min, $sec, $month, $day, $year); + } +} + +// ------------------------------------------------------------------------ + +/** + * Timezone Menu + * + * Generates a drop-down menu of timezones. + * + * @access public + * @param string timezone + * @param string classname + * @param string menu name + * @return string + */ +if ( ! function_exists('timezone_menu')) +{ + function timezone_menu($default = 'UTC', $class = "", $name = 'timezones') + { + $CI =& get_instance(); + $CI->lang->load('date'); + + if ($default == 'GMT') + $default = 'UTC'; + + $menu = '"; + + return $menu; + } +} + +// ------------------------------------------------------------------------ + +/** + * Timezones + * + * Returns an array of timezones. This is a helper function + * for various other ones in this library + * + * @access public + * @param string timezone + * @return string + */ +if ( ! function_exists('timezones')) +{ + function timezones($tz = '') + { + // Note: Don't change the order of these even though + // some items appear to be in the wrong order + + $zones = array( + 'UM12' => -12, + 'UM11' => -11, + 'UM10' => -10, + 'UM95' => -9.5, + 'UM9' => -9, + 'UM8' => -8, + 'UM7' => -7, + 'UM6' => -6, + 'UM5' => -5, + 'UM45' => -4.5, + 'UM4' => -4, + 'UM35' => -3.5, + 'UM3' => -3, + 'UM2' => -2, + 'UM1' => -1, + 'UTC' => 0, + 'UP1' => +1, + 'UP2' => +2, + 'UP3' => +3, + 'UP35' => +3.5, + 'UP4' => +4, + 'UP45' => +4.5, + 'UP5' => +5, + 'UP55' => +5.5, + 'UP575' => +5.75, + 'UP6' => +6, + 'UP65' => +6.5, + 'UP7' => +7, + 'UP8' => +8, + 'UP875' => +8.75, + 'UP9' => +9, + 'UP95' => +9.5, + 'UP10' => +10, + 'UP105' => +10.5, + 'UP11' => +11, + 'UP115' => +11.5, + 'UP12' => +12, + 'UP1275' => +12.75, + 'UP13' => +13, + 'UP14' => +14 + ); + + if ($tz == '') + { + return $zones; + } + + if ($tz == 'GMT') + $tz = 'UTC'; + + return ( ! isset($zones[$tz])) ? 0 : $zones[$tz]; + } +} + + +/* End of file date_helper.php */ +/* Location: ./system/helpers/date_helper.php */ \ No newline at end of file diff --git a/api/system/helpers/directory_helper.php b/api/system/helpers/directory_helper.php new file mode 100644 index 0000000..38347fa --- /dev/null +++ b/api/system/helpers/directory_helper.php @@ -0,0 +1,80 @@ + 0) && @is_dir($source_dir.$file)) + { + $filedata[$file] = directory_map($source_dir.$file.DIRECTORY_SEPARATOR, $new_depth, $hidden); + } + else + { + $filedata[] = $file; + } + } + + closedir($fp); + return $filedata; + } + + return FALSE; + } +} + + +/* End of file directory_helper.php */ +/* Location: ./system/helpers/directory_helper.php */ \ No newline at end of file diff --git a/api/system/helpers/download_helper.php b/api/system/helpers/download_helper.php new file mode 100644 index 0000000..1145688 --- /dev/null +++ b/api/system/helpers/download_helper.php @@ -0,0 +1,107 @@ + 0) + { + $data =& fread($fp, filesize($file)); + } + + flock($fp, LOCK_UN); + fclose($fp); + + return $data; + } +} + +// ------------------------------------------------------------------------ + +/** + * Write File + * + * Writes data to the file specified in the path. + * Creates a new file if non-existent. + * + * @access public + * @param string path to file + * @param string file data + * @return bool + */ +if ( ! function_exists('write_file')) +{ + function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE) + { + if ( ! $fp = @fopen($path, $mode)) + { + return FALSE; + } + + flock($fp, LOCK_EX); + fwrite($fp, $data); + flock($fp, LOCK_UN); + fclose($fp); + + return TRUE; + } +} + +// ------------------------------------------------------------------------ + +/** + * Delete Files + * + * Deletes all files contained in the supplied directory path. + * Files must be writable or owned by the system in order to be deleted. + * If the second parameter is set to TRUE, any directories contained + * within the supplied base directory will be nuked as well. + * + * @access public + * @param string path to file + * @param bool whether to delete any directories found in the path + * @return bool + */ +if ( ! function_exists('delete_files')) +{ + function delete_files($path, $del_dir = FALSE, $level = 0) + { + // Trim the trailing slash + $path = rtrim($path, DIRECTORY_SEPARATOR); + + if ( ! $current_dir = @opendir($path)) + { + return FALSE; + } + + while (FALSE !== ($filename = @readdir($current_dir))) + { + if ($filename != "." and $filename != "..") + { + if (is_dir($path.DIRECTORY_SEPARATOR.$filename)) + { + // Ignore empty folders + if (substr($filename, 0, 1) != '.') + { + delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1); + } + } + else + { + unlink($path.DIRECTORY_SEPARATOR.$filename); + } + } + } + @closedir($current_dir); + + if ($del_dir == TRUE AND $level > 0) + { + return @rmdir($path); + } + + return TRUE; + } +} + +// ------------------------------------------------------------------------ + +/** + * Get Filenames + * + * Reads the specified directory and builds an array containing the filenames. + * Any sub-folders contained within the specified path are read as well. + * + * @access public + * @param string path to source + * @param bool whether to include the path as part of the filename + * @param bool internal variable to determine recursion status - do not use in calls + * @return array + */ +if ( ! function_exists('get_filenames')) +{ + function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE) + { + static $_filedata = array(); + + if ($fp = @opendir($source_dir)) + { + // reset the array and make sure $source_dir has a trailing slash on the initial call + if ($_recursion === FALSE) + { + $_filedata = array(); + $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; + } + + while (FALSE !== ($file = readdir($fp))) + { + if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0) + { + get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE); + } + elseif (strncmp($file, '.', 1) !== 0) + { + $_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file; + } + } + return $_filedata; + } + else + { + return FALSE; + } + } +} + +// -------------------------------------------------------------------- + +/** + * Get Directory File Information + * + * Reads the specified directory and builds an array containing the filenames, + * filesize, dates, and permissions + * + * Any sub-folders contained within the specified path are read as well. + * + * @access public + * @param string path to source + * @param bool Look only at the top level directory specified? + * @param bool internal variable to determine recursion status - do not use in calls + * @return array + */ +if ( ! function_exists('get_dir_file_info')) +{ + function get_dir_file_info($source_dir, $top_level_only = TRUE, $_recursion = FALSE) + { + static $_filedata = array(); + $relative_path = $source_dir; + + if ($fp = @opendir($source_dir)) + { + // reset the array and make sure $source_dir has a trailing slash on the initial call + if ($_recursion === FALSE) + { + $_filedata = array(); + $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; + } + + // foreach (scandir($source_dir, 1) as $file) // In addition to being PHP5+, scandir() is simply not as fast + while (FALSE !== ($file = readdir($fp))) + { + if (@is_dir($source_dir.$file) AND strncmp($file, '.', 1) !== 0 AND $top_level_only === FALSE) + { + get_dir_file_info($source_dir.$file.DIRECTORY_SEPARATOR, $top_level_only, TRUE); + } + elseif (strncmp($file, '.', 1) !== 0) + { + $_filedata[$file] = get_file_info($source_dir.$file); + $_filedata[$file]['relative_path'] = $relative_path; + } + } + + return $_filedata; + } + else + { + return FALSE; + } + } +} + +// -------------------------------------------------------------------- + +/** +* Get File Info +* +* Given a file and path, returns the name, path, size, date modified +* Second parameter allows you to explicitly declare what information you want returned +* Options are: name, server_path, size, date, readable, writable, executable, fileperms +* Returns FALSE if the file cannot be found. +* +* @access public +* @param string path to file +* @param mixed array or comma separated string of information returned +* @return array +*/ +if ( ! function_exists('get_file_info')) +{ + function get_file_info($file, $returned_values = array('name', 'server_path', 'size', 'date')) + { + + if ( ! file_exists($file)) + { + return FALSE; + } + + if (is_string($returned_values)) + { + $returned_values = explode(',', $returned_values); + } + + foreach ($returned_values as $key) + { + switch ($key) + { + case 'name': + $fileinfo['name'] = substr(strrchr($file, DIRECTORY_SEPARATOR), 1); + break; + case 'server_path': + $fileinfo['server_path'] = $file; + break; + case 'size': + $fileinfo['size'] = filesize($file); + break; + case 'date': + $fileinfo['date'] = filemtime($file); + break; + case 'readable': + $fileinfo['readable'] = is_readable($file); + break; + case 'writable': + // There are known problems using is_weritable on IIS. It may not be reliable - consider fileperms() + $fileinfo['writable'] = is_writable($file); + break; + case 'executable': + $fileinfo['executable'] = is_executable($file); + break; + case 'fileperms': + $fileinfo['fileperms'] = fileperms($file); + break; + } + } + + return $fileinfo; + } +} + +// -------------------------------------------------------------------- + +/** + * Get Mime by Extension + * + * Translates a file extension into a mime type based on config/mimes.php. + * Returns FALSE if it can't determine the type, or open the mime config file + * + * Note: this is NOT an accurate way of determining file mime types, and is here strictly as a convenience + * It should NOT be trusted, and should certainly NOT be used for security + * + * @access public + * @param string path to file + * @return mixed + */ +if ( ! function_exists('get_mime_by_extension')) +{ + function get_mime_by_extension($file) + { + $extension = strtolower(substr(strrchr($file, '.'), 1)); + + global $mimes; + + if ( ! is_array($mimes)) + { + if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); + } + elseif (is_file(APPPATH.'config/mimes.php')) + { + include(APPPATH.'config/mimes.php'); + } + + if ( ! is_array($mimes)) + { + return FALSE; + } + } + + if (array_key_exists($extension, $mimes)) + { + if (is_array($mimes[$extension])) + { + // Multiple mime types, just give the first one + return current($mimes[$extension]); + } + else + { + return $mimes[$extension]; + } + } + else + { + return FALSE; + } + } +} + +// -------------------------------------------------------------------- + +/** + * Symbolic Permissions + * + * Takes a numeric value representing a file's permissions and returns + * standard symbolic notation representing that value + * + * @access public + * @param int + * @return string + */ +if ( ! function_exists('symbolic_permissions')) +{ + function symbolic_permissions($perms) + { + if (($perms & 0xC000) == 0xC000) + { + $symbolic = 's'; // Socket + } + elseif (($perms & 0xA000) == 0xA000) + { + $symbolic = 'l'; // Symbolic Link + } + elseif (($perms & 0x8000) == 0x8000) + { + $symbolic = '-'; // Regular + } + elseif (($perms & 0x6000) == 0x6000) + { + $symbolic = 'b'; // Block special + } + elseif (($perms & 0x4000) == 0x4000) + { + $symbolic = 'd'; // Directory + } + elseif (($perms & 0x2000) == 0x2000) + { + $symbolic = 'c'; // Character special + } + elseif (($perms & 0x1000) == 0x1000) + { + $symbolic = 'p'; // FIFO pipe + } + else + { + $symbolic = 'u'; // Unknown + } + + // Owner + $symbolic .= (($perms & 0x0100) ? 'r' : '-'); + $symbolic .= (($perms & 0x0080) ? 'w' : '-'); + $symbolic .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); + + // Group + $symbolic .= (($perms & 0x0020) ? 'r' : '-'); + $symbolic .= (($perms & 0x0010) ? 'w' : '-'); + $symbolic .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); + + // World + $symbolic .= (($perms & 0x0004) ? 'r' : '-'); + $symbolic .= (($perms & 0x0002) ? 'w' : '-'); + $symbolic .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); + + return $symbolic; + } +} + +// -------------------------------------------------------------------- + +/** + * Octal Permissions + * + * Takes a numeric value representing a file's permissions and returns + * a three character string representing the file's octal permissions + * + * @access public + * @param int + * @return string + */ +if ( ! function_exists('octal_permissions')) +{ + function octal_permissions($perms) + { + return substr(sprintf('%o', $perms), -3); + } +} + + +/* End of file file_helper.php */ +/* Location: ./system/helpers/file_helper.php */ \ No newline at end of file diff --git a/api/system/helpers/form_helper.php b/api/system/helpers/form_helper.php new file mode 100644 index 0000000..8733ae0 --- /dev/null +++ b/api/system/helpers/form_helper.php @@ -0,0 +1,1054 @@ +config->site_url($action); + } + + // If no action is provided then set to the current url + $action OR $action = $CI->config->site_url($CI->uri->uri_string()); + + $form = '
config->item('csrf_protection') === TRUE AND ! (strpos($action, $CI->config->base_url()) === FALSE OR strpos($form, 'method="get"'))) + { + $hidden[$CI->security->get_csrf_token_name()] = $CI->security->get_csrf_hash(); + } + + if (is_array($hidden) AND count($hidden) > 0) + { + $form .= sprintf("
%s
", form_hidden($hidden)); + } + + return $form; + } +} + +// ------------------------------------------------------------------------ + +/** + * Form Declaration - Multipart type + * + * Creates the opening portion of the form, but with "multipart/form-data". + * + * @access public + * @param string the URI segments of the form destination + * @param array a key/value pair of attributes + * @param array a key/value pair hidden data + * @return string + */ +if ( ! function_exists('form_open_multipart')) +{ + function form_open_multipart($action = '', $attributes = array(), $hidden = array()) + { + if (is_string($attributes)) + { + $attributes .= ' enctype="multipart/form-data"'; + } + else + { + $attributes['enctype'] = 'multipart/form-data'; + } + + return form_open($action, $attributes, $hidden); + } +} + +// ------------------------------------------------------------------------ + +/** + * Hidden Input Field + * + * Generates hidden fields. You can pass a simple key/value string or an associative + * array with multiple values. + * + * @access public + * @param mixed + * @param string + * @return string + */ +if ( ! function_exists('form_hidden')) +{ + function form_hidden($name, $value = '', $recursing = FALSE) + { + static $form; + + if ($recursing === FALSE) + { + $form = "\n"; + } + + if (is_array($name)) + { + foreach ($name as $key => $val) + { + form_hidden($key, $val, TRUE); + } + return $form; + } + + if ( ! is_array($value)) + { + $form .= ''."\n"; + } + else + { + foreach ($value as $k => $v) + { + $k = (is_int($k)) ? '' : $k; + form_hidden($name.'['.$k.']', $v, TRUE); + } + } + + return $form; + } +} + +// ------------------------------------------------------------------------ + +/** + * Text Input Field + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_input')) +{ + function form_input($data = '', $value = '', $extra = '') + { + $defaults = array('type' => 'text', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); + + return ""; + } +} + +// ------------------------------------------------------------------------ + +/** + * Password Field + * + * Identical to the input function but adds the "password" type + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_password')) +{ + function form_password($data = '', $value = '', $extra = '') + { + if ( ! is_array($data)) + { + $data = array('name' => $data); + } + + $data['type'] = 'password'; + return form_input($data, $value, $extra); + } +} + +// ------------------------------------------------------------------------ + +/** + * Upload Field + * + * Identical to the input function but adds the "file" type + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_upload')) +{ + function form_upload($data = '', $value = '', $extra = '') + { + if ( ! is_array($data)) + { + $data = array('name' => $data); + } + + $data['type'] = 'file'; + return form_input($data, $value, $extra); + } +} + +// ------------------------------------------------------------------------ + +/** + * Textarea field + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_textarea')) +{ + function form_textarea($data = '', $value = '', $extra = '') + { + $defaults = array('name' => (( ! is_array($data)) ? $data : ''), 'cols' => '40', 'rows' => '10'); + + if ( ! is_array($data) OR ! isset($data['value'])) + { + $val = $value; + } + else + { + $val = $data['value']; + unset($data['value']); // textareas don't use the value attribute + } + + $name = (is_array($data)) ? $data['name'] : $data; + return ""; + } +} + +// ------------------------------------------------------------------------ + +/** + * Multi-select menu + * + * @access public + * @param string + * @param array + * @param mixed + * @param string + * @return type + */ +if ( ! function_exists('form_multiselect')) +{ + function form_multiselect($name = '', $options = array(), $selected = array(), $extra = '') + { + if ( ! strpos($extra, 'multiple')) + { + $extra .= ' multiple="multiple"'; + } + + return form_dropdown($name, $options, $selected, $extra); + } +} + +// -------------------------------------------------------------------- + +/** + * Drop-down Menu + * + * @access public + * @param string + * @param array + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_dropdown')) +{ + function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '') + { + if ( ! is_array($selected)) + { + $selected = array($selected); + } + + // If no selected state was submitted we will attempt to set it automatically + if (count($selected) === 0) + { + // If the form name appears in the $_POST array we have a winner! + if (isset($_POST[$name])) + { + $selected = array($_POST[$name]); + } + } + + if ($extra != '') $extra = ' '.$extra; + + $multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : ''; + + $form = ''; + + return $form; + } +} + +// ------------------------------------------------------------------------ + +/** + * Checkbox Field + * + * @access public + * @param mixed + * @param string + * @param bool + * @param string + * @return string + */ +if ( ! function_exists('form_checkbox')) +{ + function form_checkbox($data = '', $value = '', $checked = FALSE, $extra = '') + { + $defaults = array('type' => 'checkbox', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); + + if (is_array($data) AND array_key_exists('checked', $data)) + { + $checked = $data['checked']; + + if ($checked == FALSE) + { + unset($data['checked']); + } + else + { + $data['checked'] = 'checked'; + } + } + + if ($checked == TRUE) + { + $defaults['checked'] = 'checked'; + } + else + { + unset($defaults['checked']); + } + + return ""; + } +} + +// ------------------------------------------------------------------------ + +/** + * Radio Button + * + * @access public + * @param mixed + * @param string + * @param bool + * @param string + * @return string + */ +if ( ! function_exists('form_radio')) +{ + function form_radio($data = '', $value = '', $checked = FALSE, $extra = '') + { + if ( ! is_array($data)) + { + $data = array('name' => $data); + } + + $data['type'] = 'radio'; + return form_checkbox($data, $value, $checked, $extra); + } +} + +// ------------------------------------------------------------------------ + +/** + * Submit Button + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_submit')) +{ + function form_submit($data = '', $value = '', $extra = '') + { + $defaults = array('type' => 'submit', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); + + return ""; + } +} + +// ------------------------------------------------------------------------ + +/** + * Reset Button + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_reset')) +{ + function form_reset($data = '', $value = '', $extra = '') + { + $defaults = array('type' => 'reset', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value); + + return ""; + } +} + +// ------------------------------------------------------------------------ + +/** + * Form Button + * + * @access public + * @param mixed + * @param string + * @param string + * @return string + */ +if ( ! function_exists('form_button')) +{ + function form_button($data = '', $content = '', $extra = '') + { + $defaults = array('name' => (( ! is_array($data)) ? $data : ''), 'type' => 'button'); + + if ( is_array($data) AND isset($data['content'])) + { + $content = $data['content']; + unset($data['content']); // content is not an attribute + } + + return ""; + } +} + +// ------------------------------------------------------------------------ + +/** + * Form Label Tag + * + * @access public + * @param string The text to appear onscreen + * @param string The id the label applies to + * @param string Additional attributes + * @return string + */ +if ( ! function_exists('form_label')) +{ + function form_label($label_text = '', $id = '', $attributes = array()) + { + + $label = ' 0) + { + foreach ($attributes as $key => $val) + { + $label .= ' '.$key.'="'.$val.'"'; + } + } + + $label .= ">$label_text"; + + return $label; + } +} + +// ------------------------------------------------------------------------ +/** + * Fieldset Tag + * + * Used to produce
text. To close fieldset + * use form_fieldset_close() + * + * @access public + * @param string The legend text + * @param string Additional attributes + * @return string + */ +if ( ! function_exists('form_fieldset')) +{ + function form_fieldset($legend_text = '', $attributes = array()) + { + $fieldset = "".$extra; + } +} + +// ------------------------------------------------------------------------ + +/** + * Form Close Tag + * + * @access public + * @param string + * @return string + */ +if ( ! function_exists('form_close')) +{ + function form_close($extra = '') + { + return "".$extra; + } +} + +// ------------------------------------------------------------------------ + +/** + * Form Prep + * + * Formats text so that it can be safely placed in a form field in the event it has HTML tags. + * + * @access public + * @param string + * @return string + */ +if ( ! function_exists('form_prep')) +{ + function form_prep($str = '', $field_name = '') + { + static $prepped_fields = array(); + + // if the field name is an array we do this recursively + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = form_prep($val); + } + + return $str; + } + + if ($str === '') + { + return ''; + } + + // we've already prepped a field with this name + // @todo need to figure out a way to namespace this so + // that we know the *exact* field and not just one with + // the same name + if (isset($prepped_fields[$field_name])) + { + return $str; + } + + $str = htmlspecialchars($str); + + // In case htmlspecialchars misses these. + $str = str_replace(array("'", '"'), array("'", """), $str); + + if ($field_name != '') + { + $prepped_fields[$field_name] = $field_name; + } + + return $str; + } +} + +// ------------------------------------------------------------------------ + +/** + * Form Value + * + * Grabs a value from the POST array for the specified field so you can + * re-populate an input field or textarea. If Form Validation + * is active it retrieves the info from the validation class + * + * @access public + * @param string + * @return mixed + */ +if ( ! function_exists('set_value')) +{ + function set_value($field = '', $default = '') + { + if (FALSE === ($OBJ =& _get_validation_object())) + { + if ( ! isset($_POST[$field])) + { + return $default; + } + + return form_prep($_POST[$field], $field); + } + + return form_prep($OBJ->set_value($field, $default), $field); + } +} + +// ------------------------------------------------------------------------ + +/** + * Set Select + * + * Let's you set the selected value of a Search User Guide    + + + + +
+ + + +
+ +

Change Log

+ +

Version 2.1.4

+

Release Date: July 8, 2013

+ + +
    +
  • General Changes +
      +
    • Improved security in xss_clean().
    • +
    +
  • +
+ +

Bug fixes for 2.1.4:

+
    +
  • Fixed a bug (#1936) - Migrations Library method latest() had a typo when retrieving language values.
  • +
  • Fixed a bug (#2021) - Migrations Library configuration file was mistakenly using Windows style line feeds.
  • +
  • Fixed a bug (#1273) - Active Record method set_update_batch() was using the incorrect variables and would cause an error.
  • +
  • Fixed a bug (#2337) - Email Library method print_debugger() was not using htmlspecialchars() when being shown in the browser.
  • +
+ + +

Version 2.1.3

+

Release Date: October 8, 2012

+ +

Bug fixes for 2.1.3:

+
    +
  • Fixed a bug (#1543) - File-based Caching method get_metadata() used a non-existent array key to look for the TTL value.
  • +
  • Fixed a bug (#1314) - Session Library method sess_destroy() didn't destroy the userdata array.
  • +
  • Fixed a bug where the Profiler Library issued an E_WARNING error if Session userdata contains objects.
  • +
  • Fixed a bug (#1699) - Migration Library ignored the $config['migration_path'] setting.
  • +
  • Fixed a bug (#227) - Input Library allowed unconditional spoofing of HTTP clients' IP addresses through the HTTP_CLIENT_IP header.
  • +
  • Fixed a bug (#907) - Input Library ignored HTTP_X_CLUSTER_CLIENT_IP and HTTP_X_CLIENT_IP headers when checking for proxies.
  • +
  • Fixed a bug (#940) - csrf_verify() used to set the CSRF cookie while processing a POST request with no actual POST data, which resulted in validating a request that should be considered invalid.
  • +
  • Fixed a bug in the Security Library where a CSRF cookie was created even if $config['csrf_protection'] is set tot FALSE.
  • +
  • Fixed a bug (#1715) - Input Library triggered csrf_verify() on CLI requests.
  • +
+ +

Version 2.1.2

+

Release Date: June 29, 2012

+ +
    +
  • General Changes +
      +
    • Improved security in xss_clean().
    • +
    +
  • +
+ +

Version 2.1.1

+

Release Date: June 12, 2012

+ +
    +
  • General Changes +
      +
    • Fixed support for docx, xlsx files in mimes.php.
    • +
    +
  • +
  • Libraries + +
  • +
  • Helpers +
      +
    • url_title() performance and output improved. You can now use any string as the word delimiter. Backwards compatible with 'dash' or 'underscore' as words delimiters.
    • +
    +
  • +
+ +

Bug fixes for 2.1.1

+
    +
  • Fixed a bug (#697) - A wrong array key was used in the Upload library to check for mime-types.
  • +
  • Fixed a bug - form_open() compared $action against site_url() instead of base_url()
  • +
  • Fixed a bug - CI_Upload::_file_mime_type() could've failed if mime_content_type() is used for the detection and returns FALSE.
  • +
  • Fixed a bug (#538) - Windows paths were ignored when using the Image Manipulation Class to create a new file.
  • +
  • Fixed a bug - When database caching was enabled, $this->db->query() checked the cache before binding variables which resulted in cached queries never being found.
  • +
  • Fixed a bug - CSRF cookie value was allowed to be any (non-empty) string before being written to the output, making code injection a risk.
  • +
  • Fixed a bug (#726) - PDO put a 'dbname' argument in it's connection string regardless of the database platform in use, which made it impossible to use SQLite.
  • +
  • Fixed a bug - CI_DB_pdo_result::num_rows() was not returning properly value with SELECT queries, cause it was relying on PDOStatement::rowCount().
  • +
  • Fixed a bug (#1059) - CI_Image_lib::clear() was not correctly clearing all necessary object properties, namely width and height.
  • +
+ + +

Version 2.1.0

+

Release Date: November 14, 2011

+ +
    +
  • General Changes +
      +
    • Fixed a potential parameter injection flaw in the Security Library and strengthened the XSS filter for HTML5 vulnerabilites.
    • +
    • Callback validation rules can now accept parameters like any other validation rule.
    • +
    • Added html_escape() to the Common functions to escape HTML output for preventing XSS easliy.
    • +
    +
  • +
  • Helpers +
      +
    • Added increment_string() to String Helper to turn "foo" into "foo-1" or "foo-1" into "foo-2".
    • +
    • Altered form helper - made action on form_open_multipart helper function call optional. Fixes (#65)
    • +
    • url_title() will now trim extra dashes from beginning and end.
    • +
    • Improved speed of String Helper's random_string() method
    • +
    +
  • +
  • Database +
      +
    • Added a CUBRID driver to the Database driver. Thanks to the CUBRID team for supplying this patch.
    • +
    • Added a PDO driver to the Database driver.
    • +
    • Typecast limit and offset in the Database driver to integers to avoid possible injection.
    • +
    • Added additional option 'none' for the optional third argument for $this->db->like() in the Database driver. +
    • +
    • Added $this->db->insert_batch() support to the OCI8 (Oracle) driver.
    • +
    +
  • +
  • Libraries +
      +
    • Changed $this->cart->insert() in the Cart library to return the Row ID if a single item was inserted successfully.
    • +
    • Added support to set an optional parameter in your callback rules of validation using the Form Validation library.
    • +
    • Added a Migration library to assist with applying incremental updates to your database schema.
    • +
    • Driver children can be located in any package path.
    • +
    • Added is_unique to the Form Validation library.
    • +
    • Added $config['use_page_numbers'] to the Pagination library, which enables real page numbers in the URI.
    • +
    • Added TLS and SSL Encryption for SMTP.
    • +
    +
  • +
  • Core +
      +
    • Changed private functions in URI library to protected so MY_URI can override them.
    • +
    • Removed CI_CORE boolean constant from CodeIgniter.php (there are no longer different Reactor and Core versions).
    • +
    +
  • +
+ +

Bug fixes for 2.1.0

+
    +
  • Fixed #378 Robots identified as regular browsers by the User Agent class.
  • +
  • If a config class was loaded first then a library with the same name is loaded, the config would be ignored.
  • +
  • Fixed a bug (Reactor #19) where 1) the 404_override route was being ignored in some cases, and 2) auto-loaded libraries were not available to the 404_override controller when a controller existed but the requested method did not.
  • +
  • Fixed a bug (Reactor #89) where MySQL export would fail if the table had hyphens or other non alphanumeric/underscore characters.
  • +
  • Fixed a bug (#200) where MySQL queries would be malformed after calling $this->db->count_all() then $this->db->get()
  • +
  • Fixed bug #105 that stopped query errors from being logged unless database debugging was enabled
  • +
  • Fixed a bug (#160) - Removed unneeded array copy in the file cache driver.
  • +
  • Fixed a bug (#150) - field_data() now correctly returns column length.
  • +
  • Fixed a bug (#8) - load_class() now looks for core classes in APPPATH first, allowing them to be replaced.
  • +
  • Fixed a bug (#24) - ODBC database driver called incorrect parent in __construct().
  • +
  • Fixed a bug (#85) - OCI8 (Oracle) database escape_str() function did not escape correct.
  • +
  • Fixed a bug (#344) - Using schema found in Saving Session Data to a Database, system would throw error "user_data does not have a default value" when deleting then creating a session.
  • +
  • Fixed a bug (#112) - OCI8 (Oracle) driver didn't pass the configured database character set when connecting.
  • +
  • Fixed a bug (#182) - OCI8 (Oracle) driver used to re-execute the statement whenever num_rows() is called.
  • +
  • Fixed a bug (#82) - WHERE clause field names in the DB update_string() method were not escaped, resulting in failed queries in some cases.
  • +
  • Fixed a bug (#89) - Fix a variable type mismatch in DB display_error() where an array is expected, but a string could be set instead.
  • +
  • Fixed a bug (#467) - Suppress warnings generated from get_magic_quotes_gpc() (deprecated in PHP 5.4)
  • +
  • Fixed a bug (#484) - First time _csrf_set_hash() is called, hash is never set to the cookie (in Security.php).
  • +
  • Fixed a bug (#60) - Added _file_mime_type() method to the File Uploading Library in order to fix a possible MIME-type injection (also fixes bug #394).
  • +
  • Fixed a bug (#537) - Support for all wav type in browser.
  • +
  • Fixed a bug (#576) - Using ini_get() function to detect if apc is enabled or not.
  • +
  • Fixed invalid date time format in Date helper and XMLRPC library.
  • +
+ +

Version 2.0.3

+

Release Date: August 20, 2011

+ +
    +
  • Security +
      +
    • An improvement was made to the MySQL and MySQLi drivers to prevent exposing a potential vector for SQL injection on sites using multi-byte character sets in the database client connection.

      An incompatibility in PHP versions < 5.2.3 and MySQL < 5.0.7 with mysql_set_charset() creates a situation where using multi-byte character sets on these environments may potentially expose a SQL injection attack vector. Latin-1, UTF-8, and other "low ASCII" character sets are unaffected on all environments.

      If you are running or considering running a multi-byte character set for your database connection, please pay close attention to the server environment you are deploying on to ensure you are not vulnerable.

    • +
    +
  • +
  • General Changes +
      +
    • Fixed a bug where there was a misspelling within a code comment in the index.php file.
    • +
    • Added Session Class userdata to the output profiler. Additionally, added a show/hide toggle on HTTP Headers, Session Data and Config Variables.
    • +
    • Removed internal usage of the EXT constant.
    • +
    • Visual updates to the welcome_message view file and default error templates. Thanks to danijelb for the pull request.
    • +
    • Added "application/x-csv" to mimes.php.
    • +
    • Fixed a bug where Email library attachments with a "." in the name would using invalid MIME-types.
    • +
    • Callback validation rules can now accept parameters like any other validation rule.
    • +
    +
  • +
  • Helpers +
      +
    • Added an optional third parameter to heading() which allows adding html attributes to the rendered heading tag.
    • +
    • form_open() now only adds a hidden (Cross-site Reference Forgery) protection field when the form's action is internal and is set to the post method. (Reactor #165)
    • +
    • Re-worked plural() and singular() functions in the Inflector helper to support considerably more words.
    • +
    +
  • +
  • Libraries +
      +
    • Altered Session to use a longer match against the user_agent string. See upgrade notes if using database sessions.
    • +
    • Added is_unique to the Form Validation library.
    • +
    • Added $this->db->set_dbprefix() to the Database Driver.
    • +
    • Changed $this->cart->insert() in the Cart Library to return the Row ID if a single item was inserted successfully.
    • +
    • Added $this->load->get_var() to the Loader library to retrieve global vars set with $this->load->view() and $this->load->vars().
    • +
    • Changed $this->db->having() to insert quotes using escape() rather than escape_str().
    • +
    +
  • +
+ +

Bug fixes for 2.0.3

+
    +
  • Added ENVIRONMENT to reserved constants. (Reactor #196)
  • +
  • Changed server check to ensure SCRIPT_NAME is defined. (Reactor #57)
  • +
  • Removed APPPATH.'third_party' from the packages autoloader to negate needless file stats if no packages exist or if the developer does not load any other packages by default.
  • +
  • Fixed a bug (Reactor #231) where Sessions Library database table example SQL did not contain an index on last_activity. See Upgrade Notes.
  • +
  • Fixed a bug (Reactor #229) where the Sessions Library example SQL in the documentation contained incorrect SQL.
  • +
  • Fixed a bug (Core #340) where when passing in the second parameter to $this->db->select(), column names in subsequent queries would not be properly escaped.
  • +
  • Fixed issue #199 - Attributes passed as string does not include a space between it and the opening tag.
  • +
  • Fixed a bug where the method $this->cart->total_items() from Cart Library now returns the sum of the quantity of all items in the cart instead of your total count.
  • +
  • Fixed a bug where not setting 'null' when adding fields in db_forge for mysql and mysqli drivers would default to NULL instead of NOT NULL as the docs suggest.
  • +
  • Fixed a bug where using $this->db->select_max(), $this->db->select_min(), etc could throw notices. Thanks to w43l for the patch.
  • +
  • Replace checks for STDIN with php_sapi_name() == 'cli' which on the whole is more reliable. This should get parameters in crontab working.
  • +
+ +

Version 2.0.2

+

Release Date: April 7, 2011
+Hg Tag: v2.0.2

+ +
    +
  • General changes +
      +
    • The Security library was moved to the core and is now loaded automatically. Please remove your loading calls.
    • +
    • The CI_SHA class is now deprecated. All supported versions of PHP provide a sha1() function.
    • +
    • constants.php will now be loaded from the environment folder if available.
    • +
    • Added language key error logging
    • +
    • Made Environment Support optional. Comment out or delete the constant to stop environment checks.
    • +
    • Added Environment Support for Hooks.
    • +
    • Added CI_ Prefix to the Cache driver.
    • +
    • Added CLI usage documentation.
    • +
    +
  • +
  • Helpers +
      +
    • Removed the previously deprecated dohash() from the Security helper; use do_hash() instead.
    • +
    • Changed the 'plural' function so that it doesn't ruin the captalization of your string. It also take into consideration acronyms which are all caps.
    • +
    +
  • +
  • Database +
      +
    • $this->db->count_all_results() will now return an integer instead of a string.
    • +
    +
  • +
+ +

Bug fixes for 2.0.2

+
    +
  • Fixed a bug (Reactor #145) where the Output Library had parse_exec_vars set to protected.
  • +
  • Fixed a bug (Reactor #80) where is_really_writable would create an empty file when on Windows or with safe_mode enabled.
  • +
  • Fixed various bugs with User Guide.
  • +
  • Added is_cli_request() method to documentation for Input class.
  • +
  • Added form_validation_lang entries for decimal, less_than and greater_than.
  • +
  • Fixed issue #153 Escape Str Bug in MSSQL driver.
  • +
  • Fixed issue #172 Google Chrome 11 posts incorrectly when action is empty.
  • + +
+ +

Version 2.0.1

+

Release Date: March 15, 2011
+Hg Tag: v2.0.1

+ +
    +
  • General changes +
      +
    • Added $config['cookie_secure'] to the config file to allow requiring a secure (HTTPS) in order to set cookies.
    • +
    • Added the constant CI_CORE to help differentiate between Core: TRUE and Reactor: FALSE.
    • +
    • Added an ENVIRONMENT constant in index.php, which affects PHP error reporting settings, and optionally, + which configuration files are loaded (see below). Read more on the Handling Environments page.
    • +
    • Added support for environment-specific configuration files.
    • +
    +
  • +
  • Libraries +
      +
    • Added decimal, less_than and greater_than rules to the Form validation Class.
    • +
    • Input Class methods post() and get() will now return a full array if the first argument is not provided.
    • +
    • Secure cookies can now be made with the set_cookie() helper and Input Class method.
    • +
    • Added set_content_type() to Output Class to set the output Content-Type HTTP header based on a MIME Type or a config/mimes.php array key.
    • +
    • Output Class will now support method chaining.
    • +
    +
  • +
  • Helpers +
      +
    • Changed the logic for form_open() in Form helper. If no value is passed it will submit to the current URL.
    • +
    +
  • +
+ +

Bug fixes for 2.0.1

+
    +
  • CLI requests can now be run from any folder, not just when CD'ed next to index.php.
  • +
  • Fixed issue #41: Added audio/mp3 mime type to mp3.
  • +
  • Fixed a bug (Core #329) where the file caching driver referenced the incorrect cache directory.
  • +
  • Fixed a bug (Reactor #69) where the SHA1 library was named incorrectly.
  • +
+ +

Version 2.0.0

+

Release Date: January 28, 2011
+Hg Tag: v2.0.0

+ +
    +
  • General changes +
      +
    • PHP 4 support is removed. CodeIgniter now requires PHP 5.1.6.
    • +
    • Scaffolding, having been deprecated for a number of versions, has been removed.
    • +
    • Plugins have been removed, in favor of Helpers. The CAPTCHA plugin has been converted to a Helper and documented. The JavaScript calendar plugin was removed due to the ready availability of great JavaScript calendars, particularly with jQuery.
    • +
    • Added new special Library type: Drivers.
    • +
    • Added full query-string support. See the config file for details.
    • +
    • Moved the application folder outside of the system folder.
    • +
    • Moved system/cache and system/logs directories to the application directory.
    • +
    • Added routing overrides to the main index.php file, enabling the normal routing to be overridden on a per "index" file basis.
    • +
    • Added the ability to set config values (or override config values) directly from data set in the main index.php file. This allows a single application to be used with multiple front controllers, each having its own config values.
    • +
    • Added $config['directory_trigger'] to the config file so that a controller sub-directory can be specified when running _GET strings instead of URI segments.
    • +
    • Added ability to set "Package" paths - specific paths where the Loader and Config classes should try to look first for a requested file. This allows distribution of sub-applications with their own libraries, models, config files, etc. in a single "package" directory. See the Loader class documentation for more details.
    • +
    • In-development code is now hosted at BitBucket.
    • +
    • Removed the deprecated Validation Class.
    • +
    • Added CI_ Prefix to all core classes.
    • +
    • Package paths can now be set in application/config/autoload.php.
    • +
    • Upload library file_name can now be set without an extension, the extension will be taken from the uploaded file instead of the given name.
    • +
    • In Database Forge the name can be omitted from $this->dbforge->modify_column()'s 2nd param if you aren't changing the name.
    • +
    • $config['base_url'] is now empty by default and will guess what it should be.
    • +
    • Enabled full Command Line Interface compatibility with config['uri_protocol'] = 'CLI';.
    • +
    +
  • Libraries +
      +
    • Added a Cache driver with APC, memcached, and file-based support.
    • +
    • Added $prefix, $suffix and $first_url properties to Pagination library.
    • +
    • Added the ability to suppress first, previous, next, last, and page links by setting their values to FALSE in the Pagination library.
    • +
    • Added Security library, which now contains the xss_clean function, filename_security function and other security related functions.
    • +
    • Added CSRF (Cross-site Reference Forgery) protection to the Security library.
    • +
    • Added $parse_exec_vars property to Output library.
    • +
    • Added ability to enable / disable individual sections of the Profiler
    • +
    • Added a wildcard option $config['allowed_types'] = '*' to the File Uploading Class.
    • +
    • Added an 'object' config variable to the XML-RPC Server library so that one can specify the object to look for requested methods, instead of assuming it is in the $CI superobject.
    • +
    • Added "is_object" into the list of unit tests capable of being run.
    • +
    • Table library will generate an empty cell with a blank string, or NULL value.
    • +
    • Added ability to set tag attributes for individual cells in the Table library
    • +
    • Added a parse_string() method to the Parser Class.
    • +
    • Added HTTP headers and Config information to the Profiler output.
    • +
    • Added Chrome and Flock to the list of detectable browsers by browser() in the User Agent Class.
    • +
    • The Unit Test Class now has an optional "notes" field available to it, and allows for discrete display of test result items using $this->unit->set_test_items().
    • +
    • Added a $xss_clean class variable to the XMLRPC library, enabling control over the use of the Security library's xss_clean() method.
    • +
    • Added a download() method to the FTP library
    • +
    • Changed do_xss_clean() to return FALSE if the uploaded file fails XSS checks.
    • +
    • Added stripslashes() and trim()ing of double quotes from $_FILES type value to standardize input in Upload library.
    • +
    • Added a second parameter (boolean) to $this->zip->read_dir('/path/to/directory', FALSE) to remove the preceding trail of empty folders when creating a Zip archive. This example would contain a zip with "directory" and all of its contents.
    • +
    • Added ability in the Image Library to handle PNG transparency for resize operations when using the GD lib.
    • +
    • Modified the Session class to prevent use if no encryption key is set in the config file.
    • +
    • Added a new config item to the Session class sess_expire_on_close to allow sessions to auto-expire when the browser window is closed.
    • +
    • Improved performance of the Encryption library on servers where Mcrypt is available.
    • +
    • Changed the default encryption mode in the Encryption library to CBC.
    • +
    • Added an encode_from_legacy() method to provide a way to transition encrypted data from CodeIgniter 1.x to CodeIgniter 2.x. + Please see the upgrade instructions for details.
    • +
    • Altered Form_Validation library to allow for method chaining on set_rules(), set_message() and set_error_delimiters() functions.
    • +
    • Altered Email Library to allow for method chaining.
    • +
    • Added request_headers(), get_request_header() and is_ajax_request() to the input class.
    • +
    • Altered User agent library so that is_browser(), is_mobile() and is_robot() can optionally check for a specific browser or mobile device.
    • +
    • Altered Input library so that post() and get() will return all POST and GET items (respectively) if there are no parameters passed in.
    • +
    +
  • +
  • Database +
      +
    • database configuration.
    • +
    • Added autoinit value to database configuration.
    • +
    • Added stricton value to database configuration.
    • +
    • Added database_exists() to the Database Utilities Class.
    • +
    • Semantic change to db->version() function to allow a list of exceptions for databases with functions to return version string instead of specially formed SQL queries. Currently this list only includes Oracle and SQLite.
    • +
    • Fixed a bug where driver specific table identifier protection could lead to malformed queries in the field_data() functions.
    • +
    • Fixed a bug where an undefined class variable was referenced in database drivers.
    • +
    • Modified the database errors to show the filename and line number of the problematic query.
    • +
    • Removed the following deprecated functions: orwhere, orlike, groupby, orhaving, orderby, getwhere.
    • +
    • Removed deprecated _drop_database() and _create_database() functions from the db utility drivers.
    • +
    • Improved dbforge create_table() function for the Postgres driver.
    • +
    +
  • +
  • Helpers +
      +
    • Added convert_accented_characters() function to text helper.
    • +
    • Added accept-charset to the list of inserted attributes of form_open() in the Form Helper.
    • +
    • Deprecated the dohash() function in favour of do_hash() for naming consistency.
    • +
    • Non-backwards compatible change made to get_dir_file_info() in the File Helper. No longer recurses + by default so as to encourage responsible use (this function can cause server performance issues when used without caution).
    • +
    • Modified the second parameter of directory_map() in the Directory Helper to accept an integer to specify recursion depth.
    • +
    • Modified delete_files() in the File Helper to return FALSE on failure.
    • +
    • Added an optional second parameter to byte_format() in the Number Helper to allow for decimal precision.
    • +
    • Added alpha, and sha1 string types to random_string() in the String Helper.
    • +
    • Modified prep_url() so as to not prepend http:// if the supplied string already has a scheme.
    • +
    • Modified get_file_info in the file helper, changing filectime() to filemtime() for dates.
    • +
    • Modified smiley_js() to add optional third parameter to return only the javascript with no script tags.
    • +
    • The img() function of the HTML helper will now generate an empty string as an alt attribute if one is not provided.
    • +
    • If CSRF is enabled in the application config file, form_open() will automatically insert it as a hidden field.
    • +
    • Added sanitize_filename() into the Security helper.
    • +
    • Added ellipsize() to the Text Helper
    • +
    • Added elements() to the Array Helper
    • +
    +
  • +
  • Other Changes +
      +
    • Added an optional second parameter to show_404() to disable logging.
    • +
    • Updated loader to automatically apply the sub-class prefix as an option when loading classes. Class names can be prefixed with the standard "CI_" or the same prefix as the subclass prefix, or no prefix at all.
    • +
    • Increased randomness with is_really_writable() to avoid file collisions when hundreds or thousands of requests occur at once.
    • +
    • Switched some DIR_WRITE_MODE constant uses to FILE_WRITE_MODE where files and not directories are being operated on.
    • +
    • get_mime_by_extension() is now case insensitive.
    • +
    • Added "default" to the list Reserved Names.
    • +
    • Added 'application/x-msdownload' for .exe files and ''application/x-gzip-compressed' for .tgz files to config/mimes.php.
    • +
    • Updated the output library to no longer compress output or send content-length headers if the server runs with zlib.output_compression enabled.
    • +
    • Eliminated a call to is_really_writable() on each request unless it is really needed (Output caching)
    • +
    • Documented append_output() in the Output Class.
    • +
    • Documented a second argument in the decode() function for the Encryption Class.
    • +
    • Documented db->close().
    • +
    • Updated the router to support a default route with any number of segments.
    • +
    • Moved _remove_invisible_characters() function from the Security Library to common functions.
    • +
    • Added audio/mpeg3 as a valid mime type for MP3.
    • +
    +
  • +
+ +

Bug fixes for 2.0.0

+
    +
  • Fixed a bug where you could not change the User-Agent when sending email.
  • +
  • Fixed a bug where the Output class would send incorrect cached output for controllers implementing their own _output() method.
  • +
  • Fixed a bug where a failed query would not have a saved query execution time causing errors in the Profiler
  • +
  • Fixed a bug that was writing log entries when multiple identical helpers and plugins were loaded.
  • +
  • Fixed assorted user guide typos or examples (#10693, #8951, #7825, #8660, #7883, #6771, #10656).
  • +
  • Fixed a language key in the profiler: "profiler_no_memory_usage" to "profiler_no_memory".
  • +
  • Fixed an error in the Zip library that didn't allow downloading on PHP 4 servers.
  • +
  • Fixed a bug in the Form Validation library where fields passed as rule parameters were not being translated (#9132)
  • +
  • Modified inflector helper to properly pluralize words that end in 'ch' or 'sh'
  • +
  • Fixed a bug in xss_clean() that was not allowing hyphens in query strings of submitted URLs.
  • +
  • Fixed bugs in get_dir_file_info() and get_file_info() in the File Helper with recursion, and file paths on Windows.
  • +
  • Fixed a bug where Active Record override parameter would not let you disable Active Record if it was enabled in your database config file.
  • +
  • Fixed a bug in reduce_double_slashes() in the String Helper to properly remove duplicate leading slashes (#7585)
  • +
  • Fixed a bug in values_parsing() of the XML-RPC library which prevented NULL variables typed as 'string' from being handled properly.
  • +
  • Fixed a bug were form_open_multipart() didn't accept string attribute arguments (#10930).
  • +
  • Fixed a bug (#10470) where get_mime_by_extension() was case sensitive.
  • +
  • Fixed a bug where some error messages for the SQLite and Oracle drivers would not display.
  • +
  • Fixed a bug where files created with the Zip Library would result in file creation dates of 1980.
  • +
  • Fixed a bug in the Session library that would result in PHP error when attempting to store values with objects.
  • +
  • Fixed a bug where extending the Controller class would result in a fatal PHP error.
  • +
  • Fixed a PHP Strict Standards Error in the index.php file.
  • +
  • Fixed a bug where getimagesize() was being needlessly checked on non-image files in is_allowed_type().
  • +
  • Fixed a bug in the Encryption library where an empty key was not triggering an error.
  • +
  • Fixed a bug in the Email library where CC and BCC recipients were not reset when using the clear() method (#109).
  • +
  • Fixed a bug in the URL Helper where prep_url() could cause a PHP error on PHP versions < 5.1.2.
  • +
  • Added a log message in core/output if the cache directory config value was not found.
  • +
  • Fixed a bug where multiple libraries could not be loaded by passing an array to load->library()
  • +
  • Fixed a bug in the html helper where too much white space was rendered between the src and alt tags in the img() function.
  • +
  • Fixed a bug in the profilers _compile_queries() function.
  • +
  • Fixed a bug in the date helper where the DATE_ISO8601 variable was returning an incorrectly formatted date string.
  • +
+ +

Version 1.7.2

+

Release Date: September 11, 2009
+Hg Tag: v1.7.2

+ +
    +
  • Libraries +
      +
    • Added a new Cart Class.
    • +
    • Added the ability to pass $config['file_name'] for the File Uploading Class and rename the uploaded file.
    • +
    • Changed order of listed user-agents so Safari would more accurately report itself. (#6844)
    • +
    +
  • +
  • Database +
      +
    • Switched from using gettype() in escape() to is_* methods, since future PHP versions might change its output.
    • +
    • Updated all database drivers to handle arrays in escape_str()
    • +
    • Added escape_like_str() method for escaping strings to be used in LIKE conditions
    • +
    • Updated Active Record to utilize the new LIKE escaping mechanism.
    • +
    • Added reconnect() method to DB drivers to try to keep alive / reestablish a connection after a long idle.
    • +
    • Modified MSSQL driver to use mssql_get_last_message() for error messages.
    • +
    +
  • +
  • Helpers +
      +
    • Added form_multiselect() to the Form helper.
    • +
    • Modified form_hidden() in the Form helper to accept multi-dimensional arrays.
    • +
    • Modified form_prep() in the Form helper to keep track of prepped fields to avoid multiple prep/mutation from subsequent calls which can occur when using Form Validation + and form helper functions to output form fields.
    • +
    • Modified directory_map() in the Directory helper to allow the inclusion of hidden files, and to return FALSE on failure to read directory.
    • +
    • Modified the Smiley helper to work with multiple fields and insert the smiley at the last known cursor position.
    • +
    +
  • +
  • General + +
  • +
+ +

Bug fixes for 1.7.2

+
    +
  • Fixed assorted user guide typos or examples (#6743, #7214, #7516, #7287, #7852, #8224, #8324, #8349).
  • +
  • Fixed a bug in the Form Validation library where multiple callbacks weren't working (#6110)
  • +
  • doctype helper default value was missing a "1".
  • +
  • Fixed a bug in the language class when outputting an error for an unfound file.
  • +
  • Fixed a bug in the Calendar library where the shortname was output for "May".
  • +
  • Fixed a bug with ORIG_PATH_INFO that was allowing URIs of just a slash through.
  • +
  • Fixed a fatal error in the Oracle and ODBC drivers (#6752)
  • +
  • Fixed a bug where xml_from_result() was checking for a nonexistent method.
  • +
  • Fixed a bug where Database Forge's add_column and modify_column were not looping through when sent multiple fields.
  • +
  • Fixed a bug where the File Helper was using '/' instead of the DIRECTORY_SEPARATOR constant.
  • +
  • Fixed a bug to prevent PHP errors when attempting to use sendmail on servers that have manually disabled the PHP popen() function.
  • +
  • Fixed a bug that would cause PHP errors in XML-RPC data if the PHP data type did not match the specified XML-RPC type.
  • +
  • Fixed a bug in the XML-RPC class with parsing dateTime.iso8601 data types.
  • +
  • Fixed a case sensitive string replacement in xss_clean()
  • +
  • Fixed a bug in form_textarea() where form data was not prepped correctly.
  • +
  • Fixed a bug in form_prep() causing it to not preserve entities in the user's original input when called back into a form element
  • +
  • Fixed a bug in _protect_identifiers() where the swap prefix ($swap_pre) was not being observed.
  • +
  • Fixed a bug where the 400 status header sent with the 'disallowed URI characters' was not compatible with CGI environments.
  • +
  • Fixed a bug in the typography class where heading tags could have paragraph tags inserted when using auto_typography().
  • +
+ +

Version 1.7.1

+

Release Date: February 10, 2009
+Hg Tag: 1.7.1

+ +
    +
  • Libraries +
      +
    • Fixed an arbitrary script execution security flaw (#6068) in the Form Validation library (thanks to hkk)
    • +
    • Changed default current page indicator in the Pagination library to use <strong> instead of <b>
    • +
    • A "HTTP/1.1 400 Bad Request" header is now sent when disallowed characters are encountered.
    • +
    • Added <big>, <small>, <q>, and <tt> to the Typography parser's inline elements.
    • +
    • Added more accurate error reporting for the Email library when using sendmail.
    • +
    • Removed a strict type check from the rotate() function of the Image Manipulation Class.
    • +
    • Added enhanced error checking in file saving in the Image library when using the GD lib.
    • +
    • Added an additional newline between multipart email headers and the MIME message text for better compatibility with a variety of MUAs.
    • +
    • Made modest improvements to efficiency and accuracy of explode_name() in the Image lib.
    • +
    +
  • +
  • Database +
      +
    • Added where_in to the list of expected arguments received by delete().
    • +
    +
  • +
  • Helpers +
      +
    • Added the ability to have optgroups in form_dropdown() within the form helper.
    • +
    • Added a doctype() function to the HTML helper.
    • +
    • Added ability to force lowercase for url_title() in the URL helper.
    • +
    • Changed the default "type" of form_button() to "button" from "submit" in the form helper.
    • +
    • Changed redirect() in the URL helper to allow redirections to URLs outside of the CI site.
    • +
    • Updated get_cookie() to try to fetch the cookie using the global cookie prefix if the requested cookie name doesn't exist.
    • +
    +
  • +
  • Other Changes +
      +
    • Improved security in xss_clean() to help prevent attacks targeting Internet Explorer.
    • +
    • Added 'application/msexcel' to config/mimes.php for .xls files.
    • +
    • Added 'proxy_ips' config item to whitelist reverse proxy servers from which to trust the HTTP_X_FORWARDED_FOR header to + to determine the visitor's IP address.
    • +
    • Improved accuracy of Upload::is_allowed_filetype() for images (#6715)
    • +
    +
  • +
+ +

Bug fixes for 1.7.1

+
    +
  • Database +
      +
    • Fixed a bug when doing 'random' on order_by() (#5706).
    • +
    • Fixed a bug where adding a primary key through Forge could fail (#5731).
    • +
    • Fixed a bug when using DB cache on multiple databases (#5737).
    • +
    • Fixed a bug where TRUNCATE was not considered a "write" query (#6619).
    • +
    • Fixed a bug where csv_from_result() was checking for a nonexistent method.
    • +
    • Fixed a bug _protect_identifiers() where it was improperly removing all pipe symbols from items
    • +
    +
  • +
  • Fixed assorted user guide typos or examples (#5998, #6093, #6259, #6339, #6432, #6521).
  • +
  • Fixed a bug in the MySQLi driver when no port is specified
  • +
  • Fixed a bug (#5702), in which the field label was not being fetched properly, when "matching" one field to another.
  • +
  • Fixed a bug in which identifers were not being escaped properly when reserved characters were used.
  • +
  • Fixed a bug with the regular expression used to protect submitted paragraph tags in auto typography.
  • +
  • Fixed a bug where double dashes within tag attributes were being converted to em dash entities.
  • +
  • Fixed a bug where double spaces within tag attributes were being converted to non-breaking space entities.
  • +
  • Fixed some accuracy issues with curly quotes in Typography::format_characters()
  • +
  • Changed a few docblock comments to reflect actual return values.
  • +
  • Fixed a bug with high ascii characters in subject and from email headers.
  • +
  • Fixed a bug in xss_clean() where whitespace following a validated character entity would not be preserved.
  • +
  • Fixed a bug where HTML comments and <pre> tags were being parsed in Typography::auto_typography().
  • +
  • Fixed a bug with non-breaking space cleanup in Typography::auto_typography().
  • +
  • Fixed a bug in database escaping where a compound statement (ie: SUM()) wasn't handled correctly with database prefixes.
  • +
  • Fixed a bug when an opening quote is preceded by a paragraph tag and immediately followed by another tag.
  • +
  • Fixed a bug in the Text Helper affecting some locales where word_censor() would not work on words beginning or ending with an accented character.
  • +
  • Fixed a bug in the Text Helper character limiter where the provided limit intersects the last word of the string.
  • +
  • Fixed a bug (#6342) with plural() in the Inflection helper with words ending in "y".
  • +
  • Fixed bug (#6517) where Routed URI segments returned by URI::rsegment() method were incorrect for the default controller.
  • +
  • Fixed a bug (#6706) in the Security Helper where xss_clean() was using a deprecated second argument.
  • +
  • Fixed a bug in the URL helper url_title() function where trailing periods were allowed at the end of a URL.
  • +
  • Fixed a bug (#6669) in the Email class when CRLF's are used for the newline character with headers when used with the "mail" protocol.
  • +
  • Fixed a bug (#6500) where URI::A_filter_uri() was exit()ing an error instead of using show_error().
  • +
  • Fixed a bug (#6592) in the File Helper where get_dir_file_info() where recursion was not occurring properly.
  • +
  • Tweaked Typography::auto_typography() for some edge-cases.
  • +
+ + +

Version 1.7

+

Release Date: October 23, 2008
+Hg Tag: 1.7.0

+ +
    +
  • Libraries +
      +
    • Added a new Form Validation Class. It simplifies setting rules and field names, supports arrays as field names, allows groups of validation rules to be saved in a config file, and adds some helper functions for use in view files. Please note that the old Validation class is now deprecated. We will leave it in the library folder for some time so that existing applications that use it will not break, but you are encouraged to migrate to the new version.
    • +
    • Updated the Sessions class so that any custom data being saved gets stored to a database rather than the session cookie (assuming you are using a database to store session data), permitting much more data to be saved.
    • +
    • Added the ability to store libraries in subdirectories within either the main "libraries" or the local application "libraries" folder. Please see the Loader class for more info.
    • +
    • Added the ability to assign library objects to your own variable names when you use $this->load->library(). Please see the Loader class for more info.
    • +
    • Added controller class/method info to Profiler class and support for multiple database connections.
    • +
    • Improved the "auto typography" feature and moved it out of the helper into its own Typography Class.
    • +
    • Improved performance and accuracy of xss_clean(), including reduction of false positives on image/file tests.
    • +
    • Improved Parser class to allow multiple calls to the parse() function. The output of each is appended in the output.
    • +
    • Added max_filename option to set a file name length limit in the File Upload Class.
    • +
    • Added set_status_header() function to Output class.
    • +
    • Modified Pagination class to only output the "First" link when the link for page one would not be shown.
    • +
    • Added support for mb_strlen in the Form Validation class so that multi-byte languages will calculate string lengths properly.
    • +
    +
  • +
  • Database +
      +
    • Improved Active Record class to allow full path column and table names: hostname.database.table.column. Also improved the alias handling.
    • +
    • Improved how table and column names are escaped and prefixed. It now honors full path names when adding prefixes and escaping.
    • +
    • Added Active Record caching feature to "update" and "delete" functions.
    • +
    • Added removal of non-printing control characters in escape_str() of DB drivers that do not have native PHP escaping mechanisms (mssql, oci8, odbc), to avoid potential SQL errors, and possible sources of SQL injection.
    • +
    • Added port support to MySQL, MySQLi, and MS SQL database drivers.
    • +
    • Added driver name variable in each DB driver, based on bug report #4436.
    • +
    +
  • +
  • Helpers +
      +
    • Added several new "setting" functions to the Form helper that allow POST data to be retrieved and set into forms. These are intended to be used on their own, or with the new Form Validation Class.
    • +
    • Added current_url() and uri_segments() to URL helper.
    • +
    • Altered auto_link() in the URL helper so that email addresses with "+" included will be linked.
    • +
    • Added meta() function to HTML helper.
    • +
    • Improved accuracy of calculations in Number helper.
    • +
    • Removed added newlines ("\n") from most form and html helper functions.
    • +
    • Tightened up validation in the Date helper function human_to_unix(), and eliminated the POSIX regex.
    • +
    • Updated Date helper to match the world's current time zones and offsets.
    • +
    • Modified url_title() in the URL helper to remove characters and digits that are part of + character entities, to allow dashes, underscores, and periods regardless of the $separator, and to allow uppercase characters.
    • +
    • Added support for arbitrary attributes in anchor_popup() of the URL helper.
    • +
    +
  • +
  • Other Changes +
      +
    • Added PHP Style Guide to docs.
    • +
    • Added sanitization in xss_clean() for a deprecated HTML tag that could be abused in user input in Internet Explorer.
    • +
    • Added a few openxml document mime types, and an additional mobile agent to mimes.php and user_agents.php respectively.
    • +
    • Added a file lock check during caching, before trying to write to the file.
    • +
    • Modified Cookie key cleaning to unset a few troublesome key names that can be present in certain environments, preventing CI from halting execution.
    • +
    • Changed the output of the profiler to use style attribute rather than clear, and added the id "codeigniter_profiler" to the container div.
    • +
    +
  • +
+ +

Bug fixes for 1.7.0

+
    +
  • Fixed bug in xss_clean() that could remove some desirable tag attributes.
  • +
  • Fixed assorted user guide typos or examples (#4807, #4812, #4840, #4862, #4864, #4899, #4930, #5006, #5071, #5158, #5229, #5254, #5351).
  • +
  • Fixed an edit from 1.6.3 that made the $robots array in user_agents.php go poof.
  • +
  • Fixed a bug in the Email library with quoted-printable encoding improperly encoding space and tab characters.
  • +
  • Modified XSS sanitization to no longer add semicolons after &[single letter], such as in M&M's, B&B, etc.
  • +
  • Modified XSS sanitization to no longer strip XHTML image tags of closing slashes.
  • +
  • Fixed a bug in the Session class when database sessions are used where upon session update all userdata would be errantly written to the session cookie.
  • +
  • Fixed a bug (#4536) in backups with the MySQL driver where some legacy code was causing certain characters to be double escaped.
  • +
  • Fixed a routing bug (#4661) that occurred when the default route pointed to a subfolder.
  • +
  • Fixed the spelling of "Dhaka" in the timezone_menu() function of the Date helper.
  • +
  • Fixed the spelling of "raspberry" in config/smileys.php.
  • +
  • Fixed incorrect parenthesis in form_open() function (#5135).
  • +
  • Fixed a bug that was ignoring case when comparing controller methods (#4560).
  • +
  • Fixed a bug (#4615) that was not setting SMTP authorization settings when using the initialize function.
  • +
  • Fixed a bug in highlight_code() in the Text helper that would leave a stray </span> in certain cases.
  • +
  • Fixed Oracle bug (#3306) that was preventing multiple queries in one action.
  • +
  • Fixed ODBC bug that was ignoring connection params due to its use of a constructor.
  • +
  • Fixed a DB driver bug with num_rows() that would cause an error with the Oracle driver.
  • +
  • Fixed MS SQL bug (#4915). Added brackets around database name in MS SQL driver when selecting the database, in the event that reserved characters are used in the name.
  • +
  • Fixed a DB caching bug (4718) in which the path was incorrect when no URI segments were present.
  • +
  • Fixed Image_lib class bug #4562. A path was not defined for NetPBM.
  • +
  • Fixed Image_lib class bug #4532. When cropping an image with identical height/width settings on output, a copy is made.
  • +
  • Fixed DB_driver bug (4900), in which a database error was not being logged correctly.
  • +
  • Fixed DB backup bug in which field names were not being escaped.
  • +
  • Fixed a DB Active Record caching bug in which multiple calls to cached data were not being honored.
  • +
  • Fixed a bug in the Session class that was disallowing slashes in the serialized array.
  • +
  • Fixed a Form Validation bug in which the "isset" error message was being trigged by the "required" rule.
  • +
  • Fixed a spelling error in a Loader error message.
  • +
  • Fixed a bug (5050) with IP validation with empty segments.
  • +
  • Fixed a bug in which the parser was being greedy if multiple identical sets of tags were encountered.
  • +
+ +

Version 1.6.3

+

Release Date: June 26, 2008
+Hg Tag: v1.6.3

+ +

Version 1.6.3 is a security and maintenance release and is recommended for all users.

+
    +
  • Database +
      +
    • Modified MySQL/MySQLi Forge class to give explicit names to keys
    • +
    • Added ability to set multiple column non-primary keys to the Forge class
    • +
    • Added ability to set additional database config values in DSN connections via the query string.
    • +
    +
  • +
  • Libraries +
      +
    • Set the mime type check in the Upload class to reference the global mimes variable.
    • +
    • Added support for query strings to the Pagination class, automatically detected or explicitly declared.
    • +
    • Added get_post() to the Input class.
    • +
    • Documented get() in the Input class.
    • +
    • Added the ability to automatically output language items as form labels in the Language class.
    • +
    +
  • +
  • Helpers + +
  • +
  • Other changes +
      +
    • Improved security in xss_clean().
    • +
    • Removed an unused Router reference in _display_cache().
    • +
    • Added ability to use xss_clean() to test images for XSS, useful for upload security.
    • +
    • Considerably expanded list of mobile user-agents in config/user_agents.php.
    • +
    • Charset information in the userguide has been moved above title for internationalization purposes (#4614).
    • +
    • Added "Using Associative Arrays In a Request Parameter" example to the XMLRPC userguide page.
    • +
    • Removed maxlength and size as automatically added attributes of form_input() in the form helper.
    • +
    • Documented the language file use of byte_format() in the number helper.
    • +
    +
  • +
+ + +

Bug fixes for 1.6.3

+ +
    +
  • Added a language key for valid_emails in validation_lang.php.
  • +
  • Amended fixes for bug (#3419) with parsing DSN database connections.
  • +
  • Moved the _has_operators() function (#4535) into DB_driver from DB_active_rec.
  • +
  • Fixed a syntax error in upload_lang.php.
  • +
  • Fixed a bug (#4542) with a regular expression in the Image library.
  • +
  • Fixed a bug (#4561) where orhaving() wasn't properly passing values.
  • +
  • Removed some unused variables from the code (#4563).
  • +
  • Fixed a bug where having() was not adding an = into the statement (#4568).
  • +
  • Fixed assorted user guide typos or examples (#4574, #4706).
  • +
  • Added quoted-printable headers to Email class when the multi-part override is used.
  • +
  • Fixed a double opening <p> tag in the index pages of each system directory.
  • +
+ +

Version 1.6.2

+

Release Date: May 13, 2008
+Hg Tag: 1.6.2

+
    +
  • Active Record +
      +
    • Added the ability to prevent escaping in having() clauses.
    • +
    • Added rename_table() into DBForge.
    • +
    • Fixed a bug that wasn't allowing escaping to be turned off if the value of a query was NULL.
    • +
    • DB Forge is now assigned to any models that exist after loading (#3457).
    • +
    +
  • +
  • Database +
      +
    • Added Strict Mode to database transactions.
    • +
    • Escape behaviour in where() clauses has changed; values in those with the "FALSE" argument are no longer escaped (ie: quoted).
    • +
    +
  • +
  • Config +
      +
    • Added 'application/vnd.ms-powerpoint' to list of mime types.
    • +
    • Added 'audio/mpg' to list of mime types.
    • +
    • Added new user-modifiable file constants.php containing file mode and fopen constants.
    • +
    • Added the ability to set CRLF settings via config in the Email class.
    • +
    +
  • +
  • Libraries +
      +
    • Added increased security for filename handling in the Upload library.
    • +
    • Added increased security for sessions for client-side data tampering.
    • +
    • The MySQLi forge class is now in sync with MySQL forge.
    • +
    • Added the ability to set CRLF settings via config in the Email class.
    • +
    • Unit Testing results are now colour coded, and a change was made to the default template of results.
    • +
    • Added a valid_emails rule to the Validation class.
    • +
    • The Zip class now exits within download().
    • +
    • The Zip class has undergone a substantial re-write for speed and clarity (thanks stanleyxu for the hard work and code contribution in bug report #3425!)
    • +
    +
  • +
  • Helpers +
      +
    • Added a Compatibility Helper for using some common PHP 5 functions safely in applications that might run on PHP 4 servers (thanks Seppo for the hard work and code contribution!)
    • +
    • Added form_button() in the Form helper.
    • +
    • Changed the radio() and checkbox() functions to default to not checked by default.
    • +
    • Added the ability to include an optional HTTP Response Code in the redirect() function of the URL Helper.
    • +
    • Modified img() in the HTML Helper to remove an unneeded space (#4208).
    • +
    • Modified anchor() in the URL helper to no longer add a default title= attribute (#4209).
    • +
    • The Download helper now exits within force_download().
    • +
    • Added get_dir_file_info(), get_file_info(), and get_mime_by_extension() to the File Helper.
    • +
    • Added symbolic_permissions() and octal_permissions() to the File helper.
    • +
    +
  • +
  • Plugins +
      +
    • Modified captcha generation to first look for the function imagecreatetruecolor, and fallback to imagecreate if it isn't available (#4226).
    • +
    +
  • +
  • Other + Changes +
      +
    • Added ability for xss_clean() to accept arrays.
    • +
    • Removed closing PHP tags from all PHP files to avoid accidental output and potential 'cannot modify headers' errors.
    • +
    • Removed "scripts" from the auto-load search path. Scripts were deprecated + in Version 1.4.1 (September 21, 2006). If you still need to use them for legacy reasons, they must now be manually loaded in each Controller.
    • +
    • Added a Reserved Names page to the userguide, and migrated reserved controller names into it.
    • +
    • Added a Common Functions page to the userguide for globally available functions.
    • +
    • Improved security and performance of xss_clean().
    • +
    +
  • +
+ +

Bugfixes for 1.6.2

+
    +
  • Fixed a bug where SET queries were not being handled as "write" queries.
  • +
  • Fixed a bug (#3191) with ORIG_PATH_INFO URI parsing.
  • +
  • Fixed a bug in DB Forge, when inserting an id field (#3456).
  • +
  • Fixed a bug in the table library that could cause identically constructed rows to be dropped (#3459).
  • +
  • Fixed DB Driver and MySQLi result driver checking for resources instead of objects (#3461).
  • +
  • Fixed an AR_caching error where it wasn't tracking table aliases (#3463).
  • +
  • Fixed a bug in AR compiling, where select statements with arguments got incorrectly escaped (#3478).
  • +
  • Fixed an incorrect documentation of $this->load->language (#3520).
  • +
  • Fixed bugs (#3523, #4350) in get_filenames() with recursion and problems with Windows when $include_path is used.
  • +
  • Fixed a bug (#4153) in the XML-RPC class preventing dateTime.iso8601 from being used.
  • +
  • Fixed an AR bug with or_where_not_in() (#4171).
  • +
  • Fixed a bug with xss_clean() that would add semicolons to GET URI variable strings.
  • +
  • Fixed a bug (#4206) in the Directory Helper where the directory resource was not being closed, and minor improvements.
  • +
  • Fixed a bug in the FTP library where delete_dir() was not working recursively (#4215).
  • +
  • Fixed a Validation bug when set_rules() is used with a non-array field name and rule (#4220).
  • +
  • Fixed a bug (#4223) where DB caching would not work for returned DB objects or multiple DB connections.
  • +
  • Fixed a bug in the Upload library that might output the same error twice (#4390).
  • +
  • Fixed an AR bug when joining with a table alias and table prefix (#4400).
  • +
  • Fixed a bug in the DB class testing the $params argument.
  • +
  • Fixed a bug in the Table library where the integer 0 in cell data would be displayed as a blank cell.
  • +
  • Fixed a bug in link_tag() of the URL helper where a key was passed instead of a value.
  • +
  • Fixed a bug in DB_result::row() that prevented it from returning individual fields with MySQL NULL values.
  • +
  • Fixed a bug where SMTP emails were not having dot transformation performed on lines that begin with a dot.
  • +
  • Fixed a bug in display_error() in the DB driver that was instantiating new Language and Exception objects, and not using the error heading.
  • +
  • Fixed a bug (#4413) where a URI containing slashes only e.g. 'http://example.com/index.php?//' would result in PHP errors
  • +
  • Fixed an array to string conversion error in the Validation library (#4425)
  • +
  • Fixed bug (#4451, #4299, #4339) where failed transactions will not rollback when debug mode is enabled.
  • +
  • Fixed a bug (#4506) with overlay_watermark() in the Image library preventing support for PNG-24s with alpha transparency
  • +
  • Fixed assorted user guide typos (#3453, #4364, #4379, #4399, #4408, #4412, #4448, #4488).
  • +
+ +

Version 1.6.1

+

Release Date: February 12, 2008
+Hg Tag: 1.6.1

+
    +
  • Active Record + +
  • +
  • Database drivers +
      +
    • Added support for setting client character set and collation for MySQLi.
    • +
    +
  • +
  • Core Changes +
      +
    • Modified xss_clean() to be more intelligent with its handling of URL encoded strings.
    • +
    • Added $_SERVER, $_FILES, $_ENV, and $_SESSION to sanitization of globals.
    • +
    • Added a Path Helper.
    • +
    • Simplified _reindex_segments() in the URI class.
    • +
    • Escaped the '-' in the default 'permitted_uri_chars' config item, to prevent errors if developers just try to add additional characters to the end of the default expression.
    • +
    • Modified method calling to controllers to show a 404 when a private or protected method is accessed via a URL.
    • +
    • Modified framework initiated 404s to log the controller and method for invalid requests.
    • +
    +
  • +
  • Helpers +
      +
    • Modified get_filenames() in the File Helper to return FALSE if the $source_dir is not readable.
    • +
    +
  • +
+ + +

Bugfixes for 1.6.1

+
    +
  • Deprecated is_numeric as a validation rule. Use of numeric and integer are preferred.
  • +
  • Fixed bug (#3379) in DBForge with SQLite for table creation.
  • +
  • Made Active Record fully database prefix aware (#3384).
  • +
  • Fixed a bug where DBForge was outputting invalid SQL in Postgres by adding brackets around the tables in FROM.
  • +
  • Changed the behaviour of Active Record's update() to make the WHERE clause optional (#3395).
  • +
  • Fixed a bug (#3396) where certain POST variables would cause a PHP warning.
  • +
  • Fixed a bug in query binding (#3402).
  • +
  • Changed order of SQL keywords in the Profiler $highlight array so OR would not be highlighted before ORDER BY.
  • +
  • Fixed a bug (#3404) where the MySQLi driver was testing if $this->conn_id was a resource instead of an object.
  • +
  • Fixed a bug (#3419) connecting to a database via a DSN string.
  • +
  • Fixed a bug (#3445) where the routed segment array was not re-indexed to begin with 1 when the default controller is used.
  • +
  • Fixed assorted user guide typos.
  • +
+ + + +

Version 1.6.0

+

Release Date: January 30, 2008

+
    +
  • DBForge +
      +
    • Added DBForge to the database tools.
    • +
    • Moved create_database() and drop_database() into DBForge.
    • +
    • Added add_field(), add_key(), create_table(), drop_table(), add_column(), drop_column(), modify_column() into DBForge.
    • +
    +
  • + +
  • Active Record +
      +
    • Added protect_identifiers() in Active Record.
    • +
    • All AR queries are backticked if appropriate to the database.
    • +
    • Added where_in(), or_where_in(), where_not_in(), or_where_not_in(), not_like() and or_not_like() to Active Record.
    • +
    • Added support for limit() into update() and delete() statements in Active Record.
    • +
    • Added empty_table() and truncate_table() to Active Record.
    • +
    • Added the ability to pass an array of tables to the delete() statement in Active Record.
    • +
    • Added count_all_results() function to Active Record.
    • +
    • Added select_max(), select_min(), select_avg() and select_sum() to Active Record.
    • +
    • Added the ability to use aliases with joins in Active Record.
    • +
    • Added a third parameter to Active Record's like() clause to control where the wildcard goes.
    • +
    • Added a third parameter to set() in Active Record that withholds escaping data.
    • +
    • Changed the behaviour of variables submitted to the where() clause with no values to auto set "IS NULL"
    • +
    +
  • + +
  • Other Database Related +
      +
    • MySQL driver now requires MySQL 4.1+
    • +
    • Added $this->DB->save_queries variable to DB driver, enabling queries to get saved or not. Previously they were always saved.
    • +
    • Added $this->db->dbprefix() to manually add database prefixes.
    • +
    • Added 'random' as an order_by() option , and removed "rand()" as a listed option as it was MySQL only.
    • +
    • Added a check for NULL fields in the MySQL database backup utility.
    • +
    • Added "constrain_by_prefix" parameter to db->list_table() function. If set to TRUE it will limit the result to only table names with the current prefix.
    • +
    • Deprecated from Active Record; getwhere() for get_where(); groupby() for group_by(); havingor() for having_or(); orderby() for order_by; orwhere() for or_where(); and orlike() for or_like().
    • +
    • Modified csv_from_result() to output CSV data more in the spirit of basic rules of RFC 4180.
    • +
    • Added 'char_set' and 'dbcollat' database configuration settings, to explicitly set the client communication properly.
    • +
    • Removed 'active_r' configuration setting and replaced with a global $active_record setting, which is more + in harmony with the global nature of the behavior (#1834).
    • +
    +
  • + +
  • Core changes +
      +
    • Added ability to load multiple views, whose content will be appended to the output in the order loaded.
    • +
    • Added the ability to auto-load Models.
    • +
    • Reorganized the URI and Routes classes for better clarity.
    • +
    • Added Compat.php to allow function overrides for older versions of PHP or PHP environments missing certain extensions / libraries
    • +
    • Added memory usage, GET, URI string data, and individual query execution time to Profiler output.
    • +
    • Deprecated Scaffolding.
    • +
    • Added is_really_writable() to Common.php to provide a cross-platform reliable method of testing file/folder writability.
    • +
    +
  • + +
  • Libraries +
      +
    • Changed the load protocol of Models to allow for extension.
    • +
    • Strengthened the Encryption library to help protect against man in the middle attacks when MCRYPT_MODE_CBC mode is used.
    • +
    • Added Flashdata variables, session_id regeneration and configurable session update times to the Session class.
    • +
    • Removed 'last_visit' from the Session class.
    • +
    • Added a language entry for valid_ip validation error.
    • +
    • Modified prep_for_form() in the Validation class to accept arrays, adding support for POST array validation (via callbacks only)
    • +
    • Added an "integer" rule into the Validation library.
    • +
    • Added valid_base64() to the Validation library.
    • +
    • Documented clear() in the Image Processing library.
    • +
    • Changed the behaviour of custom callbacks so that they no longer trigger the "required" rule.
    • +
    • Modified Upload class $_FILES error messages to be more precise.
    • +
    • Moved the safe mode and auth checks for the Email library into the constructor.
    • +
    • Modified variable names in _ci_load() method of Loader class to avoid conflicts with view variables.
    • +
    • Added a few additional mime type variations for CSV.
    • +
    • Enabled the 'system' methods for the XML-RPC Server library, except for 'system.multicall' which is still disabled.
    • +
    +
  • + +
  • Helpers & Plugins +
      +
    • Added link_tag() to the HTML helper.
    • +
    • Added img() to the HTML helper.
    • +
    • Added ability to "extend" Helpers.
    • +
    • Added an email helper into core helpers.
    • +
    • Added strip_quotes() function to string helper.
    • +
    • Added reduce_multiples() function to string helper.
    • +
    • Added quotes_to_entities() function to string helper.
    • +
    • Added form_fieldset(), form_fieldset_close(), form_label(), and form_reset() function to form helper.
    • +
    • Added support for external urls in form_open().
    • +
    • Removed support for db_backup in MySQLi due to incompatible functions.
    • +
    • Javascript Calendar plugin now uses the months and days from the calendar language file, instead of hard-coded values, internationalizing it.
    • +
    +
  • + + +
  • Documentation Changes +
      +
    • Added Writing Documentation section for the community to use in writing their own documentation.
    • +
    • Added titles to all user manual pages.
    • +
    • Added attributes into <html> of userguide for valid html.
    • +
    • Added Zip Encoding Class to the table of contents of the userguide.
    • +
    • Moved part of the userguide menu javascript to an external file.
    • +
    • Documented distinct() in Active Record.
    • +
    • Documented the timezones() function in the Date Helper.
    • +
    • Documented unset_userdata in the Session class.
    • +
    • Documented 2 config options to the Database configuration page.
    • +
    +
  • +
+ +

Bug fixes for Version 1.6.0

+ +
    +
  • Fixed a bug (#1813) preventing using $CI->db in the same application with returned database objects.
  • +
  • Fixed a bug (#1842) where the $this->uri->rsegments array would not include the 'index' method if routed to the controller without an implicit method.
  • +
  • Fixed a bug (#1872) where word_limiter() was not retaining whitespace.
  • +
  • Fixed a bug (#1890) in csv_from_result() where content that included the delimiter would break the file.
  • +
  • Fixed a bug (#2542)in the clean_email() method of the Email class to allow for non-numeric / non-sequential array keys.
  • +
  • Fixed a bug (#2545) in _html_entity_decode_callback() when 'global_xss_filtering' is enabled.
  • +
  • Fixed a bug (#2668) in the parser class where numeric data was ignored.
  • +
  • Fixed a bug (#2679) where the "previous" pagination link would get drawn on the first page.
  • +
  • Fixed a bug (#2702) in _object_to_array that broke some types of inserts and updates.
  • +
  • Fixed a bug (#2732) in the SQLite driver for PHP 4.
  • +
  • Fixed a bug (#2754) in Pagination to scan for non-positive num_links.
  • +
  • Fixed a bug (#2762) in the Session library where user agent matching would fail on user agents ending with a space.
  • +
  • Fixed a bug (#2784) $field_names[] vs $Ffield_names[] in postgres and sqlite drivers.
  • +
  • Fixed a bug (#2810) in the typography helper causing extraneous paragraph tags when string contains tags.
  • +
  • Fixed a bug (#2849) where arguments passed to a subfolder controller method would be incorrectly shifted, dropping the 3rd segment value.
  • +
  • Fixed a bug (#2858) which referenced a wrong variable in the Image class.
  • +
  • Fixed a bug (#2875)when loading plugin files as _plugin. and not _pi.
  • +
  • Fixed a bug (#2912) in get_filenames() in the File Helper where the array wasn't cleared after each call.
  • +
  • Fixed a bug (#2974) in highlight_phrase() that caused an error with slashes.
  • +
  • Fixed a bug (#3003) in the Encryption Library to support modes other than MCRYPT_MODE_ECB
  • +
  • Fixed a bug (#3015) in the User Agent library where more then 2 languages where not reported with languages().
  • +
  • Fixed a bug (#3017) in the Email library where some timezones were calculated incorrectly.
  • +
  • Fixed a bug (#3024) in which master_dim wasn't getting reset by clear() in the Image library.
  • +
  • Fixed a bug (#3156) in Text Helper highlight_code() causing PHP tags to be handled incorrectly.
  • +
  • Fixed a bug (#3166) that prevented num_rows from working in Oracle.
  • +
  • Fixed a bug (#3175) preventing certain libraries from working properly when autoloaded in PHP 4.
  • +
  • Fixed a bug (#3267) in the Typography Helper where unordered list was listed "un.
  • +
  • Fixed a bug (#3268) where the Router could leave '/' as the path.
  • +
  • Fixed a bug (#3279) where the Email class was sending the wrong Content-Transfer-Encoding for some character sets.
  • +
  • Fixed a bug (#3284) where the rsegment array would not be set properly if the requested URI contained more segments than the routed URI.
  • +
  • Removed extraneous load of $CFG in _display_cache() of the Output class (#3285).
  • +
  • Removed an extraneous call to loading models (#3286).
  • +
  • Fixed a bug (#3310) with sanitization of globals in the Input class that could unset CI's global variables.
  • +
  • Fixed a bug (#3314) which would cause the top level path to be deleted in delete_files() of the File helper.
  • +
  • Fixed a bug (#3328) where the smiley helper might return an undefined variable.
  • +
  • Fixed a bug (#3330) in the FTP class where a comparison wasn't getting made.
  • +
  • Removed an unused parameter from Profiler (#3332).
  • +
  • Fixed a bug in database driver where num_rows property wasn't getting updated.
  • +
  • Fixed a bug in the upload library when allowed_files wasn't defined.
  • +
  • Fixed a bug in word_wrap() of the Text Helper that incorrectly referenced an object.
  • +
  • Fixed a bug in Validation where valid_ip() wasn't called properly.
  • +
  • Fixed a bug in Validation where individual error messages for checkboxes wasn't supported.
  • +
  • Fixed a bug in captcha calling an invalid PHP function.
  • +
  • Fixed a bug in the cookie helper "set_cookie" function. It was not honoring the config settings.
  • +
  • Fixed a bug that was making validation callbacks required even when not set as such.
  • +
  • Fixed a bug in the XML-RPC library so if a type is specified, a more intelligent decision is made as to the default type.
  • +
  • Fixed an example of comma-separated emails in the email library documentation.
  • +
  • Fixed an example in the Calendar library for Showing Next/Previous Month Links.
  • +
  • Fixed a typo in the database language file.
  • +
  • Fixed a typo in the image language file "suppor" to "support".
  • +
  • Fixed an example for XML RPC.
  • +
  • Fixed an example of accept_charset() in the User Agent Library.
  • +
  • Fixed a typo in the docblock comments that had CodeIgniter spelled CodeIgnitor.
  • +
  • Fixed a typo in the String Helper (uniquid changed to uniqid).
  • +
  • Fixed typos in the email Language class (email_attachment_unredable, email_filed_smtp_login), and FTP Class (ftp_unable_to_remame).
  • +
  • Added a stripslashes() into the Upload Library.
  • +
  • Fixed a series of grammatical and spelling errors in the language files.
  • +
  • Fixed assorted user guide typos.
  • +
+

Version 1.5.4

+

Release Date: July 12, 2007

+
    +
  • Added custom Language files to the autoload options.
  • +
  • Added stripslashes() to the _clean_input_data() function in the Input class when magic quotes is on so that data will always be un-slashed within the framework.
  • +
  • Added array to string into the profiler.
  • +
  • Added some additional mime types in application/config/mimes.php.
  • +
  • Added filename_security() method to Input library.
  • +
  • Added some additional arguments to the Inflection helper singular() to compensate for words ending in "s". Also added a force parameter to pluralize().
  • +
  • Added $config['charset'] to the config file. Default value is 'UTF-8', used in some string handling functions.
  • +
  • Fixed MSSQL insert_id().
  • +
  • Fixed a logic error in the DB trans_status() function. It was incorrectly returning TRUE on failure and FALSE on success.
  • +
  • Fixed a bug that was allowing multiple load attempts on extended classes.
  • +
  • Fixed a bug in the bootstrap file that was incorrectly attempting to discern the full server path even when it was explicity set by the user.
  • +
  • Fixed a bug in the escape_str() function in the MySQL driver.
  • +
  • Fixed a typo in the Calendar library
  • +
  • Fixed a typo in rpcs.php library
  • +
  • Fixed a bug in the Zip library, providing PC Zip file compatibility with Mac OS X
  • +
  • Fixed a bug in router that was ignoring the scaffolding route for optimization
  • +
  • Fixed an IP validation bug.
  • +
  • Fixed a bug in display of POST keys in the Profiler output
  • +
  • Fixed a bug in display of queries with characters that would be interpreted as HTML in the Profiler output
  • +
  • Fixed a bug in display of Email class print debugger with characters that would be interpreted as HTML in the debugging output
  • +
  • Fixed a bug in the Content-Transfer-Encoding of HTML emails with the quoted-printable MIME type
  • +
  • Fixed a bug where one could unset certain PHP superglobals by setting them via GET or POST data
  • +
  • Fixed an undefined function error in the insert_id() function of the PostgreSQL driver
  • +
  • Fixed various doc typos.
  • +
  • Documented two functions from the String helper that were missing from the user guide: trim_slashes() and reduce_double_slashes().
  • +
  • Docs now validate to XHTML 1 transitional
  • +
  • Updated the XSS Filtering to take into account the IE expression() ability and improved certain deletions to prevent possible exploits
  • +
  • Modified the Router so that when Query Strings are Enabled, the controller trigger and function trigger values are sanitized for filename include security.
  • +
  • Modified the is_image() method in the Upload library to take into account Windows IE 6/7 eccentricities when dealing with MIMEs
  • +
  • Modified XSS Cleaning routine to be more performance friendly and compatible with PHP 5.2's new PCRE backtrack and recursion limits.
  • +
  • Modified the URL Helper to type cast the $title as a string in case a numeric value is supplied
  • +
  • Modified Form Helper form_dropdown() to type cast the keys and values of the options array as strings, allowing numeric values to be properly set as 'selected'
  • +
  • Deprecated the use if is_numeric() in various places since it allows periods. Due to compatibility problems with ctype_digit(), making it unreliable in some installations, the following regular expression was used instead: preg_match("/[^0-9]/", $n)
  • +
  • Deprecated: APPVER has been deprecated and replaced with CI_VERSION for clarity.
  • +
+

Version 1.5.3

+

Release Date: April 15, 2007

+
    +
  • Added array to string into the profiler
  • +
  • Code Igniter references updated to CodeIgniter
  • +
  • pMachine references updated to EllisLab
  • +
  • Fixed a bug in the repeater function of string helper.
  • +
  • Fixed a bug in ODBC driver
  • +
  • Fixed a bug in result_array() that was returning an empty array when no result is produced.
  • +
  • Fixed a bug in the redirect function of the url helper.
  • +
  • Fixed an undefined variable in Loader
  • +
  • Fixed a version bug in the Postgres driver
  • +
  • Fixed a bug in the textarea function of the form helper for use with strings
  • +
  • Fixed doc typos.
  • +
+

Version 1.5.2

+

Release Date: February 13, 2007

+
    +
  • Added subversion information to the downloads page.
  • +
  • Added support for captions in the Table Library
  • +
  • Fixed a bug in the download_helper that was causing Internet Explorer to load rather than download
  • +
  • Fixed a bug in the Active Record Join function that was not taking table prefixes into consideration.
  • +
  • Removed unescaped variables in error messages of Input and Router classes
  • +
  • Fixed a bug in the Loader that was causing errors on Libraries loaded twice. A debug message is now silently made in the log.
  • +
  • Fixed a bug in the form helper that gave textarea a value attribute
  • +
  • Fixed a bug in the Image Library that was ignoring resizing the same size image
  • +
  • Fixed some doc typos.
  • +
+ + +

Version 1.5.1

+

Release Date: November 23, 2006

+
    +
  • Added support for submitting arrays of libraries in the $this->load->library function.
  • +
  • Added support for naming custom library files in lower or uppercase.
  • +
  • Fixed a bug related to output buffering.
  • +
  • Fixed a bug in the active record class that was not resetting query data after a completed query.
  • +
  • Fixed a bug that was suppressing errors in controllers.
  • +
  • Fixed a problem that can cause a loop to occur when the config file is missing.
  • +
  • Fixed a bug that occurred when multiple models were loaded with the third parameter set to TRUE.
  • +
  • Fixed an oversight that was not unsetting globals properly in the input sanitize function.
  • +
  • Fixed some bugs in the Oracle DB driver.
  • +
  • Fixed an incorrectly named variable in the MySQLi result driver.
  • +
  • Fixed some doc typos.
  • +
+

Version 1.5.0.1

+

Release Date: October 31, 2006

+
    +
  • Fixed a problem in which duplicate attempts to load helpers and classes were not being stopped.
  • +
  • Fixed a bug in the word_wrap() helper function.
  • +
  • Fixed an invalid color Hex number in the Profiler class.
  • +
  • Fixed a corrupted image in the user guide.
  • +
+ + + +

Version 1.5.0

+

Release Date: October 30, 2006

+ +
    +
  • Added DB utility class, permitting DB backups, CVS or XML files from DB results, and various other functions.
  • +
  • Added Database Caching Class.
  • +
  • Added transaction support to the database classes.
  • +
  • Added Profiler Class which generates a report of Benchmark execution times, queries, and POST data at the bottom of your pages.
  • +
  • Added User Agent Library which allows browsers, robots, and mobile devises to be identified.
  • +
  • Added HTML Table Class , enabling tables to be generated from arrays or database results.
  • +
  • Added Zip Encoding Library.
  • +
  • Added FTP Library.
  • +
  • Added the ability to extend libraries and extend core classes, in addition to being able to replace them.
  • +
  • Added support for storing models within sub-folders.
  • +
  • Added Download Helper.
  • +
  • Added simple_query() function to the database classes
  • +
  • Added standard_date() function to the Date Helper.
  • +
  • Added $query->free_result() to database class.
  • +
  • Added $query->list_fields() function to database class
  • +
  • Added $this->db->platform() function
  • +
  • Added new File Helper: get_filenames()
  • +
  • Added new helper: Smiley Helper
  • +
  • Added support for <ul> and <ol> lists in the HTML Helper
  • +
  • Added the ability to rewrite short tags on-the-fly, converting them to standard PHP statements, for those servers that do not support short tags. This allows the cleaner syntax to be used regardless of whether it's supported by the server.
  • +
  • Added the ability to rename or relocate the "application" folder.
  • +
  • Added more thorough initialization in the upload class so that all class variables are reset.
  • +
  • Added "is_numeric" to validation, which uses the native PHP is_numeric function.
  • +
  • Improved the URI handler to make it more reliable when the $config['uri_protocol'] item is set to AUTO.
  • +
  • Moved most of the functions in the Controller class into the Loader class, allowing fewer reserved function names for controllers when running under PHP 5.
  • +
  • Updated the DB Result class to return an empty array when $query->result() doesn't produce a result.
  • +
  • Updated the input->cookie() and input->post() functions in Input Class to permit arrays contained cookies that are arrays to be run through the XSS filter.
  • +
  • Documented three functions from the Validation class that were missing from the user guide: set_select(), set_radio(), and set_checkbox().
  • +
  • Fixed a bug in the Email class related to SMTP Helo data.
  • +
  • Fixed a bug in the word wrapping helper and function in the email class.
  • +
  • Fixed a bug in the validation class.
  • +
  • Fixed a bug in the typography helper that was incorrectly wrapping block level elements in paragraph tags.
  • +
  • Fixed a problem in the form_prep() function that was double encoding entities.
  • +
  • Fixed a bug that affects some versions of PHP when output buffering is nested.
  • +
  • Fixed a bug that caused CI to stop working when the PHP magic __get() or __set() functions were used within models or controllers.
  • +
  • Fixed a pagination bug that was permitting negative values in the URL.
  • +
  • Fixed an oversight in which the Loader class was not allowed to be extended.
  • +
  • Changed _get_config() to get_config() since the function is not a private one.
  • +
  • Deprecated "init" folder. Initialization happens automatically now. Please see documentation.
  • +
  • Deprecated $this->db->field_names() USE $this->db->list_fields()
  • +
  • Deprecated the $config['log_errors'] item from the config.php file. Instead, $config['log_threshold'] can be set to "0" to turn it off.
  • +
+ + + + +

Version 1.4.1

+

Release Date: September 21, 2006

+ +
    +
  • Added a new feature that passes URI segments directly to your function calls as parameters. See the Controllers page for more info.
  • +
  • Added support for a function named _output(), which when used in your controllers will received the final rendered output from the output class. More info in the Controllers page.
  • +
  • Added several new functions in the URI Class to let you retrieve and manipulate URI segments that have been re-routed using the URI Routing feature. Previously, the URI class did not permit you to access any re-routed URI segments, but now it does.
  • +
  • Added $this->output->set_header() function, which allows you to set server headers.
  • +
  • Updated plugins, helpers, and language classes to allow your application folder to contain its own plugins, helpers, and language folders. Previously they were always treated as global for your entire installation. If your application folder contains any of these resources they will be used instead the global ones.
  • +
  • Added Inflector helper.
  • +
  • Added element() function in the array helper.
  • +
  • Added RAND() to active record orderby() function.
  • +
  • Added delete_cookie() and get_cookie() to Cookie helper, even though the input class has a cookie fetching function.
  • +
  • Added Oracle database driver (still undergoing testing so it might have some bugs).
  • +
  • Added the ability to combine pseudo-variables and php variables in the template parser class.
  • +
  • Added output compression option to the config file.
  • +
  • Removed the is_numeric test from the db->escape() function.
  • +
  • Fixed a MySQLi bug that was causing error messages not to contain proper error data.
  • +
  • Fixed a bug in the email class which was causing it to ignore explicitly set alternative headers.
  • +
  • Fixed a bug that was causing a PHP error when the Exceptions class was called within the get_config() function since it was causing problems.
  • +
  • Fixed an oversight in the cookie helper in which the config file cookie settings were not being honored.
  • +
  • Fixed an oversight in the upload class. An item mentioned in the 1.4 changelog was missing.
  • +
  • Added some code to allow email attachments to be reset when sending batches of email.
  • +
  • Deprecated the application/scripts folder. It will continue to work for legacy users, but it is recommended that you create your own +libraries or models instead. It was originally added before CI had user libraries or models, but it's not needed anymore.
  • +
  • Deprecated the $autoload['core'] item from the autoload.php file. Instead, please now use: $autoload['libraries']
  • +
  • Deprecated the following database functions: $this->db->smart_escape_str() and $this->db->fields().
  • +
+ + + +

Version 1.4.0

+

Release Date: September 17, 2006

+ +
    +
  • Added Hooks feature, enabling you to tap into and modify the inner workings of the framework without hacking the core files.
  • +
  • Added the ability to organize controller files into sub-folders. Kudos to Marco for suggesting this (and the next two) feature.
  • +
  • Added regular expressions support for routing rules.
  • +
  • Added the ability to remap function calls within your controllers.
  • +
  • Added the ability to replace core system classes with your own classes.
  • +
  • Added support for % character in URL.
  • +
  • Added the ability to supply full URLs using the anchor() helper function.
  • +
  • Added mode parameter to file_write() helper.
  • +
  • Added support for changing the port number in the Postgres driver.
  • +
  • Moved the list of "allowed URI characters" out of the Router class and into the config file.
  • +
  • Moved the MIME type array out of the Upload class and into its own file in the applications/config/ folder.
  • +
  • Updated the Upload class to allow the upload field name to be set when calling do_upload().
  • +
  • Updated the Config Library to be able to load config files silently, and to be able to assign config files to their own index (to avoid collisions if you use multiple config files).
  • +
  • Updated the URI Protocol code to allow more options so that URLs will work more reliably in different environments.
  • +
  • Updated the form_open() helper to allow the GET method to be used.
  • +
  • Updated the MySQLi execute() function with some code to help prevent lost connection errors.
  • +
  • Updated the SQLite Driver to check for object support before attempting to return results as objects. If unsupported it returns an array.
  • +
  • Updated the Models loader function to allow multiple loads of the same model.
  • +
  • Updated the MS SQL driver so that single quotes are escaped.
  • +
  • Updated the Postgres and ODBC drivers for better compatibility.
  • +
  • Removed a strtolower() call that was changing URL segments to lower case.
  • +
  • Removed some references that were interfering with PHP 4.4.1 compatibility.
  • +
  • Removed backticks from Postgres class since these are not needed.
  • +
  • Renamed display() to _display() in the Output class to make it clear that it's a private function.
  • +
  • Deprecated the hash() function due to a naming conflict with a native PHP function with the same name. Please use dohash() instead.
  • +
  • Fixed an bug that was preventing the input class from unsetting GET variables.
  • +
  • Fixed a router bug that was making it too greedy when matching end segments.
  • +
  • Fixed a bug that was preventing multiple discrete database calls.
  • +
  • Fixed a bug in which loading a language file was producing a "file contains no data" message.
  • +
  • Fixed a session bug caused by the XSS Filtering feature inadvertently changing the case of certain words.
  • +
  • Fixed some missing prefixes when using the database prefix feature.
  • +
  • Fixed a typo in the Calendar class (cal_november).
  • +
  • Fixed a bug in the form_checkbox() helper.
  • +
  • Fixed a bug that was allowing the second segment of the URI to be identical to the class name.
  • +
  • Fixed an evaluation bug in the database initialization function.
  • +
  • Fixed a minor bug in one of the error messages in the language class.
  • +
  • Fixed a bug in the date helper timespan function.
  • +
  • Fixed an undefined variable in the DB Driver class.
  • +
  • Fixed a bug in which dollar signs used as binding replacement values in the DB class would be treated as RegEx back-references.
  • +
  • Fixed a bug in the set_hash() function which was preventing MD5 from being used.
  • +
  • Fixed a couple bugs in the Unit Testing class.
  • +
  • Fixed an incorrectly named variable in the Validation class.
  • +
  • Fixed an incorrectly named variable in the URI class.
  • +
  • Fixed a bug in the config class that was preventing the base URL from being called properly.
  • +
  • Fixed a bug in the validation class that was not permitting callbacks if the form field was empty.
  • +
  • Fixed a problem that was preventing scaffolding from working properly with MySQLi.
  • +
  • Fixed some MS SQL bugs.
  • +
  • Fixed some doc typos.
  • +
+ + + +

Version 1.3.3

+

Release Date: June 1, 2006

+ +
    + +
  • Models do not connect automatically to the database as of this version. More info here.
  • +
  • Updated the Sessions class to utilize the active record class when running session related queries. Previously the queries assumed MySQL syntax.
  • +
  • Updated alternator() function to re-initialize when called with no arguments, allowing multiple calls.
  • +
  • Fixed a bug in the active record "having" function.
  • +
  • Fixed a problem in the validation class which was making checkboxes be ignored when required.
  • +
  • Fixed a bug in the word_limiter() helper function. It was cutting off the fist word.
  • +
  • Fixed a bug in the xss_clean function due to a PHP bug that affects some versions of html_entity_decode.
  • +
  • Fixed a validation bug that was preventing rules from being set twice in one controller.
  • +
  • Fixed a calendar bug that was not letting it use dynamically loaded languages.
  • +
  • Fixed a bug in the active record class when using WHERE clauses with LIKE
  • +
  • Fixed a bug in the hash() security helper.
  • +
  • Fixed some typos.
  • +
+ + + + +

Version 1.3.2

+

Release Date: April 17, 2006

+ +
    +
  • Changed the behavior of the validation class such that if a "required" rule is NOT explicitly stated for a field then all other tests get ignored.
  • +
  • Fixed a bug in the Controller class that was causing it to look in the local "init" folder instead of the main system one.
  • +
  • Fixed a bug in the init_pagination file. The $config item was not being set correctly.
  • +
  • Fixed a bug in the auto typography helper that was causing inconsistent behavior.
  • +
  • Fixed a couple bugs in the Model class.
  • +
  • Fixed some documentation typos and errata.
  • +
+ + + +

Version 1.3.1

+

Release Date: April 11, 2006

+ +
    +
  • Added a Unit Testing Library.
  • +
  • Added the ability to pass objects to the insert() and update() database functions. +This feature enables you to (among other things) use your Model class variables to run queries with. See the Models page for details.
  • +
  • Added the ability to pass objects to the view loading function: $this->load->view('my_view', $object);
  • +
  • Added getwhere function to Active Record class.
  • +
  • Added count_all function to Active Record class.
  • +
  • Added language file for scaffolding and fixed a scaffolding bug that occurs when there are no rows in the specified table.
  • +
  • Added $this->db->last_query(), which allows you to view your last query that was run.
  • +
  • Added a new mime type to the upload class for better compatibility.
  • +
  • Changed how cache files are read to prevent PHP errors if the cache file contains an XML tag, which PHP wants to interpret as a short tag.
  • +
  • Fixed a bug in a couple of the active record functions (where and orderby).
  • +
  • Fixed a bug in the image library when realpath() returns false.
  • +
  • Fixed a bug in the Models that was preventing libraries from being used within them.
  • +
  • Fixed a bug in the "exact_length" function of the validation class.
  • +
  • Fixed some typos in the user guide
  • +
+ + +

Version 1.3

+

Release Date: April 3, 2006

+ +
    +
  • Added support for Models.
  • +
  • Redesigned the database libraries to support additional RDBMs (Postgres, MySQLi, etc.).
  • +
  • Redesigned the Active Record class to enable more varied types of queries with simpler syntax, and advanced features like JOINs.
  • +
  • Added a feature to the database class that lets you run custom function calls.
  • +
  • Added support for private functions in your controllers. Any controller function name that starts with an underscore will not be served by a URI request.
  • +
  • Added the ability to pass your own initialization parameters to your custom core libraries when using $this->load->library()
  • +
  • Added support for running standard query string URLs. These can be optionally enabled in your config file.
  • +
  • Added the ability to specify a "suffix", which will be appended to your URLs. For example, you could add .html to your URLs, making them appear static. This feature is enabled in your config file.
  • +
  • Added a new error template for use with native PHP errors.
  • +
  • Added "alternator" function in the string helpers.
  • +
  • Removed slashing from the input class. After much debate we decided to kill this feature.
  • +
  • Change the commenting style in the scripts to the PEAR standard so that IDEs and tools like phpDocumenter can harvest the comments.
  • +
  • Added better class and function name-spacing to avoid collisions with user developed classes. All CodeIgniter classes are now prefixed with CI_ and +all controller methods are prefixed with _ci to avoid controller collisions. A list of reserved function names can be found here.
  • +
  • Redesigned how the "CI" super object is referenced, depending on whether PHP 4 or 5 is being run, since PHP 5 allows a more graceful way to manage objects that utilizes a bit less resources.
  • +
  • Deprecated: $this->db->use_table() has been deprecated. Please read the Active Record page for information.
  • +
  • Deprecated: $this->db->smart_escape_str() has been deprecated. Please use this instead: $this->db->escape()
  • +
  • Fixed a bug in the exception handler which was preventing some PHP errors from showing up.
  • +
  • Fixed a typo in the URI class. $this->total_segment() should be plural: $this->total_segments()
  • +
  • Fixed some typos in the default calendar template
  • +
  • Fixed some typos in the user guide
  • +
+ + + + + + + + +

Version 1.2

+

Release Date: March 21, 2006

+ +
    +
  • Redesigned some internal aspects of the framework to resolve scoping problems that surfaced during the beta tests. The problem was most notable when instantiating classes in your constructors, particularly if those classes in turn did work in their constructors.
  • +
  • Added a global function named get_instance() allowing the main CodeIgniter object to be accessible throughout your own classes.
  • +
  • Added new File Helper: delete_files()
  • +
  • Added new URL Helpers: base_url(), index_page()
  • +
  • Added the ability to create your own core libraries and store them in your local application directory.
  • +
  • Added an overwrite option to the Upload class, enabling files to be overwritten rather than having the file name appended.
  • +
  • Added Javascript Calendar plugin.
  • +
  • Added search feature to user guide. Note: This is done using Google, which at the time of this writing has not crawled all the pages of the docs.
  • +
  • Updated the parser class so that it allows tag pars within other tag pairs.
  • +
  • Fixed a bug in the DB "where" function.
  • +
  • Fixed a bug that was preventing custom config files to be auto-loaded.
  • +
  • Fixed a bug in the mysql class bind feature that prevented question marks in the replacement data.
  • +
  • Fixed some bugs in the xss_clean function
  • +
+ + + + + +

Version Beta 1.1

+

Release Date: March 10, 2006

+ +
    +
  • Added a Calendaring class.
  • +
  • Added support for running multiple applications that share a common CodeIgniter backend.
  • +
  • Moved the "uri protocol" variable from the index.php file into the config.php file
  • +
  • Fixed a problem that was preventing certain function calls from working within constructors.
  • +
  • Fixed a problem that was preventing the $this->load->library function from working in constructors.
  • +
  • Fixed a bug that occurred when the session class was loaded using the auto-load routine.
  • +
  • Fixed a bug that can happen with PHP versions that do not support the E_STRICT constant
  • +
  • Fixed a data type error in the form_radio function (form helper)
  • +
  • Fixed a bug that was preventing the xss_clean function from being called from the validation class.
  • +
  • Fixed the cookie related config names, which were incorrectly specified as $conf rather than $config
  • +
  • Fixed a pagination problem in the scaffolding.
  • +
  • Fixed a bug in the mysql class "where" function.
  • +
  • Fixed a regex problem in some code that trimmed duplicate slashes.
  • +
  • Fixed a bug in the br() function in the HTML helper
  • +
  • Fixed a syntax mistake in the form_dropdown function in the Form Helper.
  • +
  • Removed the "style" attributes form the form helpers.
  • +
  • Updated the documentation. Added "next/previous" links to each page and fixed various typos.
  • +
+ +

Version Beta 1.0

+

Release Date: February 28, 2006

+

First publicly released version.

+ +
+ + + + + + + diff --git a/api/user_guide/database/active_record.html b/api/user_guide/database/active_record.html new file mode 100644 index 0000000..5a31be2 --- /dev/null +++ b/api/user_guide/database/active_record.html @@ -0,0 +1,824 @@ + + + + + +Active Record : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + +
+ +

Active Record Class

+ +

CodeIgniter uses a modified version of the Active Record Database Pattern. +This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. +In some cases only one or two lines of code are necessary to perform a database action. +CodeIgniter does not require that each database table be its own class file. It instead provides a more simplified interface.

+ +

Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax +is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

+ +

Note: If you intend to write your own queries you can disable this class in your database config file, allowing the core database library and adapter to utilize fewer resources.

+ + + +

 Selecting Data

+ +

The following functions allow you to build SQL SELECT statements.

+ +

Note: If you are using PHP 5 you can use method chaining for more compact syntax. This is described at the end of the page.

+ + +

$this->db->get();

+ +

Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:

+ +$query = $this->db->get('mytable');
+
+// Produces: SELECT * FROM mytable
+ +

The second and third parameters enable you to set a limit and offset clause:

+ +$query = $this->db->get('mytable', 10, 20);
+
+// Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
+ +

You'll notice that the above function is assigned to a variable named $query, which can be used to show the results:

+ +$query = $this->db->get('mytable');
+
+foreach ($query->result() as $row)
+{
+    echo $row->title;
+}
+ +

Please visit the result functions page for a full discussion regarding result generation.

+ + +

$this->db->get_where();

+ +

Identical to the above function except that it permits you to add a "where" clause in the second parameter, +instead of using the db->where() function:

+ +$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset); + +

Please read the about the where function below for more information.

+

Note: get_where() was formerly known as getwhere(), which has been removed

+ +

$this->db->select();

+

Permits you to write the SELECT portion of your query:

+

+$this->db->select('title, content, date');
+
+$query = $this->db->get('mytable');
+
+// Produces: SELECT title, content, date FROM mytable

+

Note: If you are selecting all (*) from a table you do not need to use this function. When omitted, CodeIgniter assumes you wish to SELECT *

+ +

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.

+

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
+$query = $this->db->get('mytable');
+

+

$this->db->select_max();

+

Writes a "SELECT MAX(field)" portion for your query. You can optionally include a second parameter to rename the resulting field.

+

+$this->db->select_max('age');
+$query = $this->db->get('members');
+ +// Produces: SELECT MAX(age) as age FROM members
+
+$this->db->select_max('age', 'member_age');
+$query = $this->db->get('members');
+// Produces: SELECT MAX(age) as member_age FROM members

+ +

$this->db->select_min();

+

Writes a "SELECT MIN(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

+

+$this->db->select_min('age');
+$query = $this->db->get('members');
+// Produces: SELECT MIN(age) as age FROM members

+ +

$this->db->select_avg();

+

Writes a "SELECT AVG(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

+

+$this->db->select_avg('age');
+$query = $this->db->get('members');
+// Produces: SELECT AVG(age) as age FROM members

+ +

$this->db->select_sum();

+

Writes a "SELECT SUM(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

+

+$this->db->select_sum('age');
+$query = $this->db->get('members');
+// Produces: SELECT SUM(age) as age FROM members

+ +

$this->db->from();

+ +

Permits you to write the FROM portion of your query:

+ + +$this->db->select('title, content, date');
+$this->db->from('mytable');
+
+$query = $this->db->get();
+
+// Produces: SELECT title, content, date FROM mytable
+ +

Note: As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method +you prefer.

+ +

$this->db->join();

+ +

Permits you to write the JOIN portion of your query:

+ + +$this->db->select('*');
+$this->db->from('blogs');
+$this->db->join('comments', 'comments.id = blogs.id');
+
+$query = $this->db->get();
+
+// Produces:
+// SELECT * FROM blogs
+// JOIN comments ON comments.id = blogs.id
+
+ +

Multiple function calls can be made if you need several joins in one query.

+ +

If you need a specific type of JOIN you can specify it via the third parameter of the function. +Options are: left, right, outer, inner, left outer, and right outer.

+ + +$this->db->join('comments', 'comments.id = blogs.id', 'left');
+
+// Produces: LEFT JOIN comments ON comments.id = blogs.id
+ + + + + +

$this->db->where();

+

This function enables you to set WHERE clauses using one of four methods:

+ +

Note: All values passed to this function are escaped automatically, producing safer queries.

+ +
    +
  1. Simple key/value method: + + $this->db->where('name', $name); +

    // Produces: WHERE name = 'Joe'
    + +

    Notice that the equal sign is added for you.

    + +

    If you use multiple function calls they will be chained together with AND between them:

    + + $this->db->where('name', $name);
    + $this->db->where('title', $title);
    + $this->db->where('status', $status); +

    // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
  2. + +
  3. Custom key/value method: + +

    You can include an operator in the first parameter in order to control the comparison:

    + + $this->db->where('name !=', $name);
    + $this->db->where('id <', $id); +

    // Produces: WHERE name != 'Joe' AND id < 45
  4. +
  5. Associative array method: + + + + $array = array('name' => $name, 'title' => $title, 'status' => $status);

    + + $this->db->where($array); +

    // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
    + +

    You can include your own operators using this method as well:

    + + + $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);

    + + $this->db->where($array);
  6. +
  7. Custom string: + +

    You can write your own clauses manually:

    + + + $where = "name='Joe' AND status='boss' OR status='active'";

    + $this->db->where($where);
  8. +
+ + +

$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.

+

$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
+

+

$this->db->or_where();

+

This function is identical to the one above, except that multiple instances are joined by OR:

+ + +$this->db->where('name !=', $name);
+$this->db->or_where('id >', $id); +
+
// Produces: WHERE name != 'Joe' OR id > 50
+ +

Note: or_where() was formerly known as orwhere(), which has been removed.

+ + +

$this->db->where_in();

+

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

+

+ $names = array('Frank', 'Todd', 'James');
+ $this->db->where_in('username', $names);
+ // Produces: WHERE username IN ('Frank', 'Todd', 'James')

+ +

$this->db->or_where_in();

+

Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate

+

+ $names = array('Frank', 'Todd', 'James');
+ $this->db->or_where_in('username', $names);
+ // Produces: OR username IN ('Frank', 'Todd', 'James')

+ +

$this->db->where_not_in();

+

Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate

+

+ $names = array('Frank', 'Todd', 'James');
+ $this->db->where_not_in('username', $names);
+ // Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')

+ +

$this->db->or_where_not_in();

+

Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate

+

+ $names = array('Frank', 'Todd', 'James');
+ $this->db->or_where_not_in('username', $names);
+ // Produces: OR username NOT IN ('Frank', 'Todd', 'James')

+ +

$this->db->like();

+

This function enables you to generate LIKE clauses, useful for doing searches.

+ +

Note: All values passed to this function are escaped automatically.

+ + +
    +
  1. Simple key/value method: + + $this->db->like('title', 'match'); +

    // Produces: WHERE title LIKE '%match%'
    + +

    If you use multiple function calls they will be chained together with AND between them:

    + + $this->db->like('title', 'match');
    + $this->db->like('body', 'match'); +

    + // WHERE title LIKE '%match%' AND body LIKE '%match%
    + If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both' (which is the default). + $this->db->like('title', 'match', 'before'); +
    + // Produces: WHERE title LIKE '%match'
    +
    + $this->db->like('title', 'match', 'after');
    +// Produces: WHERE title LIKE 'match%'
    +
    + $this->db->like('title', 'match', 'both');
    +// Produces: WHERE title LIKE '%match%'
  2. + +If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'. + + + $this->db->like('title', 'match', 'none');
    +// Produces: WHERE title LIKE 'match' +
    + +
  3. Associative array method: + + + $array = array('title' => $match, 'page1' => $match, 'page2' => $match);

    + + $this->db->like($array); +

    // WHERE title LIKE '%match%' AND page1 LIKE '%match%' AND page2 LIKE '%match%'
  4. +
+ + +

$this->db->or_like();

+

This function is identical to the one above, except that multiple instances are joined by OR:

+ + +$this->db->like('title', 'match');
+$this->db->or_like('body', $match); +
+
// WHERE title LIKE '%match%' OR body LIKE '%match%'
+ + + + +

Note: or_like() was formerly known as orlike(), which has been removed.

+

$this->db->not_like();

+

This function is identical to like(), except that it generates NOT LIKE statements:

+ $this->db->not_like('title', 'match');
+
+// WHERE title NOT LIKE '%match%
+

$this->db->or_not_like();

+

This function is identical to not_like(), except that multiple instances are joined by OR:

+ $this->db->like('title', 'match');
+$this->db->or_not_like('body', 'match');
+
+// WHERE title LIKE '%match% OR body NOT LIKE '%match%'
+

$this->db->group_by();

+

Permits you to write the GROUP BY portion of your query:

+ +$this->db->group_by("title"); +

// Produces: GROUP BY title +
+ +

You can also pass an array of multiple values as well:

+ +$this->db->group_by(array("title", "date")); +
+
// Produces: GROUP BY title, date
+ +

Note: group_by() was formerly known as groupby(), which has been removed.

+ +

$this->db->distinct();
+

+

Adds the "DISTINCT" keyword to a query

+

$this->db->distinct();
+ $this->db->get('table');
+
+ // Produces: SELECT DISTINCT * FROM table

+

$this->db->having();

+

Permits you to write the HAVING portion of your query. There are 2 possible syntaxes, 1 argument or 2:

+ +$this->db->having('user_id = 45'); +
+// Produces: HAVING user_id = 45
+
+$this->db->having('user_id', 45);
+// Produces: HAVING user_id = 45
+
+
+ +

You can also pass an array of multiple values as well:

+ + +

$this->db->having(array('title =' => 'My Title', 'id <' => $id));
+
+ // Produces: HAVING title = 'My Title', id < 45

+

If you are using a database that CodeIgniter escapes queries for, you can prevent escaping content by passing an optional third argument, and setting it to FALSE.

+

$this->db->having('user_id', 45);
+// Produces: HAVING `user_id` = 45 in some databases such as MySQL +
+ $this->db->having('user_id', 45, FALSE);
+// Produces: HAVING user_id = 45

+

$this->db->or_having();

+

Identical to having(), only separates multiple clauses with "OR".

+

$this->db->order_by();

+

Lets you set an ORDER BY clause. The first parameter contains the name of the column you would like to order by. +The second parameter lets you set the direction of the result. Options are asc or desc, or random.

+ +$this->db->order_by("title", "desc"); +
+
// Produces: ORDER BY title DESC +
+ +

You can also pass your own string in the first parameter:

+ +$this->db->order_by('title desc, name asc'); +
+
// Produces: ORDER BY title DESC, name ASC +
+ +

Or multiple function calls can be made if you need multiple fields.

+ +

$this->db->order_by("title", "desc");
+ $this->db->order_by("name", "asc");
+
+ // Produces: ORDER BY title DESC, name ASC +

+

Note: order_by() was formerly known as orderby(), which has been removed.

+

Note: random ordering is not currently supported in Oracle or MSSQL drivers. These will default to 'ASC'.

+

$this->db->limit();

+

Lets you limit the number of rows you would like returned by the query:

+ + +$this->db->limit(10);
+
+// Produces: LIMIT 10
+ + +

The second parameter lets you set a result offset.

+ + +$this->db->limit(10, 20);
+
+// Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
+ + +

$this->db->count_all_results();

+ +

Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(), or_where(), like(), or_like(), etc. Example:

+echo $this->db->count_all_results('my_table');
+ +// Produces an integer, like 25
+
+$this->db->like('title', 'match');
+$this->db->from('my_table');
+echo $this->db->count_all_results();
+// Produces an integer, like 17
+ +

$this->db->count_all();

+ +

Permits you to determine the number of rows in a particular table. Submit the table name in the first parameter. Example:

+ +echo $this->db->count_all('my_table');
+
+// Produces an integer, like 25
+ + + +  +

Inserting Data

+ +

$this->db->insert();

+

Generates an insert string based on the data you supply, and runs the query. You can either pass an +array or an object to the function. Here is an example using an array:

+ + +$data = array(
+   'title' => 'My title' ,
+   'name' => 'My Name' ,
+   'date' => 'My date'
+);
+
+$this->db->insert('mytable', $data); +

+// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
+ +

The first parameter will contain the table name, the second is an associative array of values.

+ +

Here is an example using an object:

+ + +/*
+    class Myclass {
+        var $title = 'My Title';
+        var $content = 'My Content';
+        var $date = 'My Date';
+    }
+*/
+
+$object = new Myclass;
+
+$this->db->insert('mytable', $object); +

+// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
+ +

The first parameter will contain the table name, the second is an object.

+ +

Note: All values are escaped automatically producing safer queries.

+ +

$this->db->insert_batch();

+

Generates an insert string based on the data you supply, and runs the query. You can either pass an +array or an object to the function. Here is an example using an array:

+ + +$data = array(
+   array(
+      'title' => 'My title' ,
+      'name' => 'My Name' ,
+      'date' => 'My date'
+   ),
+   array(
+      'title' => 'Another title' ,
+      'name' => 'Another Name' ,
+      'date' => 'Another date'
+   )
+);
+
+$this->db->insert_batch('mytable', $data); +

+// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
+ +

The first parameter will contain the table name, the second is an associative array of values.

+ +

Note: All values are escaped automatically producing safer queries.

+ + + +

$this->db->set();

+

This function enables you to set values for inserts or updates.

+ +

It can be used instead of passing a data array directly to the insert or update functions:

+ +$this->db->set('name', $name); +
+$this->db->insert('mytable'); +

+// Produces: INSERT INTO mytable (name) VALUES ('{$name}')
+ +

If you use multiple function called they will be assembled properly based on whether you are doing an insert or an update:

+ +$this->db->set('name', $name);
+$this->db->set('title', $title);
+$this->db->set('status', $status);
+$this->db->insert('mytable');
+

set() will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE. To illustrate the difference, here is set() used both with and without the escape parameter.

+

$this->db->set('field', 'field+1', FALSE);
+ $this->db->insert('mytable');
+ // gives INSERT INTO mytable (field) VALUES (field+1)
+
+ $this->db->set('field', 'field+1');
+ $this->db->insert('mytable');
+ // gives INSERT INTO mytable (field) VALUES ('field+1')

+

You can also pass an associative array to this function:

+ +$array = array('name' => $name, 'title' => $title, 'status' => $status);

+ +$this->db->set($array);
+$this->db->insert('mytable'); +
+ +

Or an object:

+ + + +/*
+    class Myclass {
+        var $title = 'My Title';
+        var $content = 'My Content';
+        var $date = 'My Date';
+    }
+*/
+
+$object = new Myclass;
+
+$this->db->set($object);
+$this->db->insert('mytable'); +
+ + + +  +

Updating Data

+ +

$this->db->update();

+

Generates an update string and runs the query based on the data you supply. You can pass an +array or an object to the function. Here is an example using +an array:

+ + +$data = array(
+               'title' => $title,
+               'name' => $name,
+               'date' => $date
+            );
+
+$this->db->where('id', $id);
+$this->db->update('mytable', $data); +

+// Produces:
+// UPDATE mytable
+// SET title = '{$title}', name = '{$name}', date = '{$date}'
+// WHERE id = $id
+ +

Or you can supply an object:

+ + +/*
+    class Myclass {
+        var $title = 'My Title';
+        var $content = 'My Content';
+        var $date = 'My Date';
+    }
+*/
+
+$object = new Myclass;
+
+$this->db->where('id', $id);
+$this->db->update('mytable', $object); +
+
+// Produces:
+// UPDATE mytable
+// SET title = '{$title}', name = '{$name}', date = '{$date}'
+// WHERE id = $id
+ + + +

Note: All values are escaped automatically producing safer queries.

+ +

You'll notice the use of the $this->db->where() function, enabling you to set the WHERE clause. +You can optionally pass this information directly into the update function as a string:

+ +$this->db->update('mytable', $data, "id = 4"); + +

Or as an array:

+ +$this->db->update('mytable', $data, array('id' => $id)); + +

You may also use the $this->db->set() function described above when performing updates.

+ +

$this->db->update_batch();

+

Generates an update string based on the data you supply, and runs the query. You can either pass an +array or an object to the function. Here is an example using an array:

+ + +$data = array(
+   array(
+      'title' => 'My title' ,
+      'name' => 'My Name 2' ,
+      'date' => 'My date 2'
+   ),
+   array(
+      'title' => 'Another title' ,
+      'name' => 'Another Name 2' ,
+      'date' => 'Another date 2'
+   )
+);
+
+$this->db->update_batch('mytable', $data, 'title'); +

+// Produces:
+// UPDATE `mytable` SET `name` = CASE
+// WHEN `title` = 'My title' THEN 'My Name 2'
+// WHEN `title` = 'Another title' THEN 'Another Name 2'
+// ELSE `name` END,
+// `date` = CASE
+// WHEN `title` = 'My title' THEN 'My date 2'
+// WHEN `title` = 'Another title' THEN 'Another date 2'
+// ELSE `date` END
+// WHERE `title` IN ('My title','Another title')
+ +

The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.

+ +

Note: All values are escaped automatically producing safer queries.

+ + +  +

Deleting Data

+ + + +

$this->db->delete();

+

Generates a delete SQL string and runs the query.

+ + +$this->db->delete('mytable', array('id' => $id)); +

+// Produces:
+// DELETE FROM mytable
+// WHERE id = $id
+ +

The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing +the data to the second parameter of the function:

+ +

$this->db->where('id', $id);
+ $this->db->delete('mytable');
+
+ // Produces:
+ // DELETE FROM mytable
+ // WHERE id = $id

+

An array of table names can be passed into delete() if you would like to delete data from more than 1 table.

+

$tables = array('table1', 'table2', 'table3');
+$this->db->where('id', '5');
+$this->db->delete($tables);

+

If you want to delete all data from a table, you can use the truncate() function, or empty_table().

+

$this->db->empty_table();

+

Generates a delete SQL string and runs the query. $this->db->empty_table('mytable');
+
+// Produces
+// DELETE FROM mytable

+

$this->db->truncate();

+

Generates a truncate SQL string and runs the query.

+ $this->db->from('mytable');
+$this->db->truncate();
+// or
+$this->db->truncate('mytable');
+
+// Produce:
+// TRUNCATE mytable
+
+

Note: If the TRUNCATE command isn't available, truncate() will execute as "DELETE FROM table".

+ +

 Method Chaining

+ +

Method chaining allows you to simplify your syntax by connecting multiple functions. Consider this example:

+ + +$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
+
+$query = $this->db->get();
+ +

Note: Method chaining only works with PHP 5.

+ +

 

+ +

 Active Record Caching

+ +

While not "true" caching, Active Record enables you to save (or "cache") certain parts of your queries for reuse at a later point in your script's execution. Normally, when an Active Record call is completed, all stored information is reset for the next call. With caching, you can prevent this reset, and reuse information easily.

+ +

Cached calls are cumulative. If you make 2 cached select() calls, and then 2 uncached select() calls, this will result in 4 select() calls. There are three Caching functions available:

+ +

$this->db->start_cache()

+ +

This function must be called to begin caching. All Active Record queries of the correct type (see below for supported queries) are stored for later use.

+ +

$this->db->stop_cache()

+ +

This function can be called to stop caching.

+ +

$this->db->flush_cache()

+ +

This function deletes all items from the Active Record cache.

+ +

Here's a usage example:

+ +

$this->db->start_cache();
+$this->db->select('field1');
+$this->db->stop_cache();

+$this->db->get('tablename');
+
+//Generates: SELECT `field1` FROM (`tablename`)
+
+$this->db->select('field2');
+$this->db->get('tablename');
+
+//Generates: SELECT `field1`, `field2` FROM (`tablename`)
+
+$this->db->flush_cache();
+
+$this->db->select('field2');
+$this->db->get('tablename');
+
+//Generates: SELECT `field2` FROM (`tablename`)

+ +

Note: The following statements can be cached: select, from, join, where, like, group_by, having, order_by, set

+

 

+
+ + + + + + + diff --git a/api/user_guide/database/caching.html b/api/user_guide/database/caching.html new file mode 100644 index 0000000..771f993 --- /dev/null +++ b/api/user_guide/database/caching.html @@ -0,0 +1,220 @@ + + + + + +Database Caching Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ +

Database Caching Class

+ +

The Database Caching Class permits you to cache your queries as text files for reduced database load.

+ +

Important:  This class is initialized automatically by the database driver +when caching is enabled. Do NOT load this class manually.

+ +Also note:  Not all query result functions are available when you use caching. Please read this page carefully.

+ +

Enabling Caching

+ +

Caching is enabled in three steps:

+ +
    +
  • Create a writable directory on your server where the cache files can be stored.
  • +
  • Set the path to your cache folder in your application/config/database.php file.
  • +
  • Enable the caching feature, either globally by setting the preference in your application/config/database.php file, or manually as described below.
  • +
+ +

Once enabled, caching will happen automatically whenever a page is loaded that contains database queries.

+ + +

How Does Caching Work?

+ +

CodeIgniter's query caching system happens dynamically when your pages are viewed. +When caching is enabled, the first time a web page is loaded, the query result object will +be serialized and stored in a text file on your server. The next time the page is loaded the cache file will be used instead of +accessing your database. Your database usage can effectively be reduced to zero for any pages that have been cached.

+ +

Only read-type (SELECT) queries can be cached, since these are the only type of queries that produce a result. +Write-type (INSERT, UPDATE, etc.) queries, since they don't generate a result, will not be cached by the system.

+ +

Cache files DO NOT expire. Any queries that have been cached will remain cached until you delete them. The caching system +permits you clear caches associated with individual pages, or you can delete the entire collection of cache files. +Typically you'll want to use the housekeeping functions described below to delete cache files after certain +events take place, like when you've added new information to your database.

+ +

Will Caching Improve Your Site's Performance?

+ +

Getting a performance gain as a result of caching depends on many factors. +If you have a highly optimized database under very little load, you probably won't see a performance boost. +If your database is under heavy use you probably will see an improved response, assuming your file-system is not +overly taxed. Remember that caching simply changes how your information is retrieved, shifting it from being a database +operation to a file-system one.

+ +

In some clustered server environments, for example, caching may be detrimental since file-system operations are so intense. +On single servers in shared environments, caching will probably be beneficial. Unfortunately there is no +single answer to the question of whether you should cache your database. It really depends on your situation.

+ +

How are Cache Files Stored?

+ +

CodeIgniter places the result of EACH query into its own cache file. Sets of cache files are further organized into +sub-folders corresponding to your controller functions. To be precise, the sub-folders are named identically to the +first two segments of your URI (the controller class name and function name).

+ +

For example, let's say you have a controller called blog with a function called comments that +contains three queries. The caching system will create a cache folder +called blog+comments, into which it will write three cache files.

+ +

If you use dynamic queries that change based on information in your URI (when using pagination, for example), each instance of +the query will produce its own cache file. It's possible, therefore, to end up with many times more cache files than you have +queries.

+ + +

Managing your Cache Files

+ +

Since cache files do not expire, you'll need to build deletion routines into your application. For example, let's say you have a blog +that allows user commenting. Whenever a new comment is submitted you'll want to delete the cache files associated with the +controller function that serves up your comments. You'll find two delete functions described below that help you +clear data.

+ + +

Not All Database Functions Work with Caching

+ +

Lastly, we need to point out that the result object that is cached is a simplified version of the full result object. For that reason, +some of the query result functions are not available for use.

+ +

The following functions ARE NOT available when using a cached result object:

+ +
    +
  • num_fields()
  • +
  • field_names()
  • +
  • field_data()
  • +
  • free_result()
  • +
+ +

Also, the two database resources (result_id and conn_id) are not available when caching, since result resources only +pertain to run-time operations.

+ + +
+ +

Function Reference

+ + + +

$this->db->cache_on()  /   $this->db->cache_off()

+ +

Manually enables/disables caching. This can be useful if you want to +keep certain queries from being cached. Example:

+ + +// Turn caching on
+$this->db->cache_on();
+$query = $this->db->query("SELECT * FROM mytable");
+
+// Turn caching off for this one query
+$this->db->cache_off();
+$query = $this->db->query("SELECT * FROM members WHERE member_id = '$current_user'");
+
+// Turn caching back on
+$this->db->cache_on();
+$query = $this->db->query("SELECT * FROM another_table"); +
+ + +

$this->db->cache_delete()

+ +

Deletes the cache files associated with a particular page. This is useful if you need to clear caching after you update your database.

+ +

The caching system saves your cache files to folders that correspond to the URI of the page you are viewing. For example, if you are viewing +a page at example.com/index.php/blog/comments, the caching system will put all cache files associated with it in a folder +called blog+comments. To delete those particular cache files you will use:

+ +$this->db->cache_delete('blog', 'comments'); + +

If you do not use any parameters the current URI will be used when determining what should be cleared.

+ + +

$this->db->cache_delete_all()

+ +

Clears all existing cache files. Example:

+ +$this->db->cache_delete_all(); + + + + + + + + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/call_function.html b/api/user_guide/database/call_function.html new file mode 100644 index 0000000..35b5d3a --- /dev/null +++ b/api/user_guide/database/call_function.html @@ -0,0 +1,118 @@ + + + + + +Custom Function Calls : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ +

Custom Function Calls

+ +

$this->db->call_function();

+ +

This function enables you to call PHP database functions that are not natively included in CodeIgniter, in a platform independent manner. +For example, lets say you want to call the mysql_get_client_info() function, which is not natively supported +by CodeIgniter. You could do so like this: +

+ +$this->db->call_function('get_client_info'); + +

You must supply the name of the function, without the mysql_ prefix, in the first parameter. The prefix is added +automatically based on which database driver is currently being used. This permits you to run the same function on different database platforms. +Obviously not all function calls are identical between platforms, so there are limits to how useful this function can be in terms of portability.

+ +

Any parameters needed by the function you are calling will be added to the second parameter.

+ +$this->db->call_function('some_function', $param1, $param2, etc..); + + +

Often, you will either need to supply a database connection ID or a database result ID. The connection ID can be accessed using:

+ +$this->db->conn_id; + +

The result ID can be accessed from within your result object, like this:

+ +$query = $this->db->query("SOME QUERY");
+
+$query->result_id;
+ + + + + + + + + + + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/configuration.html b/api/user_guide/database/configuration.html new file mode 100644 index 0000000..6c3d7a1 --- /dev/null +++ b/api/user_guide/database/configuration.html @@ -0,0 +1,164 @@ + + + + + +Database Configuration : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ + +

Database Configuration

+ +

CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.). +The config file is located at application/config/database.php. You can also set database connection values for specific environments by placing database.php it the respective environment config folder.

+ +

The config settings are stored in a multi-dimensional array with this prototype:

+ +$db['default']['hostname'] = "localhost";
+$db['default']['username'] = "root";
+$db['default']['password'] = "";
+$db['default']['database'] = "database_name";
+$db['default']['dbdriver'] = "mysql";
+$db['default']['dbprefix'] = "";
+$db['default']['pconnect'] = TRUE;
+$db['default']['db_debug'] = FALSE;
+$db['default']['cache_on'] = FALSE;
+$db['default']['cachedir'] = "";
+$db['default']['char_set'] = "utf8";
+$db['default']['dbcollat'] = "utf8_general_ci";
+$db['default']['swap_pre'] = "";
+$db['default']['autoinit'] = TRUE;
+$db['default']['stricton'] = FALSE;
+ +

The reason we use a multi-dimensional array rather than a more simple one is to permit you to optionally store +multiple sets of connection values. If, for example, you run multiple environments (development, production, test, etc.) +under a single installation, you can set up a connection group for each, then switch between groups as needed. +For example, to set up a "test" environment you would do this:

+ +$db['test']['hostname'] = "localhost";
+$db['test']['username'] = "root";
+$db['test']['password'] = "";
+$db['test']['database'] = "database_name";
+$db['test']['dbdriver'] = "mysql";
+$db['test']['dbprefix'] = "";
+$db['test']['pconnect'] = TRUE;
+$db['test']['db_debug'] = FALSE;
+$db['test']['cache_on'] = FALSE;
+$db['test']['cachedir'] = "";
+$db['test']['char_set'] = "utf8";
+$db['test']['dbcollat'] = "utf8_general_ci";
+$db['test']['swap_pre'] = "";
+$db['test']['autoinit'] = TRUE;
+$db['test']['stricton'] = FALSE;
+ + +

Then, to globally tell the system to use that group you would set this variable located in the config file:

+ +$active_group = "test"; + +

Note: The name "test" is arbitrary. It can be anything you want. By default we've used the word "default" +for the primary connection, but it too can be renamed to something more relevant to your project.

+ +

Active Record

+ +

The Active Record Class is globally enabled or disabled by setting the $active_record variable in the database configuration file to TRUE/FALSE (boolean). If you are not using the active record class, setting it to FALSE will utilize fewer resources when the database classes are initialized.

+ +$active_record = TRUE; + +

Note: that some CodeIgniter classes such as Sessions require Active Records be enabled to access certain functionality.

+ +

Explanation of Values:

+ +
    +
  • hostname - The hostname of your database server. Often this is "localhost".
  • +
  • username - The username used to connect to the database.
  • +
  • password - The password used to connect to the database.
  • +
  • database - The name of the database you want to connect to.
  • +
  • dbdriver - The database type. ie: mysql, postgres, odbc, etc. Must be specified in lower case.
  • +
  • dbprefix - An optional table prefix which will added to the table name when running Active Record queries. This permits multiple CodeIgniter installations to share one database.
  • +
  • pconnect - TRUE/FALSE (boolean) - Whether to use a persistent connection.
  • +
  • db_debug - TRUE/FALSE (boolean) - Whether database errors should be displayed.
  • +
  • cache_on - TRUE/FALSE (boolean) - Whether database query caching is enabled, see also Database Caching Class.
  • +
  • cachedir - The absolute server path to your database query cache directory.
  • +
  • char_set - The character set used in communicating with the database.
  • +
  • dbcollat - The character collation used in communicating with the database.

    Note: For MySQL and MySQLi databases, this setting is only used as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 (and in table creation queries made with DB Forge). There is an incompatibility in PHP with mysql_real_escape_string() which can make your site vulnerable to SQL injection if you are using a multi-byte character set and are running versions lower than these. Sites using Latin-1 or UTF-8 database character set and collation are unaffected.

  • +
  • swap_pre - A default table prefix that should be swapped with dbprefix. This is useful for distributed applications where you might run manually written queries, and need the prefix to still be customizable by the end user.
  • +
  • autoinit - Whether or not to automatically connect to the database when the library loads. If set to false, the connection will take place prior to executing the first query.
  • +
  • stricton - TRUE/FALSE (boolean) - Whether to force "Strict Mode" connections, good for ensuring strict SQL while developing an application.
  • +
  • port - The database port number. To use this value you have to add a line to the database config array.$db['default']['port'] = 5432; +
+ +

Note: Depending on what database platform you are using (MySQL, Postgres, etc.) +not all values will be needed. For example, when using SQLite you will not need to supply a username or password, and +the database name will be the path to your database file. The information above assumes you are using MySQL.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/connecting.html b/api/user_guide/database/connecting.html new file mode 100644 index 0000000..679fb0b --- /dev/null +++ b/api/user_guide/database/connecting.html @@ -0,0 +1,188 @@ + + + + + +Connecting to your Database : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ + +

Connecting to your Database

+ +

There are two ways to connect to a database:

+ +

Automatically Connecting

+ +

The "auto connect" feature will load and instantiate the database class with every page load. +To enable "auto connecting", add the word database to the library array, as indicated in the following file:

+ +

application/config/autoload.php

+ +

Manually Connecting

+ +

If only some of your pages require database connectivity you can manually connect to your database by adding this +line of code in any function where it is needed, or in your class constructor to make the database +available globally in that class.

+ +$this->load->database(); + +

If the above function does not contain any information in the first parameter it will connect +to the group specified in your database config file. For most people, this is the preferred method of use.

+ +

Available Parameters

+ +
    +
  1. The database connection values, passed either as an array or a DSN string.
  2. +
  3. TRUE/FALSE (boolean). Whether to return the connection ID (see Connecting to Multiple Databases below).
  4. +
  5. TRUE/FALSE (boolean). Whether to enable the Active Record class. Set to TRUE by default.
  6. +
+ + +

Manually Connecting to a Database

+ +

The first parameter of this function can optionally be used to specify a particular database group +from your config file, or you can even submit connection values for a database that is not specified in your config file. +Examples:

+ +

To choose a specific group from your config file you can do this:

+ +$this->load->database('group_name'); + +

Where group_name is the name of the connection group from your config file.

+ + +

To connect manually to a desired database you can pass an array of values:

+ +$config['hostname'] = "localhost";
+$config['username'] = "myusername";
+$config['password'] = "mypassword";
+$config['database'] = "mydatabase";
+$config['dbdriver'] = "mysql";
+$config['dbprefix'] = "";
+$config['pconnect'] = FALSE;
+$config['db_debug'] = TRUE;
+$config['cache_on'] = FALSE;
+$config['cachedir'] = "";
+$config['char_set'] = "utf8";
+$config['dbcollat'] = "utf8_general_ci";
+
+$this->load->database($config);
+ +

For information on each of these values please see the configuration page.

+ +

Or you can submit your database values as a Data Source Name. DSNs must have this prototype:

+ +$dsn = 'dbdriver://username:password@hostname/database';
+
+$this->load->database($dsn);
+ +

To override default config values when connecting with a DSN string, add the config variables as a query string.

+ +$dsn = 'dbdriver://username:password@hostname/database?char_set=utf8&dbcollat=utf8_general_ci&cache_on=true&cachedir=/path/to/cache';
+
+$this->load->database($dsn);
+ +

Connecting to Multiple Databases

+ +

If you need to connect to more than one database simultaneously you can do so as follows:

+ + +$DB1 = $this->load->database('group_one', TRUE);
+$DB2 = $this->load->database('group_two', TRUE); +
+ +

Note: Change the words "group_one" and "group_two" to the specific group names you are connecting to (or +you can pass the connection values as indicated above).

+ +

By setting the second parameter to TRUE (boolean) the function will return the database object.

+ +
+

When you connect this way, you will use your object name to issue commands rather than the syntax used throughout this guide. In other words, rather than issuing commands with:

+ +

$this->db->query();
$this->db->result();
etc...

+ +

You will instead use:

+ +

$DB1->query();
$DB1->result();
etc...

+ +
+ +

Reconnecting / Keeping the Connection Alive

+ +

If the database server's idle timeout is exceeded while you're doing some heavy PHP lifting (processing an image, for instance), you should consider pinging the server by using the reconnect() method before sending further queries, which can gracefully keep the connection alive or re-establish it.

+ +$this->db->reconnect(); + +

Manually closing the Connection

+ +

While CodeIgniter intelligently takes care of closing your database connections, you can explicitly close the connection.

+ +$this->db->close(); +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/examples.html b/api/user_guide/database/examples.html new file mode 100644 index 0000000..c130e8a --- /dev/null +++ b/api/user_guide/database/examples.html @@ -0,0 +1,217 @@ + + + + + +Database Quick Start : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + + +
+ + + +
+ + + +
+ + +

Database Quick Start: Example Code

+ +

The following page contains example code showing how the database class is used. For complete details please +read the individual pages describing each function.

+ + +

Initializing the Database Class

+ +

The following code loads and initializes the database class based on your configuration settings:

+ +$this->load->database(); + +

Once loaded the class is ready to be used as described below.

+ +

Note: If all your pages require database access you can connect automatically. See the connecting page for details.

+ + +

Standard Query With Multiple Results (Object Version)

+ +$query = $this->db->query('SELECT name, title, email FROM my_table');
+
+foreach ($query->result() as $row)
+{
+    echo $row->title;
+    echo $row->name;
+    echo $row->email;
+}
+
+echo 'Total Results: ' . $query->num_rows(); +
+ +

The above result() function returns an array of objects. Example: $row->title

+ + +

Standard Query With Multiple Results (Array Version)

+ +$query = $this->db->query('SELECT name, title, email FROM my_table');
+
+foreach ($query->result_array() as $row)
+{
+    echo $row['title'];
+    echo $row['name'];
+    echo $row['email'];
+}
+ +

The above result_array() function returns an array of standard array indexes. Example: $row['title']

+ + +

Testing for Results

+ +

If you run queries that might not produce a result, you are encouraged to test for a result first +using the num_rows() function:

+ + +$query = $this->db->query("YOUR QUERY");
+
+if ($query->num_rows() > 0)
+{
+   foreach ($query->result() as $row)
+   {
+      echo $row->title;
+      echo $row->name;
+      echo $row->body;
+   }
+} +
+ + + + +

Standard Query With Single Result

+ +$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
+
+$row = $query->row();
+echo $row->name;
+
+ +

The above row() function returns an object. Example: $row->name

+ + +

Standard Query With Single Result (Array version)

+ +$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
+
+$row = $query->row_array();
+echo $row['name'];
+
+ +

The above row_array() function returns an array. Example: $row['name']

+ + +

Standard Insert

+ + +$sql = "INSERT INTO mytable (title, name)
+        VALUES (".$this->db->escape($title).", ".$this->db->escape($name).")";
+
+$this->db->query($sql);
+
+echo $this->db->affected_rows(); +
+ + + + +

Active Record Query

+ +

The Active Record Pattern gives you a simplified means of retrieving data:

+ + +$query = $this->db->get('table_name');
+
+foreach ($query->result() as $row)
+{
+    echo $row->title;
+}
+ +

The above get() function retrieves all the results from the supplied table. +The Active Record class contains a full compliment of functions +for working with data.

+ + +

Active Record Insert

+ + +$data = array(
+               'title' => $title,
+               'name' => $name,
+               'date' => $date
+            );
+
+$this->db->insert('mytable', $data); +

+// Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')
+ + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/fields.html b/api/user_guide/database/fields.html new file mode 100644 index 0000000..da38810 --- /dev/null +++ b/api/user_guide/database/fields.html @@ -0,0 +1,163 @@ + + + + + +Field Data : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + +
+ + + +
+ + + +
+ + +

Field Data

+ + +

$this->db->list_fields()

+

Returns an array containing the field names. This query can be called two ways:

+ + +

1. You can supply the table name and call it from the $this->db-> object:

+ + +$fields = $this->db->list_fields('table_name');

+ +foreach ($fields as $field)
+{
+   echo $field;
+} +
+ +

2. You can gather the field names associated with any query you run by calling the function +from your query result object:

+ + +$query = $this->db->query('SELECT * FROM some_table'); +

+ +foreach ($query->list_fields() as $field)
+{
+   echo $field;
+} +
+ + +

$this->db->field_exists()

+ +

Sometimes it's helpful to know whether a particular field exists before performing an action. +Returns a boolean TRUE/FALSE. Usage example:

+ + +if ($this->db->field_exists('field_name', 'table_name'))
+{
+   // some code...
+} +
+ +

Note: Replace field_name with the name of the column you are looking for, and replace +table_name with the name of the table you are looking for.

+ + +

$this->db->field_data()

+

Returns an array of objects containing field information.

+

Sometimes it's helpful to gather the field names or other metadata, like the column type, max length, etc.

+ + +

Note: Not all databases provide meta-data.

+ +

Usage example:

+ + +$fields = $this->db->field_data('table_name');

+ +foreach ($fields as $field)
+{
+   echo $field->name;
+   echo $field->type;
+   echo $field->max_length;
+   echo $field->primary_key;
+} +
+ +

If you have run a query already you can use the result object instead of supplying the table name:

+ + +$query = $this->db->query("YOUR QUERY");
+$fields = $query->field_data(); +
+ + +

The following data is available from this function if supported by your database:

+ +
    +
  • name - column name
  • +
  • max_length - maximum length of the column
  • +
  • primary_key - 1 if the column is a primary key
  • +
  • type - the type of the column
  • +
+ + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/forge.html b/api/user_guide/database/forge.html new file mode 100644 index 0000000..99e01fb --- /dev/null +++ b/api/user_guide/database/forge.html @@ -0,0 +1,234 @@ + + + + + +Database Forge Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ +

Database Forge Class

+ +

The Database Forge Class contains functions that help you manage your database.

+ +

Table of Contents

+ + + + +

Initializing the Forge Class

+ +

Important:  In order to initialize the Forge class, your database driver must +already be running, since the forge class relies on it.

+ +

Load the Forge Class as follows:

+ +$this->load->dbforge() + +

Once initialized you will access the functions using the $this->dbforge object:

+ +$this->dbforge->some_function() +

$this->dbforge->create_database('db_name')

+ +

Permits you to create the database specified in the first parameter. Returns TRUE/FALSE based on success or failure:

+ +if ($this->dbforge->create_database('my_db'))
+{
+    echo 'Database created!';
+}
+ + + + +

$this->dbforge->drop_database('db_name')

+ +

Permits you to drop the database specified in the first parameter. Returns TRUE/FALSE based on success or failure:

+ +if ($this->dbforge->drop_database('my_db'))
+{
+    echo 'Database deleted!';
+}
+ + +

Creating and Dropping Tables

+

There are several things you may wish to do when creating tables. Add fields, add keys to the table, alter columns. CodeIgniter provides a mechanism for this.

+

Adding fields

+

Fields are created via an associative array. Within the array you must include a 'type' key that relates to the datatype of the field. For example, INT, VARCHAR, TEXT, etc. Many datatypes (for example VARCHAR) also require a 'constraint' key.

+

$fields = array(
+                        'users' => array(
+                                                  'type' => 'VARCHAR',
+                                                  'constraint' => '100',
+                                           ),
+                 );
+
+// will translate to "users VARCHAR(100)" when the field is added.

+

Additionally, the following key/values can be used:

+
    +
  • unsigned/true : to generate "UNSIGNED" in the field definition.
  • +
  • default/value : to generate a default value in the field definition.
  • +
  • null/true : to generate "NULL" in the field definition. Without this, the field will default to "NOT NULL".
  • +
  • auto_increment/true : generates an auto_increment flag on the field. Note that the field type must be a type that supports this, such as integer.
  • +
+

$fields = array(
+                         'blog_id' => array(
+                                                  'type' => 'INT',
+                                                  'constraint' => 5,
+                                                  'unsigned' => TRUE,
+                                                  'auto_increment' => TRUE
+                                           ),
+                         'blog_title' => array(
+                                                 'type' => 'VARCHAR',
+                                                 'constraint' => '100',
+                                          ),
+                        'blog_author' => array(
+                                                 'type' =>'VARCHAR',
+                                                 'constraint' => '100',
+                                                 'default' => 'King of Town',
+                                          ),
+                        'blog_description' => array(
+                                                 'type' => 'TEXT',
+                                                 'null' => TRUE,
+                                          ),
+                );
+

+

After the fields have been defined, they can be added using $this->dbforge->add_field($fields); followed by a call to the create_table() function.

+

$this->dbforge->add_field()

+

The add fields function will accept the above array.

+

Passing strings as fields

+

If you know exactly how you want a field to be created, you can pass the string into the field definitions with add_field()

+

$this->dbforge->add_field("label varchar(100) NOT NULL DEFAULT 'default label'");

+

Note: Multiple calls to add_field() are cumulative.

+

Creating an id field

+

There is a special exception for creating id fields. A field with type id will automatically be assinged as an INT(9) auto_incrementing Primary Key.

+

$this->dbforge->add_field('id');
+ // gives id INT(9) NOT NULL AUTO_INCREMENT

+

Adding Keys

+

Generally speaking, you'll want your table to have Keys. This is accomplished with $this->dbforge->add_key('field'). An optional second parameter set to TRUE will make it a primary key. Note that add_key() must be followed by a call to create_table().

+

Multiple column non-primary keys must be sent as an array. Sample output below is for MySQL.

+

$this->dbforge->add_key('blog_id', TRUE);
+ // gives PRIMARY KEY `blog_id` (`blog_id`)
+
+ $this->dbforge->add_key('blog_id', TRUE);
+ $this->dbforge->add_key('site_id', TRUE);
+ // gives PRIMARY KEY `blog_id_site_id` (`blog_id`, `site_id`)
+
+ $this->dbforge->add_key('blog_name');
+ // gives KEY `blog_name` (`blog_name`)
+
+ $this->dbforge->add_key(array('blog_name', 'blog_label'));
+ // gives KEY `blog_name_blog_label` (`blog_name`, `blog_label`)

+

Creating a table

+

After fields and keys have been declared, you can create a new table with

+

$this->dbforge->create_table('table_name');
+// gives CREATE TABLE table_name

+

An optional second parameter set to TRUE adds an "IF NOT EXISTS" clause into the definition

+

$this->dbforge->create_table('table_name', TRUE);
+// gives CREATE TABLE IF NOT EXISTS table_name

+

Dropping a table

+

Executes a DROP TABLE sql

+

$this->dbforge->drop_table('table_name');
+ // gives DROP TABLE IF EXISTS table_name

+

Renaming a table

+

Executes a TABLE rename

+

$this->dbforge->rename_table('old_table_name', 'new_table_name');
+ // gives ALTER TABLE old_table_name RENAME TO new_table_name

+

Modifying Tables

+

$this->dbforge->add_column()

+

The add_column() function is used to modify an existing table. It accepts the same field array as above, and can be used for an unlimited number of additional fields.

+

$fields = array(
+                         'preferences' => array('type' => 'TEXT')
+);
+$this->dbforge->add_column('table_name', $fields);
+
+// gives ALTER TABLE table_name ADD preferences TEXT

+

$this->dbforge->drop_column()

+

Used to remove a column from a table.

+

$this->dbforge->drop_column('table_name', 'column_to_drop');

+

$this->dbforge->modify_column()

+

The usage of this function is identical to add_column(), except it alters an existing column rather than adding a new one. In order to change the name you can add a "name" key into the field defining array.

+

$fields = array(
+                        'old_name' => array(
+                                                         'name' => 'new_name',
+                                                         'type' => 'TEXT',
+                                                ),
+);
+$this->dbforge->modify_column('table_name', $fields);
+
+ // gives ALTER TABLE table_name CHANGE old_name new_name TEXT

+

 

+
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/helpers.html b/api/user_guide/database/helpers.html new file mode 100644 index 0000000..02d08ef --- /dev/null +++ b/api/user_guide/database/helpers.html @@ -0,0 +1,151 @@ + + + + + +Query Helper Functions : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + + +
+ + + +
+ + +

Query Helper Functions

+ + +

$this->db->insert_id()

+

The insert ID number when performing database inserts.

+ +

$this->db->affected_rows()

+

Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).

+

Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the +correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file.

+ + +

$this->db->count_all();

+

Permits you to determine the number of rows in a particular table. Submit the table name in the first parameter. Example:

+echo $this->db->count_all('my_table');
+
+// Produces an integer, like 25 +
+ + +

$this->db->platform()

+

Outputs the database platform you are running (MySQL, MS SQL, Postgres, etc...):

+echo $this->db->platform(); + + +

$this->db->version()

+

Outputs the database version you are running:

+echo $this->db->version(); + + +

$this->db->last_query();

+

Returns the last query that was run (the query string, not the result). Example:

+ +$str = $this->db->last_query();
+
+// Produces: SELECT * FROM sometable.... +
+ + +

The following two functions help simplify the process of writing database INSERTs and UPDATEs.

+ + +

$this->db->insert_string();

+

This function simplifies the process of writing database inserts. It returns a correctly formatted SQL insert string. Example:

+ +$data = array('name' => $name, 'email' => $email, 'url' => $url);
+
+$str = $this->db->insert_string('table_name', $data); +
+ +

The first parameter is the table name, the second is an associative array with the data to be inserted. The above example produces:

+INSERT INTO table_name (name, email, url) VALUES ('Rick', 'rick@example.com', 'example.com') + +

Note: Values are automatically escaped, producing safer queries.

+ + + +

$this->db->update_string();

+

This function simplifies the process of writing database updates. It returns a correctly formatted SQL update string. Example:

+ +$data = array('name' => $name, 'email' => $email, 'url' => $url);
+
+$where = "author_id = 1 AND status = 'active'"; +

+$str = $this->db->update_string('table_name', $data, $where); +
+ +

The first parameter is the table name, the second is an associative array with the data to be updated, and the third parameter is the "where" clause. The above example produces:

+ UPDATE table_name SET name = 'Rick', email = 'rick@example.com', url = 'example.com' WHERE author_id = 1 AND status = 'active' + +

Note: Values are automatically escaped, producing safer queries.

+ + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/index.html b/api/user_guide/database/index.html new file mode 100644 index 0000000..3bfcba4 --- /dev/null +++ b/api/user_guide/database/index.html @@ -0,0 +1,99 @@ + + + + + +The Database Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ + +

The Database Class

+ +

CodeIgniter comes with a full-featured and very fast abstracted database class that supports both traditional +structures and Active Record patterns. The database functions offer clear, simple syntax.

+ + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/queries.html b/api/user_guide/database/queries.html new file mode 100644 index 0000000..63eb0c0 --- /dev/null +++ b/api/user_guide/database/queries.html @@ -0,0 +1,158 @@ + + + + + +Queries : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + + +
+ + + +
+ + +

Queries

+ +

$this->db->query();

+ +

To submit a query, use the following function:

+ +$this->db->query('YOUR QUERY HERE'); + +

The query() function returns a database result object when "read" type queries are run, +which you can use to show your results. When "write" type queries are run it simply returns TRUE or FALSE +depending on success or failure. When retrieving data you will typically assign the query to your own variable, like this:

+ +$query = $this->db->query('YOUR QUERY HERE'); + +

$this->db->simple_query();

+ +

This is a simplified version of the $this->db->query() function. It ONLY returns TRUE/FALSE on success or failure. +It DOES NOT return a database result set, nor does it set the query timer, or compile bind data, or store your query for debugging. +It simply lets you submit a query. Most users will rarely use this function.

+ + +

Working with Database prefixes manually

+

If you have configured a database prefix and would like to prepend it to a table name for use in a native SQL query for example, then you can use the following:

+

$this->db->dbprefix('tablename');
+// outputs prefix_tablename

+ +

If for any reason you would like to change the prefix programatically without needing to create a new connection, you can use this method:

+

$this->db->set_dbprefix('newprefix');

+$this->db->dbprefix('tablename');
+// outputs newprefix_tablename

+ + +

Protecting identifiers

+

In many databases it is advisable to protect table and field names - for example with backticks in MySQL. Active Record queries are automatically protected, however if you need to manually protect an identifier you can use:

+

$this->db->protect_identifiers('table_name');

+ +

This function will also add a table prefix to your table, assuming you have a prefix specified in your database config file. To enable the prefixing set TRUE (boolen) via the second parameter:

+

$this->db->protect_identifiers('table_name', TRUE);

+ + +

Escaping Queries

+

It's a very good security practice to escape your data before submitting it into your database. +CodeIgniter has three methods that help you do this:

+ +
    +
  1. $this->db->escape() This function determines the data type so that it +can escape only string data. It also automatically adds single quotes around the data so you don't have to: + +$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
  2. + +
  3. $this->db->escape_str() This function escapes the data passed to it, regardless of type. +Most of the time you'll use the above function rather than this one. Use the function like this: + +$sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
  4. + +
  5. $this->db->escape_like_str() This method should be used when strings are to be used in LIKE +conditions so that LIKE wildcards ('%', '_') in the string are also properly escaped. + +$search = '20% raise';
    +$sql = "SELECT id FROM table WHERE column LIKE '%".$this->db->escape_like_str($search)."%'";
  6. + +
+ + +

Query Bindings

+ + +

Bindings enable you to simplify your query syntax by letting the system put the queries together for you. Consider the following example:

+ + +$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; +

+$this->db->query($sql, array(3, 'live', 'Rick')); +
+ +

The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.

+

The secondary benefit of using binds is that the values are automatically escaped, producing safer queries. You don't have to remember to manually escape data; the engine does it automatically for you.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/results.html b/api/user_guide/database/results.html new file mode 100644 index 0000000..1b7d957 --- /dev/null +++ b/api/user_guide/database/results.html @@ -0,0 +1,259 @@ + + + + + +Generating Query Results : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ + + +

Generating Query Results

+ + +

There are several ways to generate query results:

+ +

result()

+ +

This function returns the query result as an array of objects, or an empty array on failure. + + Typically you'll use this in a foreach loop, like this:

+ + + $query = $this->db->query("YOUR QUERY");
+
+ foreach ($query->result() as $row)
+ {
+    echo $row->title;
+    echo $row->name;
+    echo $row->body;
+ }
+ +

The above function is an alias of result_object().

+ +

If you run queries that might not produce a result, you are encouraged to test the result first:

+ + + $query = $this->db->query("YOUR QUERY");
+
+ if ($query->num_rows() > 0)
+ {
+    foreach ($query->result() as $row)
+    {
+       echo $row->title;
+       echo $row->name;
+       echo $row->body;
+    }
+ } +
+ +

You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)

+ + + $query = $this->db->query("SELECT * FROM users;");
+
+ foreach ($query->result('User') as $row)
+ {
+    echo $row->name; // call attributes
+    echo $row->reverse_name(); // or methods defined on the 'User' class
+ } +
+ +

result_array()

+ +

This function returns the query result as a pure array, or an empty array when no result is produced. Typically you'll use this in a foreach loop, like this:

+ + $query = $this->db->query("YOUR QUERY");
+
+ foreach ($query->result_array() as $row)
+ {
+    echo $row['title'];
+    echo $row['name'];
+    echo $row['body'];
+ }
+ + +

row()

+ +

This function returns a single result row. If your query has more than one row, it returns only the first row. + The result is returned as an object. Here's a usage example:

+ + $query = $this->db->query("YOUR QUERY");
+
+ if ($query->num_rows() > 0)
+ {
+    $row = $query->row(); +

+    echo $row->title;
+    echo $row->name;
+    echo $row->body;
+ } +
+ +

If you want a specific row returned you can submit the row number as a digit in the first parameter:

+ + $row = $query->row(5); + +

You can also add a second String parameter, which is the name of a class to instantiate the row with:

+ + + $query = $this->db->query("SELECT * FROM users LIMIT 1;");
+
+ $query->row(0, 'User')
+ echo $row->name; // call attributes
+ echo $row->reverse_name(); // or methods defined on the 'User' class
+
+ +

row_array()

+ +

Identical to the above row() function, except it returns an array. Example:

+ + + $query = $this->db->query("YOUR QUERY");
+
+ if ($query->num_rows() > 0)
+ {
+    $row = $query->row_array(); +

+    echo $row['title'];
+    echo $row['name'];
+    echo $row['body'];
+ } +
+ + +

If you want a specific row returned you can submit the row number as a digit in the first parameter:

+ + $row = $query->row_array(5); + + +

In addition, you can walk forward/backwards/first/last through your results using these variations:

+ +

+ $row = $query->first_row()
+ $row = $query->last_row()
+ $row = $query->next_row()
+ $row = $query->previous_row() +

+ +

By default they return an object unless you put the word "array" in the parameter:

+ +

+ $row = $query->first_row('array')
+ $row = $query->last_row('array')
+ $row = $query->next_row('array')
+ $row = $query->previous_row('array') +

+ + + +

Result Helper Functions

+ + +

$query->num_rows()

+

The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:

+ +$query = $this->db->query('SELECT * FROM my_table');

+echo $query->num_rows(); +
+ +

$query->num_fields()

+

The number of FIELDS (columns) returned by the query. Make sure to call the function using your query result object:

+ +$query = $this->db->query('SELECT * FROM my_table');

+echo $query->num_fields(); +
+ + + +

$query->free_result()

+

It frees the memory associated with the result and deletes the result resource ID. Normally PHP frees its memory automatically at the end of script +execution. However, if you are running a lot of queries in a particular script you might want to free the result after each query result has been +generated in order to cut down on memory consumptions. Example: +

+ +$query = $this->db->query('SELECT title FROM my_table');

+foreach ($query->result() as $row)
+{
+   echo $row->title;
+}
+$query->free_result(); // The $query result object will no longer be available
+
+$query2 = $this->db->query('SELECT name FROM some_table');

+$row = $query2->row();
+echo $row->name;
+$query2->free_result(); // The $query2 result object will no longer be available +
+ + + + + +
+ + + + + + + diff --git a/api/user_guide/database/table_data.html b/api/user_guide/database/table_data.html new file mode 100644 index 0000000..53b8b77 --- /dev/null +++ b/api/user_guide/database/table_data.html @@ -0,0 +1,113 @@ + + + + + +Table Data : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ + + +

Table Data

+ +

These functions let you fetch table information.

+ +

$this->db->list_tables();

+ +

Returns an array containing the names of all the tables in the database you are currently connected to. Example:

+ +$tables = $this->db->list_tables();
+
+foreach ($tables as $table)
+{
+   echo $table;
+} +
+ + +

$this->db->table_exists();

+ +

Sometimes it's helpful to know whether a particular table exists before running an operation on it. +Returns a boolean TRUE/FALSE. Usage example:

+ + +if ($this->db->table_exists('table_name'))
+{
+   // some code...
+} +
+ +

Note: Replace table_name with the name of the table you are looking for.

+ + + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/transactions.html b/api/user_guide/database/transactions.html new file mode 100644 index 0000000..21bfd4f --- /dev/null +++ b/api/user_guide/database/transactions.html @@ -0,0 +1,200 @@ + + + + + +Transactions : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + + +
+ + + +
+ + + +
+ + +

Transactions

+ +

CodeIgniter's database abstraction allows you to use transactions with databases that support transaction-safe table types. In MySQL, you'll need +to be running InnoDB or BDB table types rather than the more common MyISAM. Most other database platforms support transactions natively.

+ +

If you are not familiar with +transactions we recommend you find a good online resource to learn about them for your particular database. The information below assumes you +have a basic understanding of transactions. +

+ +

CodeIgniter's Approach to Transactions

+ +

CodeIgniter utilizes an approach to transactions that is very similar to the process used by the popular database class ADODB. We've chosen that approach +because it greatly simplifies the process of running transactions. In most cases all that is required are two lines of code.

+ +

Traditionally, transactions have required a fair amount of work to implement since they demand that you to keep track of your queries +and determine whether to commit or rollback based on the success or failure of your queries. This is particularly cumbersome with +nested queries. In contrast, +we've implemented a smart transaction system that does all this for you automatically (you can also manage your transactions manually if you choose to, +but there's really no benefit).

+ +

Running Transactions

+ +

To run your queries using transactions you will use the $this->db->trans_start() and $this->db->trans_complete() functions as follows:

+ + +$this->db->trans_start();
+$this->db->query('AN SQL QUERY...');
+$this->db->query('ANOTHER QUERY...');
+$this->db->query('AND YET ANOTHER QUERY...');
+$this->db->trans_complete(); +
+ +

You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure +of any given query.

+ + +

Strict Mode

+ +

By default CodeIgniter runs all transactions in Strict Mode. When strict mode is enabled, if you are running multiple groups of +transactions, if one group fails all groups will be rolled back. If strict mode is disabled, each group is treated independently, meaning +a failure of one group will not affect any others.

+ +

Strict Mode can be disabled as follows:

+ +$this->db->trans_strict(FALSE); + + +

Managing Errors

+ +

If you have error reporting enabled in your config/database.php file you'll see a standard error message if the commit was unsuccessful. If debugging is turned off, you can +manage your own errors like this:

+ + +$this->db->trans_start();
+$this->db->query('AN SQL QUERY...');
+$this->db->query('ANOTHER QUERY...');
+$this->db->trans_complete();
+
+if ($this->db->trans_status() === FALSE)
+{
+    // generate an error... or use the log_message() function to log your error
+} +
+ + +

Enabling Transactions

+ +

Transactions are enabled automatically the moment you use $this->db->trans_start(). If you would like to disable transactions you +can do so using $this->db->trans_off():

+ + +$this->db->trans_off()

+ +$this->db->trans_start();
+$this->db->query('AN SQL QUERY...');
+$this->db->trans_complete(); +
+ +

When transactions are disabled, your queries will be auto-commited, just as they are when running queries without transactions.

+ + +

Test Mode

+ +

You can optionally put the transaction system into "test mode", which will cause your queries to be rolled back -- even if the queries produce a valid result. +To use test mode simply set the first parameter in the $this->db->trans_start() function to TRUE:

+ + +$this->db->trans_start(TRUE); // Query will be rolled back
+$this->db->query('AN SQL QUERY...');
+$this->db->trans_complete(); +
+ + +

Running Transactions Manually

+ +

If you would like to run transactions manually you can do so as follows:

+ + +$this->db->trans_begin();

+ +$this->db->query('AN SQL QUERY...');
+$this->db->query('ANOTHER QUERY...');
+$this->db->query('AND YET ANOTHER QUERY...');
+ +
+ +if ($this->db->trans_status() === FALSE)
+{
+    $this->db->trans_rollback();
+}
+else
+{
+    $this->db->trans_commit();
+}
+
+ +

Note: Make sure to use $this->db->trans_begin() when running manual transactions, NOT +$this->db->trans_start().

+ + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/database/utilities.html b/api/user_guide/database/utilities.html new file mode 100644 index 0000000..cf2b00c --- /dev/null +++ b/api/user_guide/database/utilities.html @@ -0,0 +1,314 @@ + + + + + +Database Utility Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + + +
+ + + +
+ +

Database Utility Class

+ +

The Database Utility Class contains functions that help you manage your database.

+ +

Table of Contents

+ + + + + +

Initializing the Utility Class

+ +

Important:  In order to initialize the Utility class, your database driver must +already be running, since the utilities class relies on it.

+ +

Load the Utility Class as follows:

+ +$this->load->dbutil() + +

Once initialized you will access the functions using the $this->dbutil object:

+ +$this->dbutil->some_function() + +

$this->dbutil->list_databases()

+

Returns an array of database names:

+ + +$dbs = $this->dbutil->list_databases();
+
+foreach ($dbs as $db)
+{
+    echo $db;
+}
+ + +

$this->dbutil->database_exists();

+ +

Sometimes it's helpful to know whether a particular database exists. +Returns a boolean TRUE/FALSE. Usage example:

+ + +if ($this->dbutil->database_exists('database_name'))
+{
+   // some code...
+} +
+ +

Note: Replace database_name with the name of the table you are looking for. This function is case sensitive.

+ + + +

$this->dbutil->optimize_table('table_name');

+ +

Note:  This features is only available for MySQL/MySQLi databases.

+ + +

Permits you to optimize a table using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:

+ + +if ($this->dbutil->optimize_table('table_name'))
+{
+    echo 'Success!';
+} +
+ +

Note: Not all database platforms support table optimization.

+ + +

$this->dbutil->repair_table('table_name');

+ +

Note:  This features is only available for MySQL/MySQLi databases.

+ + +

Permits you to repair a table using the table name specified in the first parameter. Returns TRUE/FALSE based on success or failure:

+ + +if ($this->dbutil->repair_table('table_name'))
+{
+    echo 'Success!';
+} +
+ +

Note: Not all database platforms support table repairs.

+ + +

$this->dbutil->optimize_database();

+ +

Note:  This features is only available for MySQL/MySQLi databases.

+ +

Permits you to optimize the database your DB class is currently connected to. Returns an array containing the DB status messages or FALSE on failure.

+ + +$result = $this->dbutil->optimize_database();
+
+if ($result !== FALSE)
+{
+    print_r($result);
+} +
+ +

Note: Not all database platforms support table optimization.

+ + +

$this->dbutil->csv_from_result($db_result)

+ +

Permits you to generate a CSV file from a query result. The first parameter of the function must contain the result object from your query. +Example:

+ + +$this->load->dbutil();
+
+$query = $this->db->query("SELECT * FROM mytable");
+
+echo $this->dbutil->csv_from_result($query); +
+ +

The second and third parameters allows you to +set the delimiter and newline character. By default tabs are used as the delimiter and "\n" is used as a new line. Example:

+ + +$delimiter = ",";
+$newline = "\r\n";
+
+echo $this->dbutil->csv_from_result($query, $delimiter, $newline); +
+ +

Important:  This function will NOT write the CSV file for you. It simply creates the CSV layout. +If you need to write the file use the File Helper.

+ + +

$this->dbutil->xml_from_result($db_result)

+ +

Permits you to generate an XML file from a query result. The first parameter expects a query result object, the second +may contain an optional array of config parameters. Example:

+ + +$this->load->dbutil();
+
+$query = $this->db->query("SELECT * FROM mytable");
+
+$config = array (
+                  'root'    => 'root',
+                  'element' => 'element',
+                  'newline' => "\n",
+                  'tab'    => "\t"
+                );
+
+echo $this->dbutil->xml_from_result($query, $config); +
+ +

Important:  This function will NOT write the XML file for you. It simply creates the XML layout. +If you need to write the file use the File Helper.

+ + +

$this->dbutil->backup()

+ +

Permits you to backup your full database or individual tables. The backup data can be compressed in either Zip or Gzip format.

+ +

Note:  This features is only available for MySQL databases.

+ +

Note: Due to the limited execution time and memory available to PHP, backing up very large +databases may not be possible. If your database is very large you might need to backup directly from your SQL server +via the command line, or have your server admin do it for you if you do not have root privileges.

+ +

Usage Example

+ + +// Load the DB utility class
+$this->load->dbutil();

+ +// Backup your entire database and assign it to a variable
+$backup =& $this->dbutil->backup(); + +

+// Load the file helper and write the file to your server
+$this->load->helper('file');
+write_file('/path/to/mybackup.gz', $backup); + +

+// Load the download helper and send the file to your desktop
+$this->load->helper('download');
+force_download('mybackup.gz', $backup); +
+ +

Setting Backup Preferences

+ +

Backup preferences are set by submitting an array of values to the first parameter of the backup function. Example:

+ +$prefs = array(
+                'tables'      => array('table1', 'table2'),  // Array of tables to backup.
+                'ignore'      => array(),           // List of tables to omit from the backup
+                'format'      => 'txt',             // gzip, zip, txt
+                'filename'    => 'mybackup.sql',    // File name - NEEDED ONLY WITH ZIP FILES
+                'add_drop'    => TRUE,              // Whether to add DROP TABLE statements to backup file
+                'add_insert'  => TRUE,              // Whether to add INSERT data to backup file
+                'newline'     => "\n"               // Newline character used in backup file
+              );
+
+$this->dbutil->backup($prefs); +
+ + +

Description of Backup Preferences

+ + + + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
tablesempty arrayNoneAn array of tables you want backed up. If left blank all tables will be exported.
ignoreempty arrayNoneAn array of tables you want the backup routine to ignore.
formatgzipgzip, zip, txtThe file format of the export file.
filenamethe current date/timeNoneThe name of the backed-up file. The name is needed only if you are using zip compression.
add_dropTRUETRUE/FALSEWhether to include DROP TABLE statements in your SQL export file.
add_insertTRUETRUE/FALSEWhether to include INSERT statements in your SQL export file.
newline"\n""\n", "\r", "\r\n"Type of newline to use in your SQL export file.
+ + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/doc_style/index.html b/api/user_guide/doc_style/index.html new file mode 100644 index 0000000..2de0dd6 --- /dev/null +++ b/api/user_guide/doc_style/index.html @@ -0,0 +1,87 @@ + + + + + +Writing Documentation : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Writing Documentation

+ +

To help facilitate a consistent, easy-to-read documentation style for CodeIgniter projects, EllisLab is making the markup and CSS from the CodeIgniter user guide freely available to the community for their use. For your convenience, a template file has been created that includes the primary blocks of markup used with brief samples.

+ +

Files

+ + + + +
+ + + + + + + + \ No newline at end of file diff --git a/api/user_guide/doc_style/template.html b/api/user_guide/doc_style/template.html new file mode 100644 index 0000000..3fde59c --- /dev/null +++ b/api/user_guide/doc_style/template.html @@ -0,0 +1,128 @@ + + + + + +CodeIgniter Project Documentation Template + + + + + + + + + + + + + + +
+ + + + + +

Project Title

+
+ + + + + + + + + +
+ + +
+ + + +
+ + +

Foo Class

+ +

Brief description of Foo Class. If it extends a native CodeIgniter class, please link to the class in the CodeIgniter documents here.

+ +

Important:  This is an important note with EMPHASIS.

+ +

Features:

+ +
    +
  • Foo
  • +
  • Bar
  • +
+ +

Usage Heading

+ +

Within a text string, highlight variables using <var></var> tags, and highlight code using the <dfn></dfn> tags.

+ +

Sub-heading

+ +

Put code examples within <code></code> tags:

+ + + $this->load->library('foo');
+
+ $this->foo->bar('bat'); +
+ + +

Table Preferences

+ +

Use tables where appropriate for long lists of preferences.

+ + + + + + + + + + + + + + + + + + + + + +
PreferenceDefault ValueOptionsDescription
fooFooNoneDescription of foo.
barBarbat, bag, or bakDescription of bar.
+ +

Foo Function Reference

+ +

$this->foo->bar()

+

Description

+$this->foo->bar('baz') + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/alternative_php.html b/api/user_guide/general/alternative_php.html new file mode 100644 index 0000000..c62fef9 --- /dev/null +++ b/api/user_guide/general/alternative_php.html @@ -0,0 +1,147 @@ + + + + + +Alternate PHP Syntax for View Files : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Alternate PHP Syntax for View Files

+ +

If you do not utilize CodeIgniter's template engine, you'll be using pure PHP +in your View files. To minimize the PHP code in these files, and to make it easier to identify the code blocks it is recommended that you use +PHPs alternative syntax for control structures and short tag echo statements. If you are not familiar with this syntax, it allows you to eliminate the braces from your code, +and eliminate "echo" statements.

+ +

Automatic Short Tag Support

+ +

Note: If you find that the syntax described in this page does not work on your server it might +be that "short tags" are disabled in your PHP ini file. CodeIgniter will optionally rewrite short tags on-the-fly, +allowing you to use that syntax even if your server doesn't support it. This feature can be enabled in your +config/config.php file.

+ +

Please note that if you do use this feature, if PHP errors are encountered +in your view files, the error message and line number will not be accurately shown. Instead, all errors +will be shown as eval() errors.

+ + +

Alternative Echos

+ +

Normally to echo, or print out a variable you would do this:

+ +<?php echo $variable; ?> + +

With the alternative syntax you can instead do it this way:

+ +<?=$variable?> + + + +

Alternative Control Structures

+ +

Controls structures, like if, for, foreach, and while can be +written in a simplified format as well. Here is an example using foreach:

+ + +<ul>
+
+<?php foreach ($todo as $item): ?>
+
+<li><?=$item?></li>
+
+<?php endforeach; ?>
+
+</ul>
+ +

Notice that there are no braces. Instead, the end brace is replaced with endforeach. +Each of the control structures listed above has a similar closing syntax: +endif, endfor, endforeach, and endwhile

+ +

Also notice that instead of using a semicolon after each structure (except the last one), there is a colon. This is +important!

+ +

Here is another example, using if/elseif/else. Notice the colons:

+ + +<?php if ($username == 'sally'): ?>
+
+   <h3>Hi Sally</h3>
+
+<?php elseif ($username == 'joe'): ?>
+
+   <h3>Hi Joe</h3>
+
+<?php else: ?>
+
+   <h3>Hi unknown user</h3>
+
+<?php endif; ?>
+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/ancillary_classes.html b/api/user_guide/general/ancillary_classes.html new file mode 100644 index 0000000..c1ea33c --- /dev/null +++ b/api/user_guide/general/ancillary_classes.html @@ -0,0 +1,117 @@ + + + + + +Creating Ancillary Classes : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Creating Ancillary Classes

+ +

In some cases you may want to develop classes that exist apart from your controllers but have the ability to +utilize all of CodeIgniter's resources. This is easily possible as you'll see.

+ +

get_instance()

+ + +

Any class that you instantiate within your controller functions can access CodeIgniter's native resources simply by using the get_instance() function. +This function returns the main CodeIgniter object.

+ +

Normally, to call any of the available CodeIgniter functions requires you to use the $this construct:

+ + +$this->load->helper('url');
+$this->load->library('session');
+$this->config->item('base_url');
+etc. +
+ +

$this, however, only works within your controllers, your models, or your views. +If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows:

+ + +

First, assign the CodeIgniter object to a variable:

+ +$CI =& get_instance(); + +

Once you've assigned the object to a variable, you'll use that variable instead of $this:

+ + +$CI =& get_instance();

+$CI->load->helper('url');
+$CI->load->library('session');
+$CI->config->item('base_url');
+etc. +
+ +

Note: You'll notice that the above get_instance() function is being passed by reference: +

+$CI =& get_instance(); +

+This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

+
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/autoloader.html b/api/user_guide/general/autoloader.html new file mode 100644 index 0000000..764b42e --- /dev/null +++ b/api/user_guide/general/autoloader.html @@ -0,0 +1,100 @@ + + + + + +Auto-loading Resources : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Auto-loading Resources

+ +

CodeIgniter comes with an "Auto-load" feature that permits libraries, helpers, and models to be initialized +automatically every time the system runs. If you need certain resources globally throughout your application you should +consider auto-loading them for convenience.

+ +

The following items can be loaded automatically:

+ +
    +
  • Core classes found in the "libraries" folder
  • +
  • Helper files found in the "helpers" folder
  • +
  • Custom config files found in the "config" folder
  • +
  • Language files found in the "system/language" folder
  • +
  • Models found in the "models" folder
  • +
+ +

To autoload resources, open the application/config/autoload.php file and add the item you want +loaded to the autoload array. You'll find instructions in that file corresponding to each +type of item.

+ +

Note: Do not include the file extension (.php) when adding items to the autoload array.

+ + + + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/caching.html b/api/user_guide/general/caching.html new file mode 100644 index 0000000..af671fb --- /dev/null +++ b/api/user_guide/general/caching.html @@ -0,0 +1,115 @@ + + + + + +Web Page Caching : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ + +

Web Page Caching

+ +

CodeIgniter lets you cache your pages in order to achieve maximum performance.

+ +

Although CodeIgniter is quite fast, the amount of dynamic information you display in your pages will correlate directly to the +server resources, memory, and processing cycles utilized, which affect your page load speeds. +By caching your pages, since they are saved in their fully rendered state, you can achieve performance that nears that of static web pages.

+ + +

How Does Caching Work?

+ +

Caching can be enabled on a per-page basis, and you can set the length of time that a page should remain cached before being refreshed. +When a page is loaded for the first time, the cache file will be written to your application/cache folder. On subsequent page loads the cache file will be retrieved +and sent to the requesting user's browser. If it has expired, it will be deleted and refreshed before being sent to the browser.

+ +

Note: The Benchmark tag is not cached so you can still view your page load speed when caching is enabled.

+ +

Enabling Caching

+ +

To enable caching, put the following tag in any of your controller functions:

+ +$this->output->cache(n); + +

Where n is the number of minutes you wish the page to remain cached between refreshes.

+ +

The above tag can go anywhere within a function. It is not affected by the order that it appears, so place it wherever it seems +most logical to you. Once the tag is in place, your pages will begin being cached.

+ +

Warning: Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.

+

Note: Before the cache files can be written you must set the file permissions on your +application/cache folder such that it is writable.

+ +

Deleting Caches

+ +

If you no longer wish to cache a file you can remove the caching tag and it will no longer be refreshed when it expires. Note: +Removing the tag will not delete the cache immediately. It will have to expire normally. If you need to remove it earlier you +will need to manually delete it from your cache folder.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/cli.html b/api/user_guide/general/cli.html new file mode 100644 index 0000000..658754f --- /dev/null +++ b/api/user_guide/general/cli.html @@ -0,0 +1,150 @@ + + + + + +Running via the CLI : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Running via the CLI

+ +

+ As well as calling an applications Controllers via the URL in a browser they can also be loaded via the command-line interface (CLI). +

+ + + + + + +

What is the CLI?

+ +

The command-line interface is a text-based method of interacting with computers. For more information, check the Wikipedia article.

+ + + +

Why run via the command-line?

+ +

+ There are many reasons for running CodeIgniter from the command-line, but they are not always obvious.

+ +
    +
  • Run your cron-jobs without needing to use wget or curl
  • +
  • Make your cron-jobs inaccessible from being loaded in the URL by checking for $this->input->is_cli_request()
  • +
  • Make interactive "tasks" that can do things like set permissions, prune cache folders, run backups, etc.
  • +
  • Integrate with other applications in other languages. For example, a random C++ script could call one command and run code in your models!
  • +
+ + +

Let's try it:  Hello World!

+ +

Let's create a simple controller so you can see it in action. Using your text editor, create a file called tools.php, and put the following code in it:

+ + + +

Then save the file to your application/controllers/ folder.

+ +

Now normally you would visit the your site using a URL similar to this:

+ +example.com/index.php/tools/message/to + +

Instead, we are going to open Terminal in Mac/Lunix or go to Run > "cmd" in Windows and navigate to our CodeIgniter project.

+ +
+ $ cd /path/to/project;
+ $ php index.php tools message +
+ +

If you did it right, you should see Hello World!.

+ +
+ $ php index.php tools message "John Smith" +
+ +

Here we are passing it a argument in the same way that URL parameters work. "John Smith" is passed as a argument and output is: Hello John Smith!.

+ +

That's it!

+ +

That, in a nutshell, is all there is to know about controllers on the command line. Remember that this is just a normal controller, so routing and _remap works fine.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/common_functions.html b/api/user_guide/general/common_functions.html new file mode 100644 index 0000000..b3f4f32 --- /dev/null +++ b/api/user_guide/general/common_functions.html @@ -0,0 +1,127 @@ + + + + + +Common Functions : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Common Functions

+ +

CodeIgniter uses a few functions for its operation that are globally defined, and are available to you at any point. These do not require loading any libraries or helpers.

+ +

is_php('version_number')

+ +

is_php() determines of the PHP version being used is greater than the supplied version_number.

+ +if (is_php('5.3.0'))
+{
+    $str = quoted_printable_encode($str);
+}
+ +

Returns boolean TRUE if the installed version of PHP is equal to or greater than the supplied version number. Returns FALSE if the installed version of PHP is lower than the supplied version number.

+ + +

is_really_writable('path/to/file')

+ +

is_writable() returns TRUE on Windows servers when you really can't write to the file as the OS reports to PHP as FALSE only if the read-only attribute is marked. This function determines if a file is actually writable by attempting to write to it first. Generally only recommended on platforms where this information may be unreliable.

+ +if (is_really_writable('file.txt'))
+{
+    echo "I could write to this if I wanted to";
+}
+else
+{
+    echo "File is not writable";
+}
+ +

config_item('item_key')

+

The Config library is the preferred way of accessing configuration information, however config_item() can be used to retrieve single keys. See Config library documentation for more information.

+ +

show_error('message'), show_404('page'), log_message('level', 'message')

+

These are each outlined on the Error Handling page.

+ +

set_status_header(code, 'text');

+ +

Permits you to manually set a server status header. Example:

+ +set_status_header(401);
+// Sets the header as: Unauthorized
+ +

See here for a full list of headers.

+ + +

remove_invisible_characters($str)

+

This function prevents inserting null characters between ascii characters, like Java\0script.

+ + +

html_escape($mixed)

+

This function provides short cut for htmlspecialchars() function. It accepts string and array. To prevent Cross Site Scripting (XSS), it is very useful.

+ +
+ + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/controllers.html b/api/user_guide/general/controllers.html new file mode 100644 index 0000000..7600423 --- /dev/null +++ b/api/user_guide/general/controllers.html @@ -0,0 +1,388 @@ + + + + + +Controllers : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Controllers

+ +

Controllers are the heart of your application, as they determine how HTTP requests should be handled.

+ + + + + + +

What is a Controller?

+ +

A Controller is simply a class file that is named in a way that can be associated with a URI.

+ +

Consider this URI:

+ +example.com/index.php/blog/ + +

In the above example, CodeIgniter would attempt to find a controller named blog.php and load it.

+ +

When a controller's name matches the first segment of a URI, it will be loaded.

+ + +

Let's try it:  Hello World!

+ +

Let's create a simple controller so you can see it in action. Using your text editor, create a file called blog.php, and put the following code in it:

+ + + + + + +

Then save the file to your application/controllers/ folder.

+ +

Now visit the your site using a URL similar to this:

+ +example.com/index.php/blog/ + +

If you did it right, you should see Hello World!.

+ +

Note: Class names must start with an uppercase letter. In other words, this is valid:

+ +<?php
+class Blog extends CI_Controller {
+
+}
+?>
+ +

This is not valid:

+ +<?php
+class blog extends CI_Controller {
+
+}
+?>
+ +

Also, always make sure your controller extends the parent controller class so that it can inherit all its functions.

+ + + + +

Functions

+ +

In the above example the function name is index(). The "index" function is always loaded by default if the +second segment of the URI is empty. Another way to show your "Hello World" message would be this:

+ +example.com/index.php/blog/index/ + +

The second segment of the URI determines which function in the controller gets called.

+ +

Let's try it. Add a new function to your controller:

+ + + + +

Now load the following URL to see the comment function:

+ +example.com/index.php/blog/comments/ + +

You should see your new message.

+ + +

Passing URI Segments to your Functions

+ +

If your URI contains more then two segments they will be passed to your function as parameters.

+ +

For example, lets say you have a URI like this:

+ +example.com/index.php/products/shoes/sandals/123 + +

Your function will be passed URI segments 3 and 4 ("sandals" and "123"):

+ + +<?php
+class Products extends CI_Controller {
+
+    public function shoes($sandals, $id)
+    {
+        echo $sandals;
+        echo $id;
+    }
+}
+?> +
+ +

Important:  If you are using the URI Routing feature, the segments +passed to your function will be the re-routed ones.

+ + + +

Defining a Default Controller

+ +

CodeIgniter can be told to load a default controller when a URI is not present, +as will be the case when only your site root URL is requested. To specify a default controller, open +your application/config/routes.php file and set this variable:

+ +$route['default_controller'] = 'Blog'; + +

Where Blog is the name of the controller class you want used. If you now load your main index.php file without +specifying any URI segments you'll see your Hello World message by default.

+ + + + +

Remapping Function Calls

+ +

As noted above, the second segment of the URI typically determines which function in the controller gets called. +CodeIgniter permits you to override this behavior through the use of the _remap() function:

+ +public function _remap()
+{
+    // Some code here...
+}
+ +

Important:  If your controller contains a function named _remap(), it will always +get called regardless of what your URI contains. It overrides the normal behavior in which the URI determines which function is called, +allowing you to define your own function routing rules.

+ +

The overridden function call (typically the second segment of the URI) will be passed as a parameter to the _remap() function:

+ +public function _remap($method)
+{
+    if ($method == 'some_method')
+    {
+        $this->$method();
+    }
+    else
+    {
+        $this->default_method();
+    }
+}
+ +

Any extra segments after the method name are passed into _remap() as an optional second parameter. This array can be used in combination with PHP's call_user_func_array to emulate CodeIgniter's default behavior.

+ +public function _remap($method, $params = array())
+{
+    $method = 'process_'.$method;
+    if (method_exists($this, $method))
+    {
+        return call_user_func_array(array($this, $method), $params);
+    }
+    show_404();
+}
+ + + +

Processing Output

+ +

CodeIgniter has an output class that takes care of sending your final rendered data to the web browser automatically. More information on this can be found in the +Views and Output class pages. In some cases, however, you might want to +post-process the finalized data in some way and send it to the browser yourself. CodeIgniter permits you to +add a function named _output() to your controller that will receive the finalized output data.

+ +

Important:  If your controller contains a function named _output(), it will always +be called by the output class instead of echoing the finalized data directly. The first parameter of the function will contain the finalized output.

+ +

Here is an example:

+ + +public function _output($output)
+{
+    echo $output;
+}
+ +

Please note that your _output() function will receive the data in its finalized state. Benchmark and memory usage data will be rendered, +cache files written (if you have caching enabled), and headers will be sent (if you use that feature) +before it is handed off to the _output() function.
+
+To have your controller's output cached properly, its _output() method can use:
+ +if ($this->output->cache_expiration > 0)
+{
+    $this->output->_write_cache($output);
+}
+ +If you are using this feature the page execution timer and memory usage stats might not be perfectly accurate +since they will not take into acccount any further processing you do. For an alternate way to control output before any of the final processing is done, please see +the available methods in the Output Class.

+ + +

Private Functions

+ + +

In some cases you may want certain functions hidden from public access. To make a function private, simply add an +underscore as the name prefix and it will not be served via a URL request. For example, if you were to have a function like this:

+ + +private function _utility()
+{
+  // some code
+}
+ +

Trying to access it via the URL, like this, will not work:

+ +example.com/index.php/blog/_utility/ + + + + +

Organizing Your Controllers into Sub-folders

+ +

If you are building a large application you might find it convenient to organize your controllers into sub-folders. CodeIgniter permits you to do this.

+ +

Simply create folders within your application/controllers directory and place your controller classes within them.

+ +

Note:  When using this feature the first segment of your URI must specify the folder. For example, lets say you have a controller +located here:

+ +application/controllers/products/shoes.php + +

To call the above controller your URI will look something like this:

+ +example.com/index.php/products/shoes/show/123 + +

Each of your sub-folders may contain a default controller which will be +called if the URL contains only the sub-folder. Simply name your default controller as specified in your +application/config/routes.php file

+ + +

CodeIgniter also permits you to remap your URIs using its URI Routing feature.

+ + +

Class Constructors

+ + +

If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:

+ +parent::__construct(); + +

The reason this line is necessary is because your local constructor will be overriding the one in the parent controller class so we need to manually call it.

+ + +<?php
+class Blog extends CI_Controller {
+
+       public function __construct()
+       {
+            parent::__construct();
+            // Your own constructor code
+       }
+}
+?>
+ +

Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. +Constructors can't return a value, but they can do some default work.

+ + +

Reserved Function Names

+ +

Since your controller classes will extend the main application controller you +must be careful not to name your functions identically to the ones used by that class, otherwise your local functions +will override them. See Reserved Names for a full list.

+ +

That's it!

+ +

That, in a nutshell, is all there is to know about controllers.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/core_classes.html b/api/user_guide/general/core_classes.html new file mode 100644 index 0000000..8cd159f --- /dev/null +++ b/api/user_guide/general/core_classes.html @@ -0,0 +1,186 @@ + + + + + +Creating Core System Classes : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Creating Core System Classes

+ +

Every time CodeIgniter runs there are several base classes that are initialized automatically as part of the core framework. +It is possible, however, to swap any of the core system classes with your own versions or even extend the core versions.

+ +

Most users will never have any need to do this, +but the option to replace or extend them does exist for those who would like to significantly alter the CodeIgniter core. +

+ +

Note:  Messing with a core system class has a lot of implications, so make sure you +know what you are doing before attempting it.

+ + +

System Class List

+ +

The following is a list of the core system files that are invoked every time CodeIgniter runs:

+ +
    +
  • Benchmark
  • +
  • Config
  • +
  • Controller
  • +
  • Exceptions
  • +
  • Hooks
  • +
  • Input
  • +
  • Language
  • +
  • Loader
  • +
  • Log
  • +
  • Output
  • +
  • Router
  • +
  • URI
  • +
  • Utf8
  • +
+ +

Replacing Core Classes

+ +

To use one of your own system classes instead of a default one simply place your version inside your local application/core directory:

+ +application/core/some-class.php + +

If this directory does not exist you can create it.

+ +

Any file named identically to one from the list above will be used instead of the one normally used.

+ +

Please note that your class must use CI as a prefix. For example, if your file is named Input.php the class will be named:

+ + +class CI_Input {

+ +} +
+ + + +

Extending Core Class

+ +

If all you need to do is add some functionality to an existing library - perhaps add a function or two - then +it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. +Extending a class is nearly identical to replacing a class with a couple exceptions:

+ +
    +
  • The class declaration must extend the parent class.
  • +
  • Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
  • +
+ +

For example, to extend the native Input class you'll create a file named application/core/MY_Input.php, and declare your class with:

+ + +class MY_Input extends CI_Input {

+ +}
+ +

Note: If you need to use a constructor in your class make sure you extend the parent constructor:

+ + +class MY_Input extends CI_Input {
+
+    function __construct()
+    {
+        parent::__construct();
+    }
+}
+ +

Tip:  Any functions in your class that are named identically to the functions in the parent class will be used instead of the native ones +(this is known as "method overriding"). +This allows you to substantially alter the CodeIgniter core.

+ +

If you are extending the Controller core class, then be sure to extend your new class in your application controller's constructors.

+ +class Welcome extends MY_Controller {
+
+    function __construct()
+    {
+        parent::__construct();
+    }
+
+    function index()
+    {
+        $this->load->view('welcome_message');
+    }
+}
+ +

Setting Your Own Prefix

+ +

To set your own sub-class prefix, open your application/config/config.php file and look for this item:

+ +$config['subclass_prefix'] = 'MY_'; + +

Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

+ + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/creating_drivers.html b/api/user_guide/general/creating_drivers.html new file mode 100644 index 0000000..46a41f0 --- /dev/null +++ b/api/user_guide/general/creating_drivers.html @@ -0,0 +1,100 @@ + + + + + +Creating Drivers : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Creating Drivers

+ +

Driver Directory and File Structure

+ +

Sample driver directory and file structure layout:

+ +
    +
  • /application/libraries/Driver_name +
      +
    • Driver_name.php
    • +
    • drivers +
        +
      • Driver_name_subclass_1.php
      • +
      • Driver_name_subclass_2.php
      • +
      • Driver_name_subclass_3.php
      • +
      +
    • +
    +
  • +
+ +

NOTE: In order to maintain compatibility on case-sensitive file systems, the Driver_name directory must be ucfirst()

+ + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/creating_libraries.html b/api/user_guide/general/creating_libraries.html new file mode 100644 index 0000000..0d424a2 --- /dev/null +++ b/api/user_guide/general/creating_libraries.html @@ -0,0 +1,293 @@ + + + + + +Creating Libraries : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Creating Libraries

+ +

When we use the term "Libraries" we are normally referring to the classes that are located in the libraries +directory and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can create +your own libraries within your application/libraries directory in order to maintain separation between your local resources +and the global framework resources.

+ +

As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality +to an existing library. Or you can even replace native libraries just by placing identically named versions in your application/libraries folder.

+ +

In summary:

+ +
    +
  • You can create entirely new libraries.
  • +
  • You can extend native libraries.
  • +
  • You can replace native libraries.
  • +
+ +

The page below explains these three concepts in detail.

+ +

Note: The Database classes can not be extended or replaced with your own classes. All other classes are able to be replaced/extended.

+ + +

Storage

+ +

Your library classes should be placed within your application/libraries folder, as this is where CodeIgniter will look for them when +they are initialized.

+ + +

Naming Conventions

+ +
    +
  • File names must be capitalized. For example:  Myclass.php
  • +
  • Class declarations must be capitalized. For example:  class Myclass
  • +
  • Class names and file names must match.
  • +
+ + +

The Class File

+ +

Classes should have this basic prototype (Note: We are using the name Someclass purely as an example):

+ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +

+class Someclass {
+
+    public function some_function()
+    {
+    }
+}

+/* End of file Someclass.php */
+ + +

Using Your Class

+ +

From within any of your Controller functions you can initialize your class using the standard:

+ +$this->load->library('someclass'); + +

Where someclass is the file name, without the ".php" file extension. You can submit the file name capitalized or lower case. +CodeIgniter doesn't care.

+ +

Once loaded you can access your class using the lower case version:

+ +$this->someclass->some_function();  // Object instances will always be lower case + + + + +

Passing Parameters When Initializing Your Class

+ +

In the library loading function you can dynamically pass data as an array via the second parameter and it will be passed to your class +constructor:

+ + +$params = array('type' => 'large', 'color' => 'red');
+
+$this->load->library('Someclass', $params);
+ +

If you use this feature you must set up your class constructor to expect data:

+ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+
+class Someclass {
+
+    public function __construct($params)
+    {
+        // Do something with $params
+    }
+}

+?>
+ +

You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name +and store it in your application/config/ folder. Note that if you dynamically pass parameters as described above, +the config file option will not be available.

+ + + + + + + +

Utilizing CodeIgniter Resources within Your Library

+ + +

To access CodeIgniter's native resources within your library use the get_instance() function. +This function returns the CodeIgniter super object.

+ +

Normally from within your controller functions you will call any of the available CodeIgniter functions using the $this construct:

+ + +$this->load->helper('url');
+$this->load->library('session');
+$this->config->item('base_url');
+etc. +
+ +

$this, however, only works directly within your controllers, your models, or your views. +If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows:

+ + +

First, assign the CodeIgniter object to a variable:

+ +$CI =& get_instance(); + +

Once you've assigned the object to a variable, you'll use that variable instead of $this:

+ + +$CI =& get_instance();
+
+$CI->load->helper('url');
+$CI->load->library('session');
+$CI->config->item('base_url');
+etc. +
+ +

Note: You'll notice that the above get_instance() function is being passed by reference: +

+$CI =& get_instance(); +
+
+This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

+ + +

Replacing Native Libraries with Your Versions

+ +

Simply by naming your class files identically to a native library will cause CodeIgniter to use it instead of the native one. To use this +feature you must name the file and the class declaration exactly the same as the native library. For example, to replace the native Email library +you'll create a file named application/libraries/Email.php, and declare your class with:

+ + +class CI_Email {

+ +}
+ +

Note that most native classes are prefixed with CI_.

+ +

To load your library you'll see the standard loading function:

+ +$this->load->library('email'); + +

Note: At this time the Database classes can not be replaced with your own versions.

+ + +

Extending Native Libraries

+ +

If all you need to do is add some functionality to an existing library - perhaps add a function or two - then +it's overkill to replace the entire library with your version. In this case it's better to simply extend the class. +Extending a class is nearly identical to replacing a class with a couple exceptions:

+ +
    +
  • The class declaration must extend the parent class.
  • +
  • Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
  • +
+ +

For example, to extend the native Email class you'll create a file named application/libraries/MY_Email.php, and declare your class with:

+ + +class MY_Email extends CI_Email {

+ +}
+ +

Note: If you need to use a constructor in your class make sure you extend the parent constructor:

+ + + +class MY_Email extends CI_Email {
+
+    public function __construct()
+    {
+        parent::__construct();
+    }
+}
+ + +

Loading Your Sub-class

+ +

To load your sub-class you'll use the standard syntax normally used. DO NOT include your prefix. For example, +to load the example above, which extends the Email class, you will use:

+ +$this->load->library('email'); + +

Once loaded you will use the class variable as you normally would for the class you are extending. In the case of +the email class all calls will use:

+ + +$this->email->some_function(); + + +

Setting Your Own Prefix

+ +

To set your own sub-class prefix, open your application/config/config.php file and look for this item:

+ +$config['subclass_prefix'] = 'MY_'; + +

Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/credits.html b/api/user_guide/general/credits.html new file mode 100644 index 0000000..67a461f --- /dev/null +++ b/api/user_guide/general/credits.html @@ -0,0 +1,87 @@ + + + + + +Credits : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Credits

+ +

CodeIgniter was originally developed by Rick Ellis (CEO of +EllisLab, Inc.). The framework was written for performance in the real +world, with many of the class libraries, helpers, and sub-systems borrowed from the code-base of +ExpressionEngine.

+ +

It is currently developed and maintained by the ExpressionEngine Development Team.
+Bleeding edge development is spearheaded by the handpicked contributors of the Reactor Team.

+ +

A hat tip goes to Ruby on Rails for inspiring us to create a PHP framework, and for +bringing frameworks into the general consciousness of the web community.

+ +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/drivers.html b/api/user_guide/general/drivers.html new file mode 100644 index 0000000..b2f91ce --- /dev/null +++ b/api/user_guide/general/drivers.html @@ -0,0 +1,104 @@ + + + + + +Using CodeIgniter Drivers : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Using CodeIgniter Drivers

+ + +

Drivers are a special type of Library that has a parent class and any number of potential child classes. Child classes have access to the parent class, but not their siblings. Drivers provide an elegant syntax in your controllers for libraries that benefit from or require being broken down into discrete classes.

+ +

Drivers are found in the system/libraries folder, in their own folder which is identically named to the parent library class. Also inside that folder is a subfolder named drivers, which contains all of the possible child class files.

+ +

To use a driver you will initialize it within a controller using the following initialization function:

+ +$this->load->driver('class name'); + +

Where class name is the name of the driver class you want to invoke. For example, to load a driver named "Some Parent" you would do this:

+ +$this->load->driver('some_parent'); + +

Methods of that class can then be invoked with:

+ +$this->some_parent->some_method(); + +

The child classes, the drivers themselves, can then be called directly through the parent class, without initializing them:

+ +$this->some_parent->child_one->some_method();
+$this->some_parent->child_two->another_method();
+ +

Creating Your Own Drivers

+ +

Please read the section of the user guide that discusses how to create your own drivers.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/environments.html b/api/user_guide/general/environments.html new file mode 100644 index 0000000..25190a5 --- /dev/null +++ b/api/user_guide/general/environments.html @@ -0,0 +1,126 @@ + + + + + +Handling Multiple Environments : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Handling Multiple Environments

+ +

+ Developers often desire different system behavior depending on whether + an application is running in a development or production + environment. For example, verbose error output is something that would + be useful while developing an application, but it may also pose a security issue when "live". +

+ +

The ENVIRONMENT Constant

+ +

+ By default, CodeIgniter comes with the environment constant set to + 'development'. At the top of index.php, you will see: +

+ + +define('ENVIRONMENT', 'development'); + + +

+ In addition to affecting some basic framework behavior (see the next section), + you may use this constant in your own development to differentiate + between which environment you are running in. +

+ +

Effects On Default Framework Behavior

+ +

+ There are some places in the CodeIgniter system where the ENVIRONMENT + constant is used. This section describes how default framework behavior is + affected. +

+ +

Error Reporting

+ +

+ Setting the ENVIRONMENT constant to a value of 'development' will + cause all PHP errors to be rendered to the browser when they occur. Conversely, + setting the constant to 'production' will disable all error output. Disabling + error reporting in production is a good security practice. +

+ +

Configuration Files

+ +

+ Optionally, you can have CodeIgniter load environment-specific + configuration files. This may be useful for managing things like differing API keys + across multiple environments. This is described in more detail in the + environment section of the Config Class documentation. +

+ +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/errors.html b/api/user_guide/general/errors.html new file mode 100644 index 0000000..6764b54 --- /dev/null +++ b/api/user_guide/general/errors.html @@ -0,0 +1,140 @@ + + + + + +Error Handling : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Error Handling

+ +

CodeIgniter lets you build error reporting into your applications using the functions described below. +In addition, it has an error logging class that permits error and debugging messages to be saved as text files.

+ +

Note: By default, CodeIgniter displays all PHP errors. You might +wish to change this behavior once your development is complete. You'll find the error_reporting() +function located at the top of your main index.php file. Disabling error reporting will NOT prevent log files +from being written if there are errors.

+ +

Unlike most systems in CodeIgniter, the error functions are simple procedural interfaces that are available +globally throughout the application. This approach permits error messages to get triggered without having to worry +about class/function scoping.

+ +

The following functions let you generate errors:

+ +

show_error('message' [, int $status_code= 500 ] )

+

This function will display the error message supplied to it using the following error template:

+

application/errors/error_general.php

+

The optional parameter $status_code determines what HTTP status code should be sent with the error.

+ +

show_404('page' [, 'log_error'])

+

This function will display the 404 error message supplied to it using the following error template:

+

application/errors/error_404.php

+ +

The function expects the string passed to it to be the file path to the page that isn't found. +Note that CodeIgniter automatically shows 404 messages if controllers are not found.

+ +

CodeIgniter automatically logs any show_404() calls. Setting the optional second parameter to FALSE will skip logging.

+ + +

log_message('level', 'message')

+ +

This function lets you write messages to your log files. You must supply one of three "levels" +in the first parameter, indicating what type of message it is (debug, error, info), with the message +itself in the second parameter. Example:

+ + +if ($some_var == "")
+{
+    log_message('error', 'Some variable did not contain a value.');
+}
+else
+{
+    log_message('debug', 'Some variable was correctly set');
+}
+
+log_message('info', 'The purpose of some variable is to provide some value.');
+
+ +

There are three message types:

+ +
    +
  1. Error Messages. These are actual errors, such as PHP errors or user errors.
  2. +
  3. Debug Messages. These are messages that assist in debugging. For example, if a class has been initialized, you could log this as debugging info.
  4. +
  5. Informational Messages. These are the lowest priority messages, simply giving information regarding some process. CodeIgniter doesn't natively generate any info messages but you may want to in your application.
  6. +
+ + +

Note: In order for the log file to actually be written, the + "logs" folder must be writable. In addition, you must set the "threshold" for logging in application/config/config.php. +You might, for example, only want error messages to be logged, and not the other two types. +If you set it to zero logging will be disabled.

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/helpers.html b/api/user_guide/general/helpers.html new file mode 100644 index 0000000..0614dcb --- /dev/null +++ b/api/user_guide/general/helpers.html @@ -0,0 +1,185 @@ + + + + + +Helper Functions : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Helper Functions

+ +

Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular +category. There are URL Helpers, that assist in creating links, there are Form Helpers +that help you create form elements, Text Helpers perform various text formatting routines, +Cookie Helpers set and read cookies, File Helpers help you deal with files, etc. +

+ +

Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. +Each helper function performs one specific task, with no dependence on other functions.

+ +

CodeIgniter does not load Helper Files by default, so the first step in using +a Helper is to load it. Once loaded, it becomes globally available in your controller and views.

+ +

Helpers are typically stored in your system/helpers, or application/helpers directory. CodeIgniter will look first in your application/helpers +directory. If the directory does not exist or the specified helper is not located there CI will instead look in your global +system/helpers folder.

+ + +

Loading a Helper

+ +

Loading a helper file is quite simple using the following function:

+ +$this->load->helper('name'); + +

Where name is the file name of the helper, without the .php file extension or the "helper" part.

+ +

For example, to load the URL Helper file, which is named url_helper.php, you would do this:

+ +$this->load->helper('url'); + +

A helper can be loaded anywhere within your controller functions (or even within your View files, although that's not a good practice), +as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available +automatically in any function, or you can load a helper in a specific function that needs it.

+ +

Note: The Helper loading function above does not return a value, so don't try to assign it to a variable. Just use it as shown.

+ + +

Loading Multiple Helpers

+ +

If you need to load more than one helper you can specify them in an array, like this:

+ +$this->load->helper( array('helper1', 'helper2', 'helper3') ); + +

Auto-loading Helpers

+ +

If you find that you need a particular helper globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. +This is done by opening the application/config/autoload.php file and adding the helper to the autoload array.

+ + +

Using a Helper

+ +

Once you've loaded the Helper File containing the function you intend to use, you'll call it the way you would a standard PHP function.

+ +

For example, to create a link using the anchor() function in one of your view files you would do this:

+ +<?php echo anchor('blog/comments', 'Click Here');?> + +

Where "Click Here" is the name of the link, and "blog/comments" is the URI to the controller/function you wish to link to.

+ +

"Extending" Helpers

+ +

To "extend" Helpers, create a file in your application/helpers/ folder with an identical name to the existing Helper, but prefixed with MY_ (this item is configurable. See below.).

+ +

If all you need to do is add some functionality to an existing helper - perhaps add a function or two, or change how a particular + helper function operates - then it's overkill to replace the entire helper with your version. In this case it's better to simply + "extend" the Helper. The term "extend" is used loosely since Helper functions are procedural and discrete and cannot be extended + in the traditional programmatic sense. Under the hood, this gives you the ability to add to the functions a Helper provides, + or to modify how the native Helper functions operate.

+ +

For example, to extend the native Array Helper you'll create a file named application/helpers/MY_array_helper.php, and add or override functions:

+ + +// any_in_array() is not in the Array Helper, so it defines a new function
+function any_in_array($needle, $haystack)
+{
+    $needle = (is_array($needle)) ? $needle : array($needle);
+
+    foreach ($needle as $item)
+    {
+        if (in_array($item, $haystack))
+        {
+            return TRUE;
+        }
+        }
+
+    return FALSE;
+}
+
+// random_element() is included in Array Helper, so it overrides the native function
+function random_element($array)
+{
+    shuffle($array);
+    return array_pop($array);
+}
+
+ +

Setting Your Own Prefix

+ +

The filename prefix for "extending" Helpers is the same used to extend libraries and Core classes. To set your own prefix, open your application/config/config.php file and look for this item:

+ +$config['subclass_prefix'] = 'MY_'; + +

Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

+ + +

Now What?

+ +

In the Table of Contents you'll find a list of all the available Helper Files. Browse each one to see what they do.

+ + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/hooks.html b/api/user_guide/general/hooks.html new file mode 100644 index 0000000..c75f45d --- /dev/null +++ b/api/user_guide/general/hooks.html @@ -0,0 +1,165 @@ + + + + + +Hooks : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Hooks - Extending the Framework Core

+ +

CodeIgniter's Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files. +When CodeIgniter runs it follows a specific execution process, diagramed in the Application Flow page. +There may be instances, however, where you'd like to cause some action to take place at a particular stage in the execution process. +For example, you might want to run a script right before your controllers get loaded, or right after, or you might want to trigger one of +your own scripts in some other location. +

+ +

Enabling Hooks

+ +

The hooks feature can be globally enabled/disabled by setting the following item in the application/config/config.php file:

+ +$config['enable_hooks'] = TRUE; + + +

Defining a Hook

+ +

Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype:

+ + +$hook['pre_controller'] = array(
+                                'class'    => 'MyClass',
+                                'function' => 'Myfunction',
+                                'filename' => 'Myclass.php',
+                                'filepath' => 'hooks',
+                                'params'   => array('beer', 'wine', 'snacks')
+                                );
+ +

Notes:
The array index correlates to the name of the particular hook point you want to +use. In the above example the hook point is pre_controller. A list of hook points is found below. +The following items should be defined in your associative hook array:

+ +
    +
  • class  The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class, leave this item blank.
  • +
  • function  The function name you wish to call.
  • +
  • filename  The file name containing your class/function.
  • +
  • filepath  The name of the directory containing your script. Note: Your script must be located in a directory INSIDE your application folder, so the file path is relative to that folder. For example, if your script is located in application/hooks, you will simply use hooks as your filepath. If your script is located in application/hooks/utilities you will use hooks/utilities as your filepath. No trailing slash.
  • +
  • params  Any parameters you wish to pass to your script. This item is optional.
  • +
+ + +

Multiple Calls to the Same Hook

+ +

If want to use the same hook point with more then one script, simply make your array declaration multi-dimensional, like this:

+ + +$hook['pre_controller'][] = array(
+                                'class'    => 'MyClass',
+                                'function' => 'Myfunction',
+                                'filename' => 'Myclass.php',
+                                'filepath' => 'hooks',
+                                'params'   => array('beer', 'wine', 'snacks')
+                                );
+
+$hook['pre_controller'][] = array(
+                                'class'    => 'MyOtherClass',
+                                'function' => 'MyOtherfunction',
+                                'filename' => 'Myotherclass.php',
+                                'filepath' => 'hooks',
+                                'params'   => array('red', 'yellow', 'blue')
+                                );
+ +

Notice the brackets after each array index:

+ +$hook['pre_controller'][] + +

This permits you to have the same hook point with multiple scripts. The order you define your array will be the execution order.

+ + +

Hook Points

+ +

The following is a list of available hook points.

+ +
    +
  • pre_system
    + Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened.
  • +
  • pre_controller
    + Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.
  • +
  • post_controller_constructor
    + Called immediately after your controller is instantiated, but prior to any method calls happening.
  • +
  • post_controller
    + Called immediately after your controller is fully executed.
  • +
  • display_override
    + Overrides the _display() function, used to send the finalized page to the web browser at the end of system execution. This permits you to + use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output()
  • +
  • cache_override
    + Enables you to call your own function instead of the _display_cache() function in the output class. This permits you to use your own cache display mechanism.
  • +
  • post_system
    + Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.
  • +
+
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/libraries.html b/api/user_guide/general/libraries.html new file mode 100644 index 0000000..6830fb0 --- /dev/null +++ b/api/user_guide/general/libraries.html @@ -0,0 +1,98 @@ + + + + + +Using CodeIgniter Libraries : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Using CodeIgniter Libraries

+ + +

All of the available libraries are located in your system/libraries folder. +In most cases, to use one of these classes involves initializing it within a controller using the following initialization function:

+ +$this->load->library('class name'); + +

Where class name is the name of the class you want to invoke. For example, to load the form validation class you would do this:

+ +$this->load->library('form_validation'); + +

Once initialized you can use it as indicated in the user guide page corresponding to that class.

+ +

Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load function.

+ +$this->load->library(array('email', 'table')); + +

Creating Your Own Libraries

+ +

Please read the section of the user guide that discusses how to create your own libraries

+ + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/managing_apps.html b/api/user_guide/general/managing_apps.html new file mode 100644 index 0000000..8f96736 --- /dev/null +++ b/api/user_guide/general/managing_apps.html @@ -0,0 +1,133 @@ + + + + + +Managing your Applications : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Managing your Applications

+ +

By default it is assumed that you only intend to use CodeIgniter to manage one application, which you will build in your +application/ directory. It is possible, however, to have multiple sets of applications that share a single +CodeIgniter installation, or even to rename or relocate your application folder.

+ +

Renaming the Application Folder

+ +

If you would like to rename your application folder you may do so as long as you open your main index.php +file and set its name using the $application_folder variable:

+ +$application_folder = "application"; + +

Relocating your Application Folder

+ +

It is possible to move your application folder to a different location on your server than your system folder. +To do so open your main index.php and set a full server path in the $application_folder variable.

+ + +$application_folder = "/Path/to/your/application"; + + +

Running Multiple Applications with one CodeIgniter Installation

+ +

If you would like to share a common CodeIgniter installation to manage several different applications simply +put all of the directories located inside your application folder into their +own sub-folder.

+ +

For example, let's say you want to create two applications, "foo" and "bar". You could structure your +application folders like this:

+ +applications/foo/
+applications/foo/config/
+applications/foo/controllers/
+applications/foo/errors/
+applications/foo/libraries/
+applications/foo/models/
+applications/foo/views/
+applications/bar/
+applications/bar/config/
+applications/bar/controllers/
+applications/bar/errors/
+applications/bar/libraries/
+applications/bar/models/
+applications/bar/views/
+ + +

To select a particular application for use requires that you open your main index.php file and set the $application_folder +variable. For example, to select the "foo" application for use you would do this:

+ +$application_folder = "applications/foo"; + +

Note:  Each of your applications will need its own index.php file which +calls the desired application. The index.php file can be named anything you want.

+ + + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/models.html b/api/user_guide/general/models.html new file mode 100644 index 0000000..4fd9984 --- /dev/null +++ b/api/user_guide/general/models.html @@ -0,0 +1,251 @@ + + + + + +Models : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Models

+ +

Models are optionally available for those who want to use a more traditional MVC approach.

+ + + + + + + +

What is a Model?

+ +

Models are PHP classes that are designed to work with information in your database. For example, let's say +you use CodeIgniter to manage a blog. You might have a model class that contains functions to insert, update, and +retrieve your blog data. Here is an example of what such a model class might look like:

+ + +class Blogmodel extends CI_Model {
+
+    var $title   = '';
+    var $content = '';
+    var $date    = '';
+
+    function __construct()
+    {
+        // Call the Model constructor
+        parent::__construct();
+    }
+    
+    function get_last_ten_entries()
+    {
+        $query = $this->db->get('entries', 10);
+        return $query->result();
+    }
+
+    function insert_entry()
+    {
+        $this->title   = $_POST['title']; // please read the below note
+        $this->content = $_POST['content'];
+        $this->date    = time();
+
+        $this->db->insert('entries', $this);
+    }
+
+    function update_entry()
+    {
+        $this->title   = $_POST['title'];
+        $this->content = $_POST['content'];
+        $this->date    = time();
+
+        $this->db->update('entries', $this, array('id' => $_POST['id']));
+    }
+
+}
+ +

Note: The functions in the above example use the Active Record database functions.

+

Note: For the sake of simplicity in this example we're using $_POST directly. This is generally bad practice, and a more common approach would be to use the Input Class $this->input->post('title')

+

Anatomy of a Model

+ +

Model classes are stored in your application/models/ folder. They can be nested within sub-folders if you +want this type of organization.

+ +

The basic prototype for a model class is this:

+ + + +class Model_name extends CI_Model {
+
+    function __construct()
+    {
+        parent::__construct();
+    }
+}
+ +

Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the name lowercase. +Make sure your class extends the base Model class.

+ +

The file name will be a lower case version of your class name. For example, if your class is this:

+ + +class User_model extends CI_Model {
+
+    function __construct()
+    {
+        parent::__construct();
+    }
+}
+ +

Your file will be this:

+ +application/models/user_model.php + + + +

Loading a Model

+ +

Your models will typically be loaded and called from within your controller functions. +To load a model you will use the following function:

+ +$this->load->model('Model_name'); + +

If your model is located in a sub-folder, include the relative path from your models folder. For example, if +you have a model located at application/models/blog/queries.php you'll load it using:

+ +$this->load->model('blog/queries'); + + +

Once loaded, you will access your model functions using an object with the same name as your class:

+ + +$this->load->model('Model_name');
+
+$this->Model_name->function(); +
+ +

If you would like your model assigned to a different object name you can specify it via the second parameter of the loading +function:

+ + + +$this->load->model('Model_name', 'fubar');
+
+$this->fubar->function(); +
+ +

Here is an example of a controller, that loads a model, then serves a view:

+ + +class Blog_controller extends CI_Controller {
+
+    function blog()
+    {
+        $this->load->model('Blog');
+
+        $data['query'] = $this->Blog->get_last_ten_entries();

+        $this->load->view('blog', $data);
+    }
+}
+ +

Auto-loading Models

+

If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload.php file and adding the model to the autoload array.

+ + +

Connecting to your Database

+ +

When a model is loaded it does NOT connect automatically to your database. The following options for connecting are available to you:

+ +
    +
  • You can connect using the standard database methods described here, either from within your Controller class or your Model class.
  • +
  • You can tell the model loading function to auto-connect by passing TRUE (boolean) via the third parameter, +and connectivity settings, as defined in your database config file will be used: + + $this->load->model('Model_name', '', TRUE); +
  • + + +
  • You can manually pass database connectivity settings via the third parameter: + + + $config['hostname'] = "localhost";
    + $config['username'] = "myusername";
    + $config['password'] = "mypassword";
    + $config['database'] = "mydatabase";
    + $config['dbdriver'] = "mysql";
    + $config['dbprefix'] = "";
    + $config['pconnect'] = FALSE;
    + $config['db_debug'] = TRUE;
    +
    + $this->load->model('Model_name', '', $config);
  • +
+ + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/profiling.html b/api/user_guide/general/profiling.html new file mode 100644 index 0000000..e333cf5 --- /dev/null +++ b/api/user_guide/general/profiling.html @@ -0,0 +1,181 @@ + + + + + +Profiling Your Application : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ + +

Profiling Your Application

+ +

The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages. +This information can be useful during development in order to help with debugging and optimization.

+ + +

Initializing the Class

+ +

Important:  This class does NOT need to be initialized. It is loaded automatically by the +Output Class if profiling is enabled as shown below.

+ +

Enabling the Profiler

+ +

To enable the profiler place the following function anywhere within your Controller functions:

+ $this->output->enable_profiler(TRUE); + +

When enabled a report will be generated and inserted at the bottom of your pages.

+ +

To disable the profiler you will use:

+ $this->output->enable_profiler(FALSE); + + +

Setting Benchmark Points

+ +

In order for the Profiler to compile and display your benchmark data you must name your mark points using specific syntax.

+ +

Please read the information on setting Benchmark points in Benchmark Class page.

+ + +

Enabling and Disabling Profiler Sections

+ +

Each section of Profiler data can be enabled or disabled by setting a corresponding config variable to TRUE or FALSE. This can be done one of two ways. First, you can set application wide defaults with the application/config/profiler.php config file.

+ + $config['config']          = FALSE;
+ $config['queries']         = FALSE;
+ +

In your controllers, you can override the defaults and config file values by calling the set_profiler_sections() method of the Output class:

+ + $sections = array(
+     'config'  => TRUE,
+     'queries' => TRUE
+     );
+
+ $this->output->set_profiler_sections($sections);
+ +

Available sections and the array key used to access them are described in the table below.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyDescriptionDefault
benchmarksElapsed time of Benchmark points and total execution timeTRUE
configCodeIgniter Config variablesTRUE
controller_infoThe Controller class and method requestedTRUE
getAny GET data passed in the requestTRUE
http_headersThe HTTP headers for the current requestTRUE
memory_usageAmount of memory consumed by the current request, in bytesTRUE
postAny POST data passed in the requestTRUE
queriesListing of all database queries executed, including execution timeTRUE
uri_stringThe URI of the current requestTRUE
query_toggle_countThe number of queries after which the query block will default to hidden.25
+ + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/quick_reference.html b/api/user_guide/general/quick_reference.html new file mode 100644 index 0000000..ac1b27e --- /dev/null +++ b/api/user_guide/general/quick_reference.html @@ -0,0 +1,77 @@ + + + + + +Quick Reference Chart : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Quick Reference Chart

+ +

For a PDF version of this chart, click here.

+ +

+ +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/requirements.html b/api/user_guide/general/requirements.html new file mode 100644 index 0000000..9691d20 --- /dev/null +++ b/api/user_guide/general/requirements.html @@ -0,0 +1,82 @@ + + + + + +Server Requirements : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Server Requirements

+ +
    +
  • PHP version 5.1.6 or newer.
  • +
  • A Database is required for most web application programming. Current supported databases are MySQL (4.1+), MySQLi, MS SQL, Postgres, Oracle, SQLite, and ODBC.
  • +
+ + + +
+ + + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/reserved_names.html b/api/user_guide/general/reserved_names.html new file mode 100644 index 0000000..34306b5 --- /dev/null +++ b/api/user_guide/general/reserved_names.html @@ -0,0 +1,128 @@ + + + + + +Reserved Names : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Reserved Names

+ +

In order to help out, CodeIgniter uses a series of functions and names in its operation. Because of this, some names cannot be used by a developer. Following is a list of reserved names that cannot be used.

+

Controller names

+

Since your controller classes will extend the main application controller you +must be careful not to name your functions identically to the ones used by that class, otherwise your local functions +will override them. The following +is a list of reserved names. Do not name your controller any of these:

+
    +
  • Controller
  • +
  • CI_Base
  • +
  • _ci_initialize
  • +
  • Default
  • +
  • index
  • +
+

Functions

+
    +
  • is_really_writable()
  • +
  • load_class()
  • +
  • get_config()
  • +
  • config_item()
  • +
  • show_error()
  • +
  • show_404()
  • +
  • log_message()
  • +
  • _exception_handler()
  • +
  • get_instance()
  • +
+

Variables

+
    +
  • $config
  • +
  • $mimes
  • +
  • $lang
  • +
+

Constants

+
    +
  • ENVIRONMENT
  • +
  • EXT
  • +
  • FCPATH
  • +
  • SELF
  • +
  • BASEPATH
  • +
  • APPPATH
  • +
  • CI_VERSION
  • +
  • FILE_READ_MODE
  • +
  • FILE_WRITE_MODE
  • +
  • DIR_READ_MODE
  • +
  • DIR_WRITE_MODE
  • +
  • FOPEN_READ
  • +
  • FOPEN_READ_WRITE
  • +
  • FOPEN_WRITE_CREATE_DESTRUCTIVE
  • +
  • FOPEN_READ_WRITE_CREATE_DESTRUCTIVE
  • +
  • FOPEN_WRITE_CREATE
  • +
  • FOPEN_READ_WRITE_CREATE
  • +
  • FOPEN_WRITE_CREATE_STRICT
  • +
  • FOPEN_READ_WRITE_CREATE_STRICT
  • +
+
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/routing.html b/api/user_guide/general/routing.html new file mode 100644 index 0000000..61fe934 --- /dev/null +++ b/api/user_guide/general/routing.html @@ -0,0 +1,171 @@ + + + + + +URI Routing : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

URI Routing

+ +

Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. +The segments in a URI normally follow this pattern:

+ +example.com/class/function/id/ + +

In some instances, however, you may want to remap this relationship so that a different class/function can be called +instead of the one corresponding to the URL.

+ +

For example, lets say you want your URLs to have this prototype:

+ +

+example.com/product/1/
+example.com/product/2/
+example.com/product/3/
+example.com/product/4/ +

+ +

Normally the second segment of the URL is reserved for the function name, but in the example above it instead has a product ID. +To overcome this, CodeIgniter allows you to remap the URI handler.

+ + +

Setting your own routing rules

+ +

Routing rules are defined in your application/config/routes.php file. In it you'll see an array called $route that +permits you to specify your own routing criteria. Routes can either be specified using wildcards or Regular Expressions

+ + +

Wildcards

+ +

A typical wildcard route might look something like this:

+ +$route['product/:num'] = "catalog/product_lookup"; + +

In a route, the array key contains the URI to be matched, while the array value contains the destination it should be re-routed to. +In the above example, if the literal word "product" is found in the first segment of the URL, and a number is found in the second segment, +the "catalog" class and the "product_lookup" method are instead used.

+ +

You can match literal values or you can use two wildcard types:

+ +

(:num) will match a segment containing only numbers.
+(:any) will match a segment containing any character. +

+ +

Note: Routes will run in the order they are defined. +Higher routes will always take precedence over lower ones.

+ +

Examples

+ +

Here are a few routing examples:

+ +$route['journals'] = "blogs"; +

A URL containing the word "journals" in the first segment will be remapped to the "blogs" class.

+ +$route['blog/joe'] = "blogs/users/34"; +

A URL containing the segments blog/joe will be remapped to the "blogs" class and the "users" method. The ID will be set to "34".

+ +$route['product/(:any)'] = "catalog/product_lookup"; +

A URL with "product" as the first segment, and anything in the second will be remapped to the "catalog" class and the "product_lookup" method.

+ +$route['product/(:num)'] = "catalog/product_lookup_by_id/$1"; +

A URL with "product" as the first segment, and a number in the second will be remapped to the "catalog" class and the "product_lookup_by_id" method passing in the match as a variable to the function.

+ +

Important: Do not use leading/trailing slashes.

+ +

Regular Expressions

+ +

If you prefer you can use regular expressions to define your routing rules. Any valid regular expression is allowed, as are back-references.

+ +

Note:  If you use back-references you must use the dollar syntax rather than the double backslash syntax.

+ +

A typical RegEx route might look something like this:

+ +$route['products/([a-z]+)/(\d+)'] = "$1/id_$2"; + +

In the above example, a URI similar to products/shirts/123 would instead call the shirts controller class and the id_123 function.

+ +

You can also mix and match wildcards with regular expressions.

+ +

Reserved Routes

+ +

There are two reserved routes:

+ +$route['default_controller'] = 'welcome'; + +

This route indicates which controller class should be loaded if the URI contains no data, which will be the case +when people load your root URL. In the above example, the "welcome" class would be loaded. You +are encouraged to always have a default route otherwise a 404 page will appear by default.

+ +$route['404_override'] = ''; + +

This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 +error page. It won't affect to the show_404() function, which will continue loading the default error_404.php file at application/errors/error_404.php.

+ +

Important:  The reserved routes must come before any wildcard or regular expression routes.

+ +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/security.html b/api/user_guide/general/security.html new file mode 100644 index 0000000..1032014 --- /dev/null +++ b/api/user_guide/general/security.html @@ -0,0 +1,164 @@ + + + + + +Security : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ +

Security

+ +

This page describes some "best practices" regarding web security, and details +CodeIgniter's internal security features.

+ + +

URI Security

+ +

CodeIgniter is fairly restrictive regarding which characters it allows in your URI strings in order to help +minimize the possibility that malicious data can be passed to your application. URIs may only contain the following: +

+ +
    +
  • Alpha-numeric text
  • +
  • Tilde: ~
  • +
  • Period: .
  • +
  • Colon: :
  • +
  • Underscore: _
  • +
  • Dash: -
  • +
+ +

Register_globals

+ +

During system initialization all global variables are unset, except those found in the $_GET, $_POST, and $_COOKIE arrays. The unsetting +routine is effectively the same as register_globals = off.

+ + +

error_reporting

+ +

+ In production environments, it is typically desirable to disable PHP's + error reporting by setting the internal error_reporting flag to a value of 0. This disables native PHP + errors from being rendered as output, which may potentially contain + sensitive information. +

+ +

+ Setting CodeIgniter's ENVIRONMENT constant in index.php to a + value of 'production' will turn off these errors. In development + mode, it is recommended that a value of 'development' is used. + More information about differentiating between environments can be found + on the Handling Environments page. +

+ +

magic_quotes_runtime

+ +

The magic_quotes_runtime directive is turned off during system initialization so that you don't have to remove slashes when +retrieving data from your database.

+ +

Best Practices

+ +

Before accepting any data into your application, whether it be POST data from a form submission, COOKIE data, URI data, +XML-RPC data, or even data from the SERVER array, you are encouraged to practice this three step approach:

+ +
    +
  1. Filter the data as if it were tainted.
  2. +
  3. Validate the data to ensure it conforms to the correct type, length, size, etc. (sometimes this step can replace step one)
  4. +
  5. Escape the data before submitting it into your database.
  6. +
+ +

CodeIgniter provides the following functions to assist in this process:

+ +
    + +
  • XSS Filtering

    + +

    CodeIgniter comes with a Cross Site Scripting filter. This filter looks for commonly +used techniques to embed malicious Javascript into your data, or other types of code that attempt to hijack cookies +or do other malicious things. The XSS Filter is described here. +

    +
  • + +
  • Validate the data

    + +

    CodeIgniter has a Form Validation Class that assists you in validating, filtering, and prepping +your data.

    +
  • + +
  • Escape all data before database insertion

    + +

    Never insert information into your database without escaping it. Please see the section that discusses +queries for more information.

    + +
  • + +
+ + + + +
+ + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/styleguide.html b/api/user_guide/general/styleguide.html new file mode 100644 index 0000000..4cd704b --- /dev/null +++ b/api/user_guide/general/styleguide.html @@ -0,0 +1,679 @@ + + + + + +Style Guide : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +

CodeIgniter User Guide Version 2.1.4

+
+ + + + + + + + + +
+ + +
+ + + +
+ + +

General Style and Syntax

+ +

The following page describes the use of coding rules adhered to when developing CodeIgniter.

+ + +

Table of Contents

+ + +
  • + +

    File Format

    +
    +

    Files should be saved with Unicode (UTF-8) encoding. The BOM + should not be used. Unlike UTF-16 and UTF-32, there's no byte order to indicate in + a UTF-8 encoded file, and the BOM can have a negative side effect in PHP of sending output, + preventing the application from being able to set its own headers. Unix line endings should + be used (LF).

    + +

    Here is how to apply these settings in some of the more common text editors. Instructions for your + text editor may vary; check your text editor's documentation.

    + +
    TextMate
    + +
      +
    1. Open the Application Preferences
    2. +
    3. Click Advanced, and then the "Saving" tab
    4. +
    5. In "File Encoding", select "UTF-8 (recommended)"
    6. +
    7. In "Line Endings", select "LF (recommended)"
    8. +
    9. Optional: Check "Use for existing files as well" if you wish to modify the line + endings of files you open to your new preference.
    10. +
    + +
    BBEdit
    + +
      +
    1. Open the Application Preferences
    2. +
    3. Select "Text Encodings" on the left.
    4. +
    5. In "Default text encoding for new documents", select "Unicode (UTF-8, no BOM)"
    6. +
    7. Optional: In "If file's encoding can't be guessed, use", select + "Unicode (UTF-8, no BOM)"
    8. +
    9. Select "Text Files" on the left.
    10. +
    11. In "Default line breaks", select "Mac OS X and Unix (LF)"
    12. +
    +
    + +

    PHP Closing Tag

    +
    +

    The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced + by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should + OMIT the closing PHP tag, and instead use a comment block to mark the end of file and it's location relative to the application root. + This allows you to still identify a file as being complete and not truncated.

    +INCORRECT: +<?php + +echo "Here's my code!"; + +?> + +CORRECT: +<?php + +echo "Here's my code!"; + +/* End of file myfile.php */ +/* Location: ./system/modules/mymodule/myfile.php */ + +
    + + +

    Class and Method Naming

    +
    +

    Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. All other class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names.

    + + INCORRECT: +class superclass +class SuperClass + +CORRECT: +class Super_class + + + class Super_class { + + function __construct() + { + + } +} + +

    Examples of improper and proper method naming:

    + + INCORRECT: +function fileproperties() // not descriptive and needs underscore separator +function fileProperties() // not descriptive and uses CamelCase +function getfileproperties() // Better! But still missing underscore separator +function getFileProperties() // uses CamelCase +function get_the_file_properties_from_the_file() // wordy + +CORRECT: +function get_file_properties() // descriptive, underscore separator, and all lowercase letters + +
    + + +

    Variable Names

    +
    +

    The guidelines for variable naming is very similar to that used for class methods. Namely, variables should contain only lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops.

    +INCORRECT: +$j = 'foo'; // single letter variables should only be used in for() loops +$Str // contains uppercase letters +$bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning +$groupid // multiple words, needs underscore separator +$name_of_last_city_used // too long + +CORRECT: +for ($j = 0; $j < 10; $j++) +$str +$buffer +$group_id +$last_city + +
    + + +

    Commenting

    +
    +

    In general, code should be commented prolifically. It not only helps describe the flow and intent of the code for less experienced programmers, but can prove invaluable when returning to your own code months down the line. There is not a required format for comments, but the following are recommended.

    + +

    DocBlock style comments preceding class and method declarations so they can be picked up by IDEs:

    + +/** + * Super Class + * + * @package Package Name + * @subpackage Subpackage + * @category Category + * @author Author Name + * @link http://example.com + */ +class Super_class { + +/** + * Encodes string for use in XML + * + * @access public + * @param string + * @return string + */ +function xml_encode($str) + +

    Use single line comments within code, leaving a blank line between large comment blocks and code.

    + +// break up the string by newlines +$parts = explode("\n", $str); + +// A longer comment that needs to give greater detail on what is +// occurring and why can use multiple single-line comments. Try to +// keep the width reasonable, around 70 characters is the easiest to +// read. Don't hesitate to link to permanent external resources +// that may provide greater detail: +// +// http://example.com/information_about_something/in_particular/ + +$parts = $this->foo($parts); + +
    + + +

    Constants

    +
    +

    Constants follow the same guidelines as do variables, except constants should always be fully uppercase. Always use CodeIgniter constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.

    +INCORRECT: +myConstant // missing underscore separator and not fully uppercase +N // no single-letter constants +S_C_VER // not descriptive +$str = str_replace('{foo}', 'bar', $str); // should use LD and RD constants + +CORRECT: +MY_CONSTANT +NEWLINE +SUPER_CLASS_VERSION +$str = str_replace(LD.'foo'.RD, 'bar', $str); + +
    + + +

    TRUE, FALSE, and NULL

    +
    +

    TRUE, FALSE, and NULL keywords should always be fully uppercase.

    +INCORRECT: +if ($foo == true) +$bar = false; +function foo($bar = null) + +CORRECT: +if ($foo == TRUE) +$bar = FALSE; +function foo($bar = NULL) +
    + + + +

    Logical Operators

    +
    +

    Use of || is discouraged as its clarity on some output devices is low (looking like the number 11 for instance). + && is preferred over AND but either are acceptable, and a space should always precede and follow !.

    +INCORRECT: +if ($foo || $bar) +if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications +if (!$foo) +if (! is_array($foo)) + +CORRECT: +if ($foo OR $bar) +if ($foo && $bar) // recommended +if ( ! $foo) +if ( ! is_array($foo)) + +
    + + + +

    Comparing Return Values and Typecasting

    +
    +

    Some PHP functions return FALSE on failure, but may also have a valid return value of "" or 0, which would evaluate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type evaluation.

    +

    Use the same stringency in returning and checking your own variables. Use === and !== as necessary. + +INCORRECT: +// If 'foo' is at the beginning of the string, strpos will return a 0, +// resulting in this conditional evaluating as TRUE +if (strpos($str, 'foo') == FALSE) + +CORRECT: +if (strpos($str, 'foo') === FALSE) + + +INCORRECT: +function build_string($str = "") +{ + if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? + { + + } +} + +CORRECT: +function build_string($str = "") +{ + if ($str === "") + { + + } +} + +

    See also information regarding typecasting, which can be quite useful. Typecasting has a slightly different effect which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables become empty strings, 0 (and other numbers) become strings of digits, and boolean TRUE becomes "1":

    + +$str = (string) $str; // cast $str as a string + +
    + + +

    Debugging Code

    +
    +

    No debugging code can be left in place for submitted add-ons unless it is commented out, i.e. no var_dump(), print_r(), die(), and exit() calls that were used while creating the add-on, unless they are commented out.

    + +// print_r($foo); +
    + + + +

    Whitespace in Files

    +
    +

    No whitespace can precede the opening PHP tag or follow the closing PHP tag. Output is buffered, so whitespace in your files can cause output to begin before CodeIgniter outputs its content, leading to errors and an inability for CodeIgniter to send proper headers. In the examples below, select the text with your mouse to reveal the incorrect whitespace.

    + +

    INCORRECT:

    + +<?php + // ...there is whitespace and a linebreak above the opening PHP tag + // as well as whitespace after the closing PHP tag +?> + +

    CORRECT:

    +<?php + // this sample has no whitespace before or after the opening and closing PHP tags +?> + +
    + + +

    Compatibility

    +
    +

    Unless specifically mentioned in your add-on's documentation, all code must be compatible with PHP version 5.1+. Additionally, do not use PHP functions that require non-default libraries to be installed unless your code contains an alternative method when the function is not available, or you implicitly document that your add-on requires said PHP libraries.

    +
    + + + +

    Class and File Names using Common Words

    +
    +

    When your class or filename is a common word, or might quite likely be identically named in another PHP script, provide a unique prefix to help prevent collision. Always realize that your end users may be running other add-ons or third party PHP scripts. Choose a prefix that is unique to your identity as a developer or company.

    + +INCORRECT: +class Email pi.email.php +class Xml ext.xml.php +class Import mod.import.php + +CORRECT: +class Pre_email pi.pre_email.php +class Pre_xml ext.pre_xml.php +class Pre_import mod.pre_import.php + +
    + + +

    Database Table Names

    +
    +

    Any tables that your add-on might use must use the 'exp_' prefix, followed by a prefix uniquely identifying you as the developer or company, and then a short descriptive table name. You do not need to be concerned about the database prefix being used on the user's installation, as CodeIgniter's database class will automatically convert 'exp_' to what is actually being used.

    + +INCORRECT: +email_addresses // missing both prefixes +pre_email_addresses // missing exp_ prefix +exp_email_addresses // missing unique prefix + +CORRECT: +exp_pre_email_addresses + + +

    NOTE: Be mindful that MySQL has a limit of 64 characters for table names. This should not be an issue as table names that would exceed this would likely have unreasonable names. For instance, the following table name exceeds this limitation by one character. Silly, no? exp_pre_email_addresses_of_registered_users_in_seattle_washington +

    + + + +

    One File per Class

    +
    +

    Use separate files for each class your add-on uses, unless the classes are closely related. An example of CodeIgniter files that contains multiple classes is the Database class file, which contains both the DB class and the DB_Cache class, and the Magpie plugin, which contains both the Magpie and Snoopy classes.

    +
    + + + +

    Whitespace

    +
    +

    Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace allows the developer looking at your code to have indentation at levels that they prefer and customize in whatever application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus, say, four space characters.

    +
    + + + +

    Line Breaks

    +
    +

    Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any case ensure that your text editor is setup to save files with Unix line breaks.

    +
    + + + +

    Code Indenting

    +
    +

    Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves, and indented at the same level as the control statement that "owns" them.

    + +INCORRECT: +function foo($bar) { + // ... +} + +foreach ($arr as $key => $val) { + // ... +} + +if ($foo == $bar) { + // ... +} else { + // ... +} + +for ($i = 0; $i < 10; $i++) + { + for ($j = 0; $j < 10; $j++) + { + // ... + } + } + +CORRECT: +function foo($bar) +{ + // ... +} + +foreach ($arr as $key => $val) +{ + // ... +} + +if ($foo == $bar) +{ + // ... +} +else +{ + // ... +} + +for ($i = 0; $i < 10; $i++) +{ + for ($j = 0; $j < 10; $j++) + { + // ... + } +} +
    + + +

    Bracket and Parenthetic Spacing

    +
    +

    In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch, while), to help distinguish them from functions and increase readability.

    + +INCORRECT: +$arr[ $foo ] = 'foo'; + +CORRECT: +$arr[$foo] = 'foo'; // no spaces around array keys + + +INCORRECT: +function foo ( $bar ) +{ + +} + +CORRECT: +function foo($bar) // no spaces around parenthesis in function declarations +{ + +} + + +INCORRECT: +foreach( $query->result() as $row ) + +CORRECT: +foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis + +
    + + + +

    Localized Text

    +
    +

    Any text that is output in the control panel should use language variables in your lang file to allow localization.

    + +INCORRECT: +return "Invalid Selection"; + +CORRECT: +return $this->lang->line('invalid_selection'); +
    + + + +

    Private Methods and Variables

    +
    +

    Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.

    + +convert_text() // public method +_convert_text() // private method +
    + + + +

    PHP Errors

    +
    +

    Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance, never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it isset().

    + +

    Make sure that while developing your add-on, error reporting is enabled for ALL users, and that display_errors is enabled in the PHP environment. You can check this setting with:

    + +if (ini_get('display_errors') == 1) +{ + exit "Enabled"; +} + +

    On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you can often enable it with:

    + +ini_set('display_errors', 1); + +

    NOTE: Setting the display_errors setting with ini_set() at runtime is not identical to having it enabled in the PHP environment. Namely, it will not have any effect if the script has fatal errors

    +
    + + + +

    Short Open Tags

    +
    +

    Always use full PHP opening tags, in case a server does not have short_open_tag enabled.

    + +INCORRECT: +<? echo $foo; ?> + +<?=$foo?> + +CORRECT: +<?php echo $foo; ?> +
    + + + +

    One Statement Per Line

    +
    +

    Never combine statements on one line.

    + +INCORRECT: +$foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag); + +CORRECT: +$foo = 'this'; +$bar = 'that'; +$bat = str_replace($foo, $bar, $bag); + +
    + + + +

    Strings

    +
    +

    Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.

    + +INCORRECT: +"My String" // no variable parsing, so no use for double quotes +"My string $foo" // needs braces +'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly + +CORRECT: +'My String' +"My string {$foo}" +"SELECT foo FROM bar WHERE baz = 'bag'" +
    + + + +

    SQL Queries

    +
    +

    MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.

    + +

    Break up long queries into multiple lines for legibility, preferably breaking for each clause.

    + +INCORRECT: +// keywords are lowercase and query is too long for +// a single line (... indicates continuation of line) +$query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses +...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100"); + +CORRECT: +$query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz + FROM exp_pre_email_addresses + WHERE foo != 'oof' + AND baz != 'zab' + ORDER BY foobaz + LIMIT 5, 100"); +
    + + + +

    Default Function Arguments

    +
    +

    Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and provides common fallback values which can save a few lines of code. Example:

    + +function foo($bar = '', $baz = FALSE) +
    + + + +
  • + + + + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/urls.html b/api/user_guide/general/urls.html new file mode 100644 index 0000000..9493eb3 --- /dev/null +++ b/api/user_guide/general/urls.html @@ -0,0 +1,151 @@ + + + + + +CodeIgniter URLs : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    CodeIgniter URLs

    + +

    By default, URLs in CodeIgniter are designed to be search-engine and human friendly. Rather than using the standard "query string" +approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based approach:

    + +example.com/news/article/my_article + +

    Note: Query string URLs can be optionally enabled, as described below.

    + +

    URI Segments

    + +

    The segments in the URL, in following with the Model-View-Controller approach, usually represent:

    + +example.com/class/function/ID + +
      +
    1. The first segment represents the controller class that should be invoked.
    2. +
    3. The second segment represents the class function, or method, that should be called.
    4. +
    5. The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
    6. +
    + +

    The URI Class and the URL Helper +contain functions that make it easy to work with your URI data. In addition, your URLs can be remapped using the +URI Routing feature for more flexibility.

    + + + +

    Removing the index.php file

    + +

    By default, the index.php file will be included in your URLs:

    + +example.com/index.php/news/article/my_article + +

    You can easily remove this file by using a .htaccess file with some simple rules. Here is an example + of such a file, using the "negative" method in which everything is redirected except the specified items:

    + +RewriteEngine on
    +RewriteCond $1 !^(index\.php|images|robots\.txt)
    +RewriteRule ^(.*)$ /index.php/$1 [L]
    + +

    In the above example, any HTTP request other than those for index.php, images, and robots.txt is treated as +a request for your index.php file.

    + + +

    Adding a URL Suffix

    + +

    In your config/config.php file you can specify a suffix that will be added to all URLs generated +by CodeIgniter. For example, if a URL is this:

    + +example.com/index.php/products/view/shoes + +

    You can optionally add a suffix, like .html, making the page appear to be of a certain type:

    + +example.com/index.php/products/view/shoes.html + + +

    Enabling Query Strings

    + +

    In some cases you might prefer to use query strings URLs:

    + +index.php?c=products&m=view&id=345 + +

    CodeIgniter optionally supports this capability, which can be enabled in your application/config.php file. If you +open your config file you'll see these items:

    + +$config['enable_query_strings'] = FALSE;
    +$config['controller_trigger'] = 'c';
    +$config['function_trigger'] = 'm';
    + +

    If you change "enable_query_strings" to TRUE this feature will become active. Your controllers and functions will then +be accessible using the "trigger" words you've set to invoke your controllers and methods:

    + +index.php?c=controller&m=method + +

    Please note: If you are using query strings you will have to build your own URLs, rather than utilizing +the URL helpers (and other helpers that generate URLs, like some of the form helpers) as these are designed to work with +segment based URLs.

    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/general/views.html b/api/user_guide/general/views.html new file mode 100644 index 0000000..c4dd6c6 --- /dev/null +++ b/api/user_guide/general/views.html @@ -0,0 +1,274 @@ + + + + + +Views : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Views

    + +

    A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. +In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type +of hierarchy.

    + +

    Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the +traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers page +you should do so before continuing.

    + +

    Using the example controller you created in the controller page, let's add a view to it.

    + +

    Creating a View

    + +

    Using your text editor, create a file called blogview.php, and put this in it:

    + + + +

    Then save the file in your application/views/ folder.

    + +

    Loading a View

    + +

    To load a particular view file you will use the following function:

    + +$this->load->view('name'); + +

    Where name is the name of your view file. Note: The .php file extension does not need to be specified unless you use something other than .php.

    + + +

    Now, open the controller file you made earlier called blog.php, and replace the echo statement with the view loading function:

    + + + + + +

    If you visit your site using the URL you did earlier you should see your new view. The URL was similar to this:

    + +example.com/index.php/blog/ + +

    Loading multiple views

    +

    CodeIgniter will intelligently handle multiple calls to $this->load->view from within a controller. If more than one call happens they will be appended together. For example, you may wish to have a header view, a menu view, a content view, and a footer view. That might look something like this:

    +

    <?php
    +
    +class Page extends CI_Controller {

    + +    function index()
    +   {
    +      $data['page_title'] = 'Your title';
    +      $this->load->view('header');
    +      $this->load->view('menu');
    +      $this->load->view('content', $data);
    +      $this->load->view('footer');
    +   }
    +
    +}
    + ?>

    +

    In the example above, we are using "dynamically added data", which you will see below.

    +

    Storing Views within Sub-folders

    +

    Your view files can also be stored within sub-folders if you prefer that type of organization. When doing so you will need +to include the folder name loading the view. Example:

    + +$this->load->view('folder_name/file_name'); + + +

    Adding Dynamic Data to the View

    + +

    Data is passed from the controller to the view by way of an array or an object in the second +parameter of the view loading function. Here is an example using an array:

    + +$data = array(
    +               'title' => 'My Title',
    +               'heading' => 'My Heading',
    +               'message' => 'My Message'
    +          );
    +
    +$this->load->view('blogview', $data);
    + +

    And here's an example using an object:

    + +$data = new Someclass();
    +$this->load->view('blogview', $data);
    + +

    Note: If you use an object, the class variables will be turned into array elements.

    + + +

    Let's try it with your controller file. Open it add this code:

    + + + + +

    Now open your view file and change the text to variables that correspond to the array keys in your data:

    + + + + +

    Then load the page at the URL you've been using and you should see the variables replaced.

    + +

    Creating Loops

    + +

    The data array you pass to your view files is not limited to simple variables. You can +pass multi dimensional arrays, which can be looped to generate multiple rows. For example, if you +pull data from your database it will typically be in the form of a multi-dimensional array.

    + +

    Here's a simple example. Add this to your controller:

    + + + + +

    Now open your view file and create a loop:

    + + + +

    Note: You'll notice that in the example above we are using PHP's alternative syntax. If you +are not familiar with it you can read about it here.

    + +

    Returning views as data

    + +

    There is a third optional parameter lets you change the behavior of the function so that it returns data as a string +rather than sending it to your browser. This can be useful if you want to process the data in some way. If you +set the parameter to true (boolean) it will return data. The default behavior is false, which sends it +to your browser. Remember to assign it to a variable if you want the data returned:

    + +$string = $this->load->view('myfile', '', true); + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/array_helper.html b/api/user_guide/helpers/array_helper.html new file mode 100644 index 0000000..6b0f215 --- /dev/null +++ b/api/user_guide/helpers/array_helper.html @@ -0,0 +1,170 @@ + + + + + +Array Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Array Helper

    + +

    The Array Helper file contains functions that assist in working with arrays.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('array'); + +

    The following functions are available:

    + +

    element()

    + +

    Lets you fetch an item from an array. The function tests whether the array index is set and whether it has a value. If +a value exists it is returned. If a value does not exist it returns FALSE, or whatever you've specified as the default value via the third parameter. Example:

    + + +$array = array('color' => 'red', 'shape' => 'round', 'size' => '');
    +
    +// returns "red"
    +echo element('color', $array);
    +
    +// returns NULL
    +echo element('size', $array, NULL); +
    + + +

    random_element()

    + +

    Takes an array as input and returns a random element from it. Usage example:

    + +$quotes = array(
    +            "I find that the harder I work, the more luck I seem to have. - Thomas Jefferson",
    +            "Don't stay in bed, unless you can make money in bed. - George Burns",
    +            "We didn't lose the game; we just ran out of time. - Vince Lombardi",
    +            "If everything seems under control, you're not going fast enough. - Mario Andretti",
    +            "Reality is merely an illusion, albeit a very persistent one. - Albert Einstein",
    +            "Chance favors the prepared mind - Louis Pasteur"
    +            );
    +
    +echo random_element($quotes);
    + + +

    elements()

    + +

    Lets you fetch a number of items from an array. The function tests whether each of the array indices is set. If an index does not exist +it is set to FALSE, or whatever you've specified as the default value via the third parameter. Example:

    + + +$array = array(
    +    'color' => 'red',
    +    'shape' => 'round',
    +    'radius' => '10',
    +    'diameter' => '20'
    +);
    +
    +$my_shape = elements(array('color', 'shape', 'height'), $array);
    +
    + +

    The above will return the following array:

    + + +array(
    +    'color' => 'red',
    +    'shape' => 'round',
    +    'height' => FALSE
    +); +
    + +

    You can set the third parameter to any default value you like:

    + + +$my_shape = elements(array('color', 'shape', 'height'), $array, NULL);
    +
    + +

    The above will return the following array:

    + + +array(
    +    'color' => 'red',
    +    'shape' => 'round',
    +    'height' => NULL
    +); +
    + +

    This is useful when sending the $_POST array to one of your Models. This prevents users from +sending additional POST data to be entered into your tables:

    + + +$this->load->model('post_model');
    +
    +$this->post_model->update(elements(array('id', 'title', 'content'), $_POST)); +
    + +

    This ensures that only the id, title and content fields are sent to be updated.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/captcha_helper.html b/api/user_guide/helpers/captcha_helper.html new file mode 100644 index 0000000..b67d9dd --- /dev/null +++ b/api/user_guide/helpers/captcha_helper.html @@ -0,0 +1,195 @@ + + + + + +CAPTCHA Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    CAPTCHA Helper

    + +

    The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('captcha'); + +

    The following functions are available:

    + +

    create_captcha($data)

    + +

    Takes an array of information to generate the CAPTCHA as input and creates the image to your specifications, returning an array of associative data about the image.

    + +[array]
    +(
    +  'image' => IMAGE TAG
    +  'time' => TIMESTAMP (in microtime)
    +  'word' => CAPTCHA WORD
    +)
    + +

    The "image" is the actual image tag: +<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />

    + +

    The "time" is the micro timestamp used as the image name without the file + extension. It will be a number like this: 1139612155.3422

    + +

    The "word" is the word that appears in the captcha image, which if not + supplied to the function, will be a random string.

    + +

    Using the CAPTCHA helper

    + +

    Once loaded you can generate a captcha like this:

    + +$vals = array(
    +    'word' => 'Random word',
    +    'img_path' => './captcha/',
    +    'img_url' => 'http://example.com/captcha/',
    +    'font_path' => './path/to/fonts/texb.ttf',
    +    'img_width' => '150',
    +    'img_height' => 30,
    +    'expiration' => 7200
    +    );
    +
    +$cap = create_captcha($vals);
    +echo $cap['image'];
    + +
      +
    • The captcha function requires the GD image library.
    • +
    • Only the img_path and img_url are required.
    • +
    • If a "word" is not supplied, the function will generate a random + ASCII string. You might put together your own word library that + you can draw randomly from.
    • +
    • If you do not specify a path to a TRUE TYPE font, the native ugly GD + font will be used.
    • +
    • The "captcha" folder must be writable (666, or 777)
    • +
    • The "expiration" (in seconds) signifies how long an image will + remain in the captcha folder before it will be deleted. The default + is two hours.
    • +
    + +

    Adding a Database

    + +

    In order for the captcha function to prevent someone from submitting, you will need + to add the information returned from create_captcha() function to your database. + Then, when the data from the form is submitted by the user you will need to verify + that the data exists in the database and has not expired.

    + +

    Here is a table prototype:

    + +CREATE TABLE captcha (
    + captcha_id bigint(13) unsigned NOT NULL auto_increment,
    + captcha_time int(10) unsigned NOT NULL,
    + ip_address varchar(16) default '0' NOT NULL,
    + word varchar(20) NOT NULL,
    + PRIMARY KEY `captcha_id` (`captcha_id`),
    + KEY `word` (`word`)
    +);
    + +

    Here is an example of usage with a database. On the page where the CAPTCHA will be shown you'll have something like this:

    + +$this->load->helper('captcha');
    +$vals = array(
    +    'img_path' => './captcha/',
    +    'img_url' => 'http://example.com/captcha/'
    +    );
    +
    +$cap = create_captcha($vals);
    +
    +$data = array(
    +    'captcha_time' => $cap['time'],
    +    'ip_address' => $this->input->ip_address(),
    +    'word' => $cap['word']
    +    );
    +
    +$query = $this->db->insert_string('captcha', $data);
    +$this->db->query($query);
    +
    +echo 'Submit the word you see below:';
    +echo $cap['image'];
    +echo '<input type="text" name="captcha" value="" />';
    + +

    Then, on the page that accepts the submission you'll have something like this:

    + +// First, delete old captchas
    +$expiration = time()-7200; // Two hour limit
    +$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
    +
    +// Then see if a captcha exists:
    +$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
    +$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
    +$query = $this->db->query($sql, $binds);
    +$row = $query->row();
    +
    +if ($row->count == 0)
    +{
    +    echo "You must submit the word that appears in the image";
    +}
    + +
    + + + + + + + diff --git a/api/user_guide/helpers/cookie_helper.html b/api/user_guide/helpers/cookie_helper.html new file mode 100644 index 0000000..236f0c4 --- /dev/null +++ b/api/user_guide/helpers/cookie_helper.html @@ -0,0 +1,107 @@ + + + + + +Cookie Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Cookie Helper

    + +

    The Cookie Helper file contains functions that assist in working with cookies.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('cookie'); + +

    The following functions are available:

    + +

    set_cookie()

    + +

    This helper function gives you view file friendly syntax to set browser cookies. Refer to the Input class for a description of use, as this function is an alias to $this->input->set_cookie().

    + +

    get_cookie()

    + +

    This helper function gives you view file friendly syntax to get browser cookies. Refer to the Input class for a description of use, as this function is an alias to $this->input->cookie().

    + + +

    delete_cookie()

    + +

    Lets you delete a cookie. Unless you've set a custom path or other values, only the name of the cookie is needed:

    + +delete_cookie("name"); + +

    This function is otherwise identical to set_cookie(), except that it does not have the value and expiration parameters. You can submit an array +of values in the first parameter or you can set discrete parameters.

    + +delete_cookie($name, $domain, $path, $prefix) + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/date_helper.html b/api/user_guide/helpers/date_helper.html new file mode 100644 index 0000000..70193b1 --- /dev/null +++ b/api/user_guide/helpers/date_helper.html @@ -0,0 +1,408 @@ + + + + + +Date Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Date Helper

    + +

    The Date Helper file contains functions that help you work with dates.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('date'); + + +

    The following functions are available:

    + +

    now()

    + +

    Returns the current time as a Unix timestamp, referenced either to your server's local time or GMT, based on the "time reference" +setting in your config file. If you do not intend to set your master time reference to GMT (which you'll typically do if you +run a site that lets each user set their own timezone settings) there is no benefit to using this function over PHP's time() function. +

    + + + + +

    mdate()

    + +

    This function is identical to PHPs date() function, except that it lets you +use MySQL style date codes, where each code letter is preceded with a percent sign: %Y %m %d etc.

    + +

    The benefit of doing dates this way is that you don't have to worry about escaping any characters that +are not date codes, as you would normally have to do with the date() function. Example:

    + +$datestring = "Year: %Y Month: %m Day: %d - %h:%i %a";
    +$time = time();
    +
    +echo mdate($datestring, $time);
    + +

    If a timestamp is not included in the second parameter the current time will be used.

    + + +

    standard_date()

    + +

    Lets you generate a date string in one of several standardized formats. Example:

    + + +$format = 'DATE_RFC822';
    +$time = time();
    +
    +echo standard_date($format, $time); +
    + +

    The first parameter must contain the format, the second parameter must contain the date as a Unix timestamp.

    + +

    Supported formats:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ConstantDescriptionExample
    DATE_ATOMAtom2005-08-15T16:13:03+0000
    DATE_COOKIEHTTP CookiesSun, 14 Aug 2005 16:13:03 UTC
    DATE_ISO8601ISO-86012005-08-14T16:13:03+00:00
    DATE_RFC822RFC 822Sun, 14 Aug 05 16:13:03 UTC
    DATE_RFC850RFC 850Sunday, 14-Aug-05 16:13:03 UTC
    DATE_RFC1036RFC 1036Sunday, 14-Aug-05 16:13:03 UTC
    DATE_RFC1123RFC 1123Sun, 14 Aug 2005 16:13:03 UTC
    DATE_RFC2822RFC 2822Sun, 14 Aug 2005 16:13:03 +0000
    DATE_RSSRSSSun, 14 Aug 2005 16:13:03 UTC
    DATE_W3CWorld Wide Web Consortium2005-08-14T16:13:03+0000
    + +

    local_to_gmt()

    + +

    Takes a Unix timestamp as input and returns it as GMT. Example:

    + +$now = time();
    +
    +$gmt = local_to_gmt($now);
    + + +

    gmt_to_local()

    + +

    Takes a Unix timestamp (referenced to GMT) as input, and converts it to a localized timestamp based on the +timezone and Daylight Saving time submitted. Example:

    + + +$timestamp = '1140153693';
    +$timezone = 'UM8';
    +$daylight_saving = TRUE;
    +
    +echo gmt_to_local($timestamp, $timezone, $daylight_saving);
    + +

    Note: For a list of timezones see the reference at the bottom of this page.

    + +

    mysql_to_unix()

    + +

    Takes a MySQL Timestamp as input and returns it as Unix. Example:

    + +$mysql = '20061124092345';
    +
    +$unix = mysql_to_unix($mysql);
    + + +

    unix_to_human()

    + +

    Takes a Unix timestamp as input and returns it in a human readable format with this prototype:

    + +YYYY-MM-DD HH:MM:SS AM/PM + +

    This can be useful if you need to display a date in a form field for submission.

    + +

    The time can be formatted with or without seconds, and it can be set to European or US format. If only +the timestamp is submitted it will return the time without seconds formatted for the U.S. Examples:

    + +$now = time();
    +
    +echo unix_to_human($now); // U.S. time, no seconds
    +
    +echo unix_to_human($now, TRUE, 'us'); // U.S. time with seconds
    +
    +echo unix_to_human($now, TRUE, 'eu'); // Euro time with seconds
    + + +

    human_to_unix()

    + +

    The opposite of the above function. Takes a "human" time as input and returns it as Unix. This function is +useful if you accept "human" formatted dates submitted via a form. Returns FALSE (boolean) if +the date string passed to it is not formatted as indicated above. Example:

    + +$now = time();
    +
    +$human = unix_to_human($now);
    +
    +$unix = human_to_unix($human);
    + + + + + +

    timespan()

    + +

    Formats a unix timestamp so that is appears similar to this:

    + +1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes + +

    The first parameter must contain a Unix timestamp. The second parameter must contain a +timestamp that is greater that the first timestamp. If the second parameter empty, the current time will be used. The most common purpose +for this function is to show how much time has elapsed from some point in time in the past to now. Example:

    + +$post_date = '1079621429';
    +$now = time();
    +
    +echo timespan($post_date, $now);
    + +

    Note: The text generated by this function is found in the following language file: language/<your_lang>/date_lang.php

    + + +

    days_in_month()

    + +

    Returns the number of days in a given month/year. Takes leap years into account. Example:

    +echo days_in_month(06, 2005); + +

    If the second parameter is empty, the current year will be used.

    +

    timezones()

    +

    Takes a timezone reference (for a list of valid timezones, see the "Timezone Reference" below) and returns the number of hours offset from UTC.

    +

    echo timezones('UM5');

    +

    This function is useful when used with timezone_menu().

    +

    timezone_menu()

    +

    Generates a pull-down menu of timezones, like this one:

    + +
    + +
    + +

    This menu is useful if you run a membership site in which your users are allowed to set their local timezone value.

    + +

    The first parameter lets you set the "selected" state of the menu. For example, to set Pacific time as the default you will do this:

    + +echo timezone_menu('UM8'); + +

    Please see the timezone reference below to see the values of this menu.

    + +

    The second parameter lets you set a CSS class name for the menu.

    + +

    Note: The text contained in the menu is found in the following language file: language/<your_lang>/date_lang.php

    + + + +

    Timezone Reference

    + +

    The following table indicates each timezone and its location.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Time ZoneLocation
    UM12(UTC - 12:00) Enitwetok, Kwajalien
    UM11(UTC - 11:00) Nome, Midway Island, Samoa
    UM10(UTC - 10:00) Hawaii
    UM9(UTC - 9:00) Alaska
    UM8(UTC - 8:00) Pacific Time
    UM7(UTC - 7:00) Mountain Time
    UM6(UTC - 6:00) Central Time, Mexico City
    UM5(UTC - 5:00) Eastern Time, Bogota, Lima, Quito
    UM4(UTC - 4:00) Atlantic Time, Caracas, La Paz
    UM25(UTC - 3:30) Newfoundland
    UM3(UTC - 3:00) Brazil, Buenos Aires, Georgetown, Falkland Is.
    UM2(UTC - 2:00) Mid-Atlantic, Ascention Is., St Helena
    UM1(UTC - 1:00) Azores, Cape Verde Islands
    UTC(UTC) Casablanca, Dublin, Edinburgh, London, Lisbon, Monrovia
    UP1(UTC + 1:00) Berlin, Brussels, Copenhagen, Madrid, Paris, Rome
    UP2(UTC + 2:00) Kaliningrad, South Africa, Warsaw
    UP3(UTC + 3:00) Baghdad, Riyadh, Moscow, Nairobi
    UP25(UTC + 3:30) Tehran
    UP4(UTC + 4:00) Adu Dhabi, Baku, Muscat, Tbilisi
    UP35(UTC + 4:30) Kabul
    UP5(UTC + 5:00) Islamabad, Karachi, Tashkent
    UP45(UTC + 5:30) Bombay, Calcutta, Madras, New Delhi
    UP6(UTC + 6:00) Almaty, Colomba, Dhaka
    UP7(UTC + 7:00) Bangkok, Hanoi, Jakarta
    UP8(UTC + 8:00) Beijing, Hong Kong, Perth, Singapore, Taipei
    UP9(UTC + 9:00) Osaka, Sapporo, Seoul, Tokyo, Yakutsk
    UP85(UTC + 9:30) Adelaide, Darwin
    UP10(UTC + 10:00) Melbourne, Papua New Guinea, Sydney, Vladivostok
    UP11(UTC + 11:00) Magadan, New Caledonia, Solomon Islands
    UP12(UTC + 12:00) Auckland, Wellington, Fiji, Marshall Island
    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/directory_helper.html b/api/user_guide/helpers/directory_helper.html new file mode 100644 index 0000000..6fb6540 --- /dev/null +++ b/api/user_guide/helpers/directory_helper.html @@ -0,0 +1,143 @@ + + + + + +Directory Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + + +
    + + +
    + + + +
    + + +

    Directory Helper

    + +

    The Directory Helper file contains functions that assist in working with directories.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('directory'); + +

    The following functions are available:

    + +

    directory_map('source directory')

    + +

    This function reads the directory path specified in the first parameter +and builds an array representation of it and all its contained files. Example:

    + +$map = directory_map('./mydirectory/'); + +

    Note: Paths are almost always relative to your main index.php file.

    + +

    Sub-folders contained within the directory will be mapped as well. If you wish to control the recursion depth, +you can do so using the second parameter (integer). A depth of 1 will only map the top level directory:

    + +$map = directory_map('./mydirectory/', 1); + +

    By default, hidden files will not be included in the returned array. To override this behavior, +you may set a third parameter to true (boolean):

    + +$map = directory_map('./mydirectory/', FALSE, TRUE); + +

    Each folder name will be an array index, while its contained files will be numerically indexed. +Here is an example of a typical array:

    + +Array
    +(
    +   [libraries] => Array
    +   (
    +       [0] => benchmark.html
    +       [1] => config.html
    +       [database] => Array
    +       (
    +             [0] => active_record.html
    +             [1] => binds.html
    +             [2] => configuration.html
    +             [3] => connecting.html
    +             [4] => examples.html
    +             [5] => fields.html
    +             [6] => index.html
    +             [7] => queries.html
    +        )
    +       [2] => email.html
    +       [3] => file_uploading.html
    +       [4] => image_lib.html
    +       [5] => input.html
    +       [6] => language.html
    +       [7] => loader.html
    +       [8] => pagination.html
    +       [9] => uri.html
    +)
    + + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/download_helper.html b/api/user_guide/helpers/download_helper.html new file mode 100644 index 0000000..80d4868 --- /dev/null +++ b/api/user_guide/helpers/download_helper.html @@ -0,0 +1,112 @@ + + + + + +Download Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + + +
    + + +
    + + + +
    + + +

    Download Helper

    + +

    The Download Helper lets you download data to your desktop.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('download'); + +

    The following functions are available:

    + +

    force_download('filename', 'data')

    + +

    Generates server headers which force data to be downloaded to your desktop. Useful with file downloads. +The first parameter is the name you want the downloaded file to be named, the second parameter is the file data. +Example:

    + + +$data = 'Here is some text!';
    +$name = 'mytext.txt';
    +
    +force_download($name, $data); +
    + +

    If you want to download an existing file from your server you'll need to read the file into a string:

    + + +$data = file_get_contents("/path/to/photo.jpg"); // Read the file's contents
    +$name = 'myphoto.jpg';
    +
    +force_download($name, $data); +
    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/email_helper.html b/api/user_guide/helpers/email_helper.html new file mode 100644 index 0000000..1ec8015 --- /dev/null +++ b/api/user_guide/helpers/email_helper.html @@ -0,0 +1,102 @@ + + + + + +Email Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + + +
    + + +
    + + + +
    + + +

    Email Helper

    + +

    The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see CodeIgniter's Email Class.

    + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +

    $this->load->helper('email');

    + +

    The following functions are available:

    + +

    valid_email('email')

    + +

    Checks if an email is a correctly formatted email. Note that is doesn't actually prove the email will recieve mail, simply that it is a validly formed address.

    +

    It returns TRUE/FALSE

    + $this->load->helper('email');
    +
    +if (valid_email('email@somesite.com'))
    +{
    +    echo 'email is valid';
    +}
    +else
    +{
    +    echo 'email is not valid';
    +}
    +

    send_email('recipient', 'subject', 'message')

    +

    Sends an email using PHP's native mail() function. For a more robust email solution, see CodeIgniter's Email Class.

    +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/file_helper.html b/api/user_guide/helpers/file_helper.html new file mode 100644 index 0000000..5eb258e --- /dev/null +++ b/api/user_guide/helpers/file_helper.html @@ -0,0 +1,179 @@ + + + + + +File Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    File Helper

    + +

    The File Helper file contains functions that assist in working with files.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('file'); + +

    The following functions are available:

    + +

    read_file('path')

    + +

    Returns the data contained in the file specified in the path. Example:

    + +$string = read_file('./path/to/file.php'); + +

    The path can be a relative or full server path. Returns FALSE (boolean) on failure.

    + +

    Note: The path is relative to your main site index.php file, NOT your controller or view files. +CodeIgniter uses a front controller so paths are always relative to the main site index.

    + +

    If your server is running an open_basedir restriction this function +might not work if you are trying to access a file above the calling script.

    + +

    write_file('path', $data)

    + +

    Writes data to the file specified in the path. If the file does not exist the function will create it. Example:

    + + +$data = 'Some file data';
    +
    +if ( ! write_file('./path/to/file.php', $data))
    +{
    +     echo 'Unable to write the file';
    +}
    +else
    +{
    +     echo 'File written!';
    +}
    + +

    You can optionally set the write mode via the third parameter:

    + +write_file('./path/to/file.php', $data, 'r+'); + +

    The default mode is wb. Please see the PHP user guide for mode options.

    + +

    Note: In order for this function to write data to a file its file permissions must be set such that it is writable (666, 777, etc.). +If the file does not already exist, the directory containing it must be writable.

    + +

    Note: The path is relative to your main site index.php file, NOT your controller or view files. +CodeIgniter uses a front controller so paths are always relative to the main site index.

    + +

    delete_files('path')

    + +

    Deletes ALL files contained in the supplied path. Example:

    +delete_files('./path/to/directory/'); + +

    If the second parameter is set to true, any directories contained within the supplied root path will be deleted as well. Example:

    + +delete_files('./path/to/directory/', TRUE); + +

    Note: The files must be writable or owned by the system in order to be deleted.

    + +

    get_filenames('path/to/directory/')

    + +

    Takes a server path as input and returns an array containing the names of all files contained within it. The file path +can optionally be added to the file names by setting the second parameter to TRUE.

    + +

    get_dir_file_info('path/to/directory/', $top_level_only = TRUE)

    + +

    Reads the specified directory and builds an array containing the filenames, filesize, dates, and permissions. Sub-folders contained within the specified path are only read if forced + by sending the second parameter, $top_level_only to FALSE, as this can be an intensive operation.

    + +

    get_file_info('path/to/file', $file_information)

    + +

    Given a file and path, returns the name, path, size, date modified. Second parameter allows you to explicitly declare what information you want returned; options are: name, server_path, size, date, readable, writable, executable, fileperms. Returns FALSE if the file cannot be found.

    + +

    Note: The "writable" uses the PHP function is_writable() which is known to have issues on the IIS webserver. Consider using fileperms instead, which returns information from PHP's fileperms() function.

    +

    get_mime_by_extension('file')

    + +

    Translates a file extension into a mime type based on config/mimes.php. Returns FALSE if it can't determine the type, or open the mime config file.

    +

    +$file = "somefile.png";
    +echo $file . ' is has a mime type of ' . get_mime_by_extension($file);
    +

    +

    Note: This is not an accurate way of determining file mime types, and is here strictly as a convenience. It should not be used for security.

    + +

    symbolic_permissions($perms)

    + +

    Takes numeric permissions (such as is returned by fileperms() and returns standard symbolic notation of file permissions.

    + +echo symbolic_permissions(fileperms('./index.php'));
    +
    +// -rw-r--r--
    + +

    octal_permissions($perms)

    + +

    Takes numeric permissions (such as is returned by fileperms() and returns a three character octal notation of file permissions.

    + +echo octal_permissions(fileperms('./index.php'));
    +
    +// 644
    + +
    + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/form_helper.html b/api/user_guide/helpers/form_helper.html new file mode 100644 index 0000000..2268d45 --- /dev/null +++ b/api/user_guide/helpers/form_helper.html @@ -0,0 +1,484 @@ + + + + + +Form Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Form Helper

    + +

    The Form Helper file contains functions that assist in working with forms.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('form'); + +

    The following functions are available:

    + + + +

    form_open()

    + +

    Creates an opening form tag with a base URL built from your config preferences. It will optionally let you +add form attributes and hidden input fields, and will always add the attribute accept-charset based on the charset value in your config file.

    + +

    The main benefit of using this tag rather than hard coding your own HTML is that it permits your site to be more portable +in the event your URLs ever change.

    + +

    Here's a simple example:

    + +echo form_open('email/send'); + +

    The above example would create a form that points to your base URL plus the "email/send" URI segments, like this:

    + +<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/email/send" /> + +

    Adding Attributes

    + +

    Attributes can be added by passing an associative array to the second parameter, like this:

    + + +$attributes = array('class' => 'email', 'id' => 'myform');
    +
    +echo form_open('email/send', $attributes);
    + +

    The above example would create a form similar to this:

    + +<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/email/send"  class="email"  id="myform" /> + +

    Adding Hidden Input Fields

    + +

    Hidden fields can be added by passing an associative array to the third parameter, like this:

    + + +$hidden = array('username' => 'Joe', 'member_id' => '234');
    +
    +echo form_open('email/send', '', $hidden);
    + +

    The above example would create a form similar to this:

    + +<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/email/send">
    +<input type="hidden" name="username" value="Joe" />
    +<input type="hidden" name="member_id" value="234" />
    + + +

    form_open_multipart()

    + +

    This function is absolutely identical to the form_open() tag above except that it adds a multipart attribute, +which is necessary if you would like to use the form to upload files with.

    + +

    form_hidden()

    + +

    Lets you generate hidden input fields. You can either submit a name/value string to create one field:

    + +form_hidden('username', 'johndoe');
    +
    +// Would produce:

    +<input type="hidden" name="username" value="johndoe" />
    + +

    Or you can submit an associative array to create multiple fields:

    + +$data = array(
    +              'name'  => 'John Doe',
    +              'email' => 'john@example.com',
    +              'url'   => 'http://example.com'
    +            );
    +
    +echo form_hidden($data);
    +
    +// Would produce:

    +<input type="hidden" name="name" value="John Doe" />
    +<input type="hidden" name="email" value="john@example.com" />
    +<input type="hidden" name="url" value="http://example.com" />
    + + + + +

    form_input()

    + +

    Lets you generate a standard text input field. You can minimally pass the field name and value in the first +and second parameter:

    + +echo form_input('username', 'johndoe'); + +

    Or you can pass an associative array containing any data you wish your form to contain:

    + +$data = array(
    +              'name'        => 'username',
    +              'id'          => 'username',
    +              'value'       => 'johndoe',
    +              'maxlength'   => '100',
    +              'size'        => '50',
    +              'style'       => 'width:50%',
    +            );
    +
    +echo form_input($data);
    +
    +// Would produce:

    +<input type="text" name="username" id="username" value="johndoe" maxlength="100" size="50" style="width:50%" />
    + +

    If you would like your form to contain some additional data, like Javascript, you can pass it as a string in the +third parameter:

    + +$js = 'onClick="some_function()"';
    +
    +echo form_input('username', 'johndoe', $js);
    + +

    form_password()

    + +

    This function is identical in all respects to the form_input() function above +except that is sets it as a "password" type.

    + +

    form_upload()

    + +

    This function is identical in all respects to the form_input() function above +except that is sets it as a "file" type, allowing it to be used to upload files.

    + +

    form_textarea()

    + +

    This function is identical in all respects to the form_input() function above +except that it generates a "textarea" type. Note: Instead of the "maxlength" and "size" attributes in the above +example, you will instead specify "rows" and "cols".

    + + +

    form_dropdown()

    + +

    Lets you create a standard drop-down field. The first parameter will contain the name of the field, +the second parameter will contain an associative array of options, and the third parameter will contain the +value you wish to be selected. You can also pass an array of multiple items through the third parameter, and CodeIgniter will create a multiple select for you. Example:

    + +$options = array(
    +                  'small'  => 'Small Shirt',
    +                  'med'    => 'Medium Shirt',
    +                  'large'   => 'Large Shirt',
    +                  'xlarge' => 'Extra Large Shirt',
    +                );
    +
    +$shirts_on_sale = array('small', 'large');
    +
    +echo form_dropdown('shirts', $options, 'large');
    +
    +// Would produce:
    +
    +<select name="shirts">
    +<option value="small">Small Shirt</option>
    +<option value="med">Medium Shirt</option>
    +<option value="large" selected="selected">Large Shirt</option>
    +<option value="xlarge">Extra Large Shirt</option>
    +</select>
    +
    +echo form_dropdown('shirts', $options, $shirts_on_sale);
    +
    +// Would produce:
    +
    +<select name="shirts" multiple="multiple">
    +<option value="small" selected="selected">Small Shirt</option>
    +<option value="med">Medium Shirt</option>
    +<option value="large" selected="selected">Large Shirt</option>
    +<option value="xlarge">Extra Large Shirt</option>
    +</select>
    + + +

    If you would like the opening <select> to contain additional data, like an id attribute or JavaScript, you can pass it as a string in the +fourth parameter:

    + +$js = 'id="shirts" onChange="some_function();"';
    +
    +echo form_dropdown('shirts', $options, 'large', $js);
    + +

    If the array passed as $options is a multidimensional array, form_dropdown() will produce an <optgroup> with the array key as the label.

    + +

    form_multiselect()

    + +

    Lets you create a standard multiselect field. The first parameter will contain the name of the field, +the second parameter will contain an associative array of options, and the third parameter will contain the +value or values you wish to be selected. The parameter usage is identical to using form_dropdown() above, +except of course that the name of the field will need to use POST array syntax, e.g. foo[].

    + + +

    form_fieldset()

    + +

    Lets you generate fieldset/legend fields.

    +echo form_fieldset('Address Information');
    +echo "<p>fieldset content here</p>\n";
    +echo form_fieldset_close(); +
    +
    +// Produces
    +<fieldset> +
    +<legend>Address Information</legend> +
    +<p>form content here</p> +
    +</fieldset>
    +

    Similar to other functions, you can submit an associative array in the second parameter if you prefer to set additional attributes.

    +

    $attributes = array('id' => 'address_info', 'class' => 'address_info');
    + echo form_fieldset('Address Information', $attributes);
    +echo "<p>fieldset content here</p>\n";
    +echo form_fieldset_close();
    +
    +// Produces
    +<fieldset id="address_info" class="address_info">
    +<legend>Address Information</legend>
    +<p>form content here</p>
    +</fieldset>

    +

    form_fieldset_close()

    +

    Produces a closing </fieldset> tag. The only advantage to using this function is it permits you to pass data to it + which will be added below the tag. For example:

    +$string = "</div></div>";
    +
    +echo form_fieldset_close($string);
    +
    +// Would produce:
    +</fieldset>
    +</div></div>
    +

    form_checkbox()

    +

    Lets you generate a checkbox field. Simple example:

    +echo form_checkbox('newsletter', 'accept', TRUE);
    +
    +// Would produce:
    +
    +<input type="checkbox" name="newsletter" value="accept" checked="checked" />
    +

    The third parameter contains a boolean TRUE/FALSE to determine whether the box should be checked or not.

    +

    Similar to the other form functions in this helper, you can also pass an array of attributes to the function:

    + +$data = array(
    +    'name'        => 'newsletter',
    +    'id'          => 'newsletter',
    +    'value'       => 'accept',
    +    'checked'     => TRUE,
    +    'style'       => 'margin:10px',
    +    );
    +
    +echo form_checkbox($data);
    +
    +// Would produce:

    +<input type="checkbox" name="newsletter" id="newsletter" value="accept" checked="checked" style="margin:10px" />
    + +

    As with other functions, if you would like the tag to contain additional data, like JavaScript, you can pass it as a string in the +fourth parameter:

    + +$js = 'onClick="some_function()"';
    +
    + echo form_checkbox('newsletter', 'accept', TRUE, $js)
    + + +

    form_radio()

    +

    This function is identical in all respects to the form_checkbox() function above except that is sets it as a "radio" type.

    + + +

    form_submit()

    + +

    Lets you generate a standard submit button. Simple example:

    +echo form_submit('mysubmit', 'Submit Post!');
    +
    +// Would produce:
    +
    +<input type="submit" name="mysubmit" value="Submit Post!" />
    +

    Similar to other functions, you can submit an associative array in the first parameter if you prefer to set your own attributes. + The third parameter lets you add extra data to your form, like JavaScript.

    +

    form_label()

    +

    Lets you generate a <label>. Simple example:

    +echo form_label('What is your Name', 'username');
    +
    +// Would produce: +
    +<label for="username">What is your Name</label>
    +

    Similar to other functions, you can submit an associative array in the third parameter if you prefer to set additional attributes.

    +

    $attributes = array(
    +    'class' => 'mycustomclass',
    +    'style' => 'color: #000;',
    +);
    + echo form_label('What is your Name', 'username', $attributes);
    +
    +// Would produce:
    +<label for="username" class="mycustomclass" style="color: #000;">What is your Name</label>

    +

    form_reset()

    + +

    Lets you generate a standard reset button. Use is identical to form_submit().

    + +

    form_button()

    + +

    Lets you generate a standard button element. You can minimally pass the button name and content in the first and second parameter:

    + +echo form_button('name','content');
    +
    +// Would produce
    +<button name="name" type="button">Content</button> +
    + +Or you can pass an associative array containing any data you wish your form to contain: + +$data = array(
    +    'name' => 'button',
    +    'id' => 'button',
    +    'value' => 'true',
    +    'type' => 'reset',
    +    'content' => 'Reset'
    +);
    +
    +echo form_button($data);
    +
    +// Would produce:
    +<button name="button" id="button" value="true" type="reset">Reset</button> +
    + +If you would like your form to contain some additional data, like JavaScript, you can pass it as a string in the third parameter: + +$js = 'onClick="some_function()"';

    +echo form_button('mybutton', 'Click Me', $js); +
    + + +

    form_close()

    + +

    Produces a closing </form> tag. The only advantage to using this function is it permits you to pass data to it +which will be added below the tag. For example:

    + +$string = "</div></div>";
    +
    +echo form_close($string);
    +
    +// Would produce:
    +
    +</form>
    +</div></div>
    + + + + + +

    form_prep()

    + +

    Allows you to safely use HTML and characters such as quotes within form elements without breaking out of the form. Consider this example:

    + +$string = 'Here is a string containing "quoted" text.';
    +
    +<input type="text" name="myform" value="$string" />
    + +

    Since the above string contains a set of quotes it will cause the form to break. +The form_prep function converts HTML so that it can be used safely:

    + +<input type="text" name="myform" value="<?php echo form_prep($string); ?>" /> + +

    Note: If you use any of the form helper functions listed in this page the form +values will be prepped automatically, so there is no need to call this function. Use it only if you are +creating your own form elements.

    + + +

    set_value()

    + +

    Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. +The second (optional) parameter allows you to set a default value for the form. Example:

    + +<input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" /> + +

    The above form will show "0" when loaded for the first time.

    + +

    set_select()

    + +

    If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter +must contain the name of the select menu, the second parameter must contain the value of +each item, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).

    + +

    Example:

    + + +<select name="myselect">
    +<option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
    +<option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
    +<option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
    +</select> +
    + + +

    set_checkbox()

    + +

    Permits you to display a checkbox in the state it was submitted. The first parameter +must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE). Example:

    + +<input type="checkbox" name="mycheck" value="1" <?php echo set_checkbox('mycheck', '1'); ?> />
    +<input type="checkbox" name="mycheck" value="2" <?php echo set_checkbox('mycheck', '2'); ?> />
    + + +

    set_radio()

    + +

    Permits you to display radio buttons in the state they were submitted. This function is identical to the set_checkbox() function above.

    + +<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
    +<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />
    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/html_helper.html b/api/user_guide/helpers/html_helper.html new file mode 100644 index 0000000..b594e25 --- /dev/null +++ b/api/user_guide/helpers/html_helper.html @@ -0,0 +1,390 @@ + + + + + +HTML Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    HTML Helper

    + +

    The HTML Helper file contains functions that assist in working with HTML.

    + + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('html'); + +

    The following functions are available:

    + +

    br()

    +

    Generates line break tags (<br />) based on the number you submit. Example:

    +echo br(3); +

    The above would produce: <br /><br /><br />

    + +

    heading()

    +

    Lets you create HTML <h1> tags. The first parameter will contain the data, the +second the size of the heading. Example:

    +echo heading('Welcome!', 3); +

    The above would produce: <h3>Welcome!</h3>

    + +

    Additionally, in order to add attributes to the heading tag such as HTML classes, ids or inline styles, a third parameter is available.

    +echo heading('Welcome!', 3, 'class="pink"') +

    The above code produces: <h3 class="pink">Welcome!<<h3>

    + + +

    img()

    +

    Lets you create HTML <img /> tags. The first parameter contains the image source. Example:

    +echo img('images/picture.jpg');
    +// gives <img src="http://site.com/images/picture.jpg" />
    +

    There is an optional second parameter that is a TRUE/FALSE value that specifics if the src should have the page specified by $config['index_page'] added to the address it creates. Presumably, this would be if you were using a media controller.

    +

    echo img('images/picture.jpg', TRUE);
    +// gives <img src="http://site.com/index.php/images/picture.jpg" alt="" />

    +

    Additionally, an associative array can be passed to the img() function for complete control over all attributes and values. If an alt attribute is not provided, CodeIgniter will generate an empty string.

    +

    $image_properties = array(
    +           'src' => 'images/picture.jpg',
    +           'alt' => 'Me, demonstrating how to eat 4 slices of pizza at one time',
    +           'class' => 'post_images',
    +           'width' => '200',
    +           'height' => '200',
    +           'title' => 'That was quite a night',
    +           'rel' => 'lightbox',
    + );
    +
    + img($image_properties);
    + // <img src="http://site.com/index.php/images/picture.jpg" alt="Me, demonstrating how to eat 4 slices of pizza at one time" class="post_images" width="200" height="200" title="That was quite a night" rel="lightbox" />

    + +

    link_tag()

    +

    Lets you create HTML <link /> tags. This is useful for stylesheet links, as well as other links. The parameters are href, with optional rel, type, title, media and index_page. index_page is a TRUE/FALSE value that specifics if the href should have the page specified by $config['index_page'] added to the address it creates. +echo link_tag('css/mystyles.css');
    +// gives <link href="http://site.com/css/mystyles.css" rel="stylesheet" type="text/css" />

    +

    Further examples:

    + + + echo link_tag('favicon.ico', 'shortcut icon', 'image/ico');
    + // <link href="http://site.com/favicon.ico" rel="shortcut icon" type="image/ico" /> +
    +
    + echo link_tag('feed', 'alternate', 'application/rss+xml', 'My RSS Feed');
    + // <link href="http://site.com/feed" rel="alternate" type="application/rss+xml" title="My RSS Feed" />
    +

    Additionally, an associative array can be passed to the link() function for complete control over all attributes and values.

    +

    + $link = array(
    +           'href' => 'css/printer.css',
    +           'rel' => 'stylesheet',
    +           'type' => 'text/css',
    +           'media' => 'print'
    + );
    +
    + echo link_tag($link);
    + // <link href="http://site.com/css/printer.css" rel="stylesheet" type="text/css" media="print" />

    + +

    nbs()

    +

    Generates non-breaking spaces (&nbsp;) based on the number you submit. Example:

    +echo nbs(3); +

    The above would produce: &nbsp;&nbsp;&nbsp;

    + +

    ol()  and  ul()

    + +

    Permits you to generate ordered or unordered HTML lists from simple or multi-dimensional arrays. Example:

    + + +$this->load->helper('html');
    +
    +$list = array(
    +            'red',
    +            'blue',
    +            'green',
    +            'yellow'
    +            );
    +
    +$attributes = array(
    +                    'class' => 'boldlist',
    +                    'id'    => 'mylist'
    +                    );
    +
    +echo ul($list, $attributes);
    +
    + +

    The above code will produce this:

    + + +<ul class="boldlist" id="mylist">
    +  <li>red</li>
    +  <li>blue</li>
    +  <li>green</li>
    +  <li>yellow</li>
    +</ul> +
    + +

    Here is a more complex example, using a multi-dimensional array:

    + + +$this->load->helper('html');
    +
    +$attributes = array(
    +                    'class' => 'boldlist',
    +                    'id'    => 'mylist'
    +                    );
    +
    +$list = array(
    +            'colors' => array(
    +                                'red',
    +                                'blue',
    +                                'green'
    +                            ),
    +            'shapes' => array(
    +                                'round',
    +                                'square',
    +                                'circles' => array(
    +                                                    'ellipse',
    +                                                    'oval',
    +                                                    'sphere'
    +                                                    )
    +                            ),
    +            'moods'    => array(
    +                                'happy',
    +                                'upset' => array(
    +                                                    'defeated' => array(
    +                                                                        'dejected',
    +                                                                        'disheartened',
    +                                                                        'depressed'
    +                                                                        ),
    +                                                    'annoyed',
    +                                                    'cross',
    +                                                    'angry'
    +                                                )
    +                            )
    +            );
    +
    +
    +echo ul($list, $attributes);
    + +

    The above code will produce this:

    + + +<ul class="boldlist" id="mylist">
    +  <li>colors
    +    <ul>
    +      <li>red</li>
    +      <li>blue</li>
    +      <li>green</li>
    +    </ul>
    +  </li>
    +  <li>shapes
    +    <ul>
    +      <li>round</li>
    +      <li>suare</li>
    +      <li>circles
    +        <ul>
    +          <li>elipse</li>
    +          <li>oval</li>
    +          <li>sphere</li>
    +        </ul>
    +      </li>
    +    </ul>
    +  </li>
    +  <li>moods
    +    <ul>
    +      <li>happy</li>
    +      <li>upset
    +        <ul>
    +          <li>defeated
    +            <ul>
    +              <li>dejected</li>
    +              <li>disheartened</li>
    +              <li>depressed</li>
    +            </ul>
    +          </li>
    +          <li>annoyed</li>
    +          <li>cross</li>
    +          <li>angry</li>
    +        </ul>
    +      </li>
    +    </ul>
    +  </li>
    +</ul> +
    + + + +

    meta()

    + +

    Helps you generate meta tags. You can pass strings to the function, or simple arrays, or multidimensional ones. Examples:

    + + +echo meta('description', 'My Great site');
    +// Generates: <meta name="description" content="My Great Site" />
    +

    + +echo meta('Content-type', 'text/html; charset=utf-8', 'equiv'); // Note the third parameter. Can be "equiv" or "name"
    +// Generates: <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    + +

    + +echo meta(array('name' => 'robots', 'content' => 'no-cache'));
    +// Generates: <meta name="robots" content="no-cache" />
    + +

    + +$meta = array(
    +        array('name' => 'robots', 'content' => 'no-cache'),
    +        array('name' => 'description', 'content' => 'My Great Site'),
    +        array('name' => 'keywords', 'content' => 'love, passion, intrigue, deception'),
    +        array('name' => 'robots', 'content' => 'no-cache'),
    +        array('name' => 'Content-type', 'content' => 'text/html; charset=utf-8', 'type' => 'equiv')
    +    );
    +
    +echo meta($meta); +
    +// Generates:
    +// <meta name="robots" content="no-cache" />
    +// <meta name="description" content="My Great Site" />
    +// <meta name="keywords" content="love, passion, intrigue, deception" />
    +// <meta name="robots" content="no-cache" />
    +// <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> +
    + + +

    doctype()

    + +

    Helps you generate document type declarations, or DTD's. XHTML 1.0 Strict is used by default, but many doctypes are available.

    + + +echo doctype();
    +// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    +
    +echo doctype('html4-trans');
    +// <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +
    + +

    The following is a list of doctype choices. These are configurable, and pulled from application/config/doctypes.php

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    DoctypeOptionResult
    XHTML 1.1doctype('xhtml11')<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    XHTML 1.0 Strictdoctype('xhtml1-strict')<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    XHTML 1.0 Transitionaldoctype('xhtml1-trans')<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    XHTML 1.0 Framesetdoctype('xhtml1-frame')<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
    HTML 5doctype('html5')<!DOCTYPE html>
    HTML 4 Strictdoctype('html4-strict')<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    HTML 4 Transitionaldoctype('html4-trans')<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    HTML 4 Framesetdoctype('html4-frame')<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/inflector_helper.html b/api/user_guide/helpers/inflector_helper.html new file mode 100644 index 0000000..e044b34 --- /dev/null +++ b/api/user_guide/helpers/inflector_helper.html @@ -0,0 +1,151 @@ + + + + + +Inflector Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Inflector Helper

    + +

    The Inflector Helper file contains functions that permits you to change words to plural, singular, camel case, etc.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('inflector'); + +

    The following functions are available:

    + + +

    singular()

    + +

    Changes a plural word to singular. Example:

    + + +$word = "dogs";
    +echo singular($word); // Returns "dog" +
    + + +

    plural()

    + +

    Changes a singular word to plural. Example:

    + + +$word = "dog";
    +echo plural($word); // Returns "dogs" +
    + + +

    To force a word to end with "es" use a second "true" argument.

    + $word = "pass";
    +echo plural($word, TRUE); // Returns "passes"
    + +

    camelize()

    +

    Changes a string of words separated by spaces or underscores to camel case. Example:

    + + +$word = "my_dog_spot";
    +echo camelize($word); // Returns "myDogSpot" +
    + + +

    underscore()

    + +

    Takes multiple words separated by spaces and underscores them. Example:

    + + +$word = "my dog spot";
    +echo underscore($word); // Returns "my_dog_spot" +
    + + +

    humanize()

    + +

    Takes multiple words separated by underscores and adds spaces between them. Each word is capitalized. Example:

    + + +$word = "my_dog_spot";
    +echo humanize($word); // Returns "My Dog Spot" +
    + + + + + + + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/language_helper.html b/api/user_guide/helpers/language_helper.html new file mode 100644 index 0000000..2c7df78 --- /dev/null +++ b/api/user_guide/helpers/language_helper.html @@ -0,0 +1,98 @@ + + + + + +Language Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + + +
    + + +
    + + + +
    + + +

    Language Helper

    + +

    The Language Helper file contains functions that assist in working with language files.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('language'); + +

    The following functions are available:

    + +

    lang('language line', 'element id')

    + +

    This function returns a line of text from a loaded language file with simplified syntax + that may be more desirable for view files than calling $this->lang->line(). + The optional second parameter will also output a form label for you. Example:

    + +echo lang('language_key', 'form_item_id');
    +// becomes <label for="form_item_id">language_key</label>
    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/number_helper.html b/api/user_guide/helpers/number_helper.html new file mode 100644 index 0000000..c3e4e46 --- /dev/null +++ b/api/user_guide/helpers/number_helper.html @@ -0,0 +1,113 @@ + + + + + +Number Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Number Helper

    + +

    The Number Helper file contains functions that help you work with numeric data.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('number'); + +

    The following functions are available:

    + + +

    byte_format()

    + +

    Formats a numbers as bytes, based on size, and adds the appropriate suffix. Examples:

    + + +echo byte_format(456); // Returns 456 Bytes
    +echo byte_format(4567); // Returns 4.5 KB
    +echo byte_format(45678); // Returns 44.6 KB
    +echo byte_format(456789); // Returns 447.8 KB
    +echo byte_format(3456789); // Returns 3.3 MB
    +echo byte_format(12345678912345); // Returns 1.8 GB
    +echo byte_format(123456789123456789); // Returns 11,228.3 TB +
    + +

    An optional second parameter allows you to set the precision of the result.

    + + +echo byte_format(45678, 2); // Returns 44.61 KB + + +

    +Note: +The text generated by this function is found in the following language file: language//number_lang.php +

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/path_helper.html b/api/user_guide/helpers/path_helper.html new file mode 100644 index 0000000..1a5850e --- /dev/null +++ b/api/user_guide/helpers/path_helper.html @@ -0,0 +1,106 @@ + + + + + +Path Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Path Helper

    + +

    The Path Helper file contains functions that permits you to work with file paths on the server.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('path'); + +

    The following functions are available:

    + + +

    set_realpath()

    + +

    Checks to see if the path exists. This function will return a server path without symbolic links or relative directory structures. An optional second argument will cause an error to be triggered if the path cannot be resolved.

    + +$directory = '/etc/passwd';
    +echo set_realpath($directory);
    +// returns "/etc/passwd"
    +
    +$non_existent_directory = '/path/to/nowhere';
    +echo set_realpath($non_existent_directory, TRUE);
    +// returns an error, as the path could not be resolved +

    +echo set_realpath($non_existent_directory, FALSE);
    +// returns "/path/to/nowhere" + + + +
    +

     

    +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/security_helper.html b/api/user_guide/helpers/security_helper.html new file mode 100644 index 0000000..297800f --- /dev/null +++ b/api/user_guide/helpers/security_helper.html @@ -0,0 +1,132 @@ + + + + + +Security Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Security Helper

    + +

    The Security Helper file contains security related functions.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('security'); + +

    The following functions are available:

    + + +

    xss_clean()

    + +

    Provides Cross Site Script Hack filtering. This function is an alias to the one in the +Input class. More info can be found there.

    + + +

    sanitize_filename()

    + +

    Provides protection against directory traversal. This function is an alias to the one in the +Security class. More info can be found there.

    + + +

    do_hash()

    + +

    Permits you to create SHA1 or MD5 one way hashes suitable for encrypting passwords. Will create SHA1 by default. Examples:

    + + +$str = do_hash($str); // SHA1
    +
    +$str = do_hash($str, 'md5'); // MD5 +
    + +

    Note: This function was formerly named dohash(), which has been deprecated in favour of do_hash().

    + + + +

    strip_image_tags()

    + +

    This is a security function that will strip image tags from a string. It leaves the image URL as plain text.

    + +$string = strip_image_tags($string); + + +

    encode_php_tags()

    + +

    This is a security function that converts PHP tags to entities. Note: If you use the XSS filtering function it does this automatically.

    + +$string = encode_php_tags($string); + + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/smiley_helper.html b/api/user_guide/helpers/smiley_helper.html new file mode 100644 index 0000000..3153b70 --- /dev/null +++ b/api/user_guide/helpers/smiley_helper.html @@ -0,0 +1,215 @@ + + + + + +Smiley Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Smiley Helper

    + +

    The Smiley Helper file contains functions that let you manage smileys (emoticons).

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('smiley'); + +

    Overview

    + +

    The Smiley helper has a renderer that takes plain text simileys, like :-) and turns +them into a image representation, like smile!

    + +

    It also lets you display a set of smiley images that when clicked will be inserted into a form field. +For example, if you have a blog that allows user commenting you can show the smileys next to the comment form. +Your users can click a desired smiley and with the help of some JavaScript it will be placed into the form field.

    + + + +

    Clickable Smileys Tutorial

    + +

    Here is an example demonstrating how you might create a set of clickable smileys next to a form field. This example +requires that you first download and install the smiley images, then create a controller and the View as described.

    + +

    Important: Before you begin, please download the smiley images and put them in +a publicly accessible place on your server. This helper also assumes you have the smiley replacement array located at +application/config/smileys.php

    + + +

    The Controller

    + +

    In your application/controllers/ folder, create a file called smileys.php and place the code below in it.

    + +

    Important: Change the URL in the get_clickable_smileys() function below so that it points to +your smiley folder.

    + +

    You'll notice that in addition to the smiley helper we are using the Table Class.

    + + + +

    In your application/views/ folder, create a file called smiley_view.php and place this code in it:

    + + + + +

    When you have created the above controller and view, load it by visiting http://www.example.com/index.php/smileys/

    + + +

    Field Aliases

    + +

    When making changes to a view it can be inconvenient to have the field id in the controller. To work around this, +you can give your smiley links a generic name that will be tied to a specific id in your view.

    +$image_array = get_smiley_links("http://example.com/images/smileys/", "comment_textarea_alias"); + +

    To map the alias to the field id, pass them both into the smiley_js function:

    +$image_array = smiley_js("comment_textarea_alias", "comments"); + + +

    Function Reference

    + +

    get_clickable_smileys()

    + +

    Returns an array containing your smiley images wrapped in a clickable link. You must supply the URL to your smiley folder +and a field id or field alias.

    + +$image_array = get_smiley_links("http://example.com/images/smileys/", "comment"); +

    Note: Usage of this function without the second parameter, in combination with js_insert_smiley has been deprecated.

    + + +

    smiley_js()

    + +

    Generates the JavaScript that allows the images to be clicked and inserted into a form field. +If you supplied an alias instead of an id when generating your smiley links, you need to pass the +alias and corresponding form id into the function. +This function is designed to be placed into the <head> area of your web page.

    + +<?php echo smiley_js(); ?> +

    Note: This function replaces js_insert_smiley, which has been deprecated.

    + + +

    parse_smileys()

    + +

    Takes a string of text as input and replaces any contained plain text smileys into the image +equivalent. The first parameter must contain your string, the second must contain the URL to your smiley folder:

    + + +$str = 'Here are some simileys: :-) ;-)'; + +$str = parse_smileys($str, "http://example.com/images/smileys/"); + +echo $str; + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/string_helper.html b/api/user_guide/helpers/string_helper.html new file mode 100644 index 0000000..e1f31b8 --- /dev/null +++ b/api/user_guide/helpers/string_helper.html @@ -0,0 +1,189 @@ + + + + + +String Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    String Helper

    + +

    The String Helper file contains functions that assist in working with strings.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('string'); + +

    The following functions are available:

    + +

    random_string()

    + +

    Generates a random string based on the type and length you specify. Useful for creating passwords or generating random hashes.

    + +

    The first parameter specifies the type of string, the second parameter specifies the length. The following choices are available:

    + + alpha, alunum, numeric, nozero, unique, md5, encrypt and sha1 +
      +
    • alpha:  A string with lower and uppercase letters only.
    • +
    • alnum:  Alpha-numeric string with lower and uppercase characters.
    • +
    • numeric:  Numeric string.
    • +
    • nozero:  Numeric string with no zeros.
    • +
    • unique:  Encrypted with MD5 and uniqid(). Note: The length parameter is not available for this type. + Returns a fixed length 32 character string.
    • +
    • sha1:  An encrypted random number based on do_hash() from the security helper.
    • +
    + +

    Usage example:

    + +echo random_string('alnum', 16); + + +

    increment_string()

    + +

    Increments a string by appending a number to it or increasing the number. Useful for creating "copies" or a file or duplicating database content which has unique titles or slugs.

    + +

    Usage example:

    + +echo increment_string('file', '_'); // "file_1"
    +echo increment_string('file', '-', 2); // "file-2"
    +echo increment_string('file-4'); // "file-5"
    + + +

    alternator()

    + +

    Allows two or more items to be alternated between, when cycling through a loop. Example:

    + +for ($i = 0; $i < 10; $i++)
    +{
    +    echo alternator('string one', 'string two');
    +}
    +
    + +

    You can add as many parameters as you want, and with each iteration of your loop the next item will be returned.

    + +for ($i = 0; $i < 10; $i++)
    +{
    +    echo alternator('one', 'two', 'three', 'four', 'five');
    +}
    +
    + +

    Note: To use multiple separate calls to this function simply call the function with no arguments to re-initialize.

    + + + +

    repeater()

    +

    Generates repeating copies of the data you submit. Example:

    +$string = "\n";
    +echo repeater($string, 30);
    + +

    The above would generate 30 newlines.

    +

    reduce_double_slashes()

    +

    Converts double slashes in a string to a single slash, except those found in http://. Example:

    +$string = "http://example.com//index.php";
    +echo reduce_double_slashes($string); // results in "http://example.com/index.php"
    +

    trim_slashes()

    +

    Removes any leading/trailing slashes from a string. Example:
    +
    + $string = "/this/that/theother/";
    +echo trim_slashes($string); // results in this/that/theother

    + + +

    reduce_multiples()

    +

    Reduces multiple instances of a particular character occuring directly after each other. Example:

    + +$string="Fred, Bill,, Joe, Jimmy";
    +$string=reduce_multiples($string,","); //results in "Fred, Bill, Joe, Jimmy" +
    +

    The function accepts the following parameters: +reduce_multiples(string: text to search in, string: character to reduce, boolean: whether to remove the character from the front and end of the string) + +The first parameter contains the string in which you want to reduce the multiplies. The second parameter contains the character you want to have reduced. +The third parameter is FALSE by default; if set to TRUE it will remove occurences of the character at the beginning and the end of the string. Example: + + +$string=",Fred, Bill,, Joe, Jimmy,";
    +$string=reduce_multiples($string, ", ", TRUE); //results in "Fred, Bill, Joe, Jimmy" +
    +

    + +

    quotes_to_entities()

    +

    Converts single and double quotes in a string to the corresponding HTML entities. Example:

    +$string="Joe's \"dinner\"";
    +$string=quotes_to_entities($string); //results in "Joe&#39;s &quot;dinner&quot;" +
    + +

    strip_quotes()

    +

    Removes single and double quotes from a string. Example:

    +$string="Joe's \"dinner\"";
    +$string=strip_quotes($string); //results in "Joes dinner" +
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/text_helper.html b/api/user_guide/helpers/text_helper.html new file mode 100644 index 0000000..2816077 --- /dev/null +++ b/api/user_guide/helpers/text_helper.html @@ -0,0 +1,211 @@ + + + + + +Text Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Text Helper

    + +

    The Text Helper file contains functions that assist in working with text.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('text'); + +

    The following functions are available:

    + + +

    word_limiter()

    + +

    Truncates a string to the number of words specified. Example:

    + + +$string = "Here is a nice text string consisting of eleven words.";
    +
    +$string = word_limiter($string, 4);

    + +// Returns: Here is a nice… +
    + +

    The third parameter is an optional suffix added to the string. By default it adds an ellipsis.

    + + +

    character_limiter()

    + +

    Truncates a string to the number of characters specified. It maintains the integrity +of words so the character count may be slightly more or less then what you specify. Example:

    + + +$string = "Here is a nice text string consisting of eleven words.";
    +
    +$string = character_limiter($string, 20);

    + +// Returns: Here is a nice text string… +
    + +

    The third parameter is an optional suffix added to the string, if undeclared this helper uses an ellipsis.

    + + + +

    ascii_to_entities()

    + +

    Converts ASCII values to character entities, including high ASCII and MS Word characters that can cause problems when used in a web page, +so that they can be shown consistently regardless of browser settings or stored reliably in a database. +There is some dependence on your server's supported character sets, so it may not be 100% reliable in all cases, but for the most +part it should correctly identify characters outside the normal range (like accented characters). Example:

    + +$string = ascii_to_entities($string); + + +

    entities_to_ascii()

    + +

    This function does the opposite of the previous one; it turns character entities back into ASCII.

    + +

    convert_accented_characters()

    + +

    Transliterates high ASCII characters to low ASCII equivalents, useful when non-English characters need to be used where only standard ASCII characters are safely used, for instance, in URLs.

    + +$string = convert_accented_characters($string); + +

    This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

    + +

    word_censor()

    + +

    Enables you to censor words within a text string. The first parameter will contain the original string. The +second will contain an array of words which you disallow. The third (optional) parameter can contain a replacement value +for the words. If not specified they are replaced with pound signs: ####. Example:

    + + +$disallowed = array('darn', 'shucks', 'golly', 'phooey');
    +
    +$string = word_censor($string, $disallowed, 'Beep!');
    + + +

    highlight_code()

    + +

    Colorizes a string of code (PHP, HTML, etc.). Example:

    + +$string = highlight_code($string); + +

    The function uses PHP's highlight_string() function, so the colors used are the ones specified in your php.ini file.

    + + +

    highlight_phrase()

    + +

    Will highlight a phrase within a text string. The first parameter will contain the original string, the second will +contain the phrase you wish to highlight. The third and fourth parameters will contain the opening/closing HTML tags +you would like the phrase wrapped in. Example:

    + + +$string = "Here is a nice text string about nothing in particular.";
    +
    +$string = highlight_phrase($string, "nice text", '<span style="color:#990000">', '</span>'); +
    + +

    The above text returns:

    + +

    Here is a nice text string about nothing in particular.

    + + + +

    word_wrap()

    + +

    Wraps text at the specified character count while maintaining complete words. Example:

    + +$string = "Here is a simple string of text that will help us demonstrate this function.";
    +
    +echo word_wrap($string, 25);
    +
    +// Would produce:
    +
    +Here is a simple string
    +of text that will help
    +us demonstrate this
    +function
    + +

    ellipsize()

    + +

    This function will strip tags from a string, split it at a defined maximum length, and insert an ellipsis.

    +

    The first parameter is the string to ellipsize, the second is the number of characters in the final string. The third parameter is where in the string the ellipsis should appear from 0 - 1, left to right. For example. a value of 1 will place the ellipsis at the right of the string, .5 in the middle, and 0 at the left.

    +

    An optional forth parameter is the kind of ellipsis. By default, &hellip; will be inserted.

    + +$str = 'this_string_is_entirely_too_long_and_might_break_my_design.jpg';
    +
    +echo ellipsize($str, 32, .5);
    + +Produces: + +this_string_is_e…ak_my_design.jpg + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/typography_helper.html b/api/user_guide/helpers/typography_helper.html new file mode 100644 index 0000000..d072ed1 --- /dev/null +++ b/api/user_guide/helpers/typography_helper.html @@ -0,0 +1,112 @@ + + + + + +Typography Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Typography Helper

    + +

    The Typography Helper file contains functions that help your format text in semantically relevant ways.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('typography'); + +

    The following functions are available:

    + + +

    auto_typography()

    + +

    Formats text so that it is semantically and typographically correct HTML. Please see the Typography Class for more info.

    + +

    Usage example:

    + +$string = auto_typography($string); + +

    Note: Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. +If you choose to use this function you may want to consider +caching your pages.

    + + +

    nl2br_except_pre()

    + +

    Converts newlines to <br /> tags unless they appear within <pre> tags. +This function is identical to the native PHP nl2br() function, except that it ignores <pre> tags.

    + +

    Usage example:

    + +$string = nl2br_except_pre($string); + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/url_helper.html b/api/user_guide/helpers/url_helper.html new file mode 100644 index 0000000..fd58b43 --- /dev/null +++ b/api/user_guide/helpers/url_helper.html @@ -0,0 +1,302 @@ + + + + + +URL Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    URL Helper

    + +

    The URL Helper file contains functions that assist in working with URLs.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('url'); + +

    The following functions are available:

    + +

    site_url()

    + +

    Returns your site URL, as specified in your config file. The index.php file (or whatever you have set as your +site index_page in your config file) will be added to the URL, as will any URI segments you pass to the function, and the url_suffix as set in your config file.

    + +

    You are encouraged to use this function any time you need to generate a local URL so that your pages become more portable +in the event your URL changes.

    + +

    Segments can be optionally passed to the function as a string or an array. Here is a string example:

    + +echo site_url("news/local/123"); + +

    The above example would return something like: http://example.com/index.php/news/local/123

    + +

    Here is an example of segments passed as an array:

    + + +$segments = array('news', 'local', '123');
    +
    +echo site_url($segments);
    + + +

    base_url()

    +

    Returns your site base URL, as specified in your config file. Example:

    +echo base_url(); + +

    This function returns the same thing as site_url, without the index_page or url_suffix being appended.

    + +

    Also like site_url, you can supply segments as a string or an array. Here is a string example:

    + +echo base_url("blog/post/123"); + +

    The above example would return something like: http://example.com/blog/post/123

    + +

    This is useful because unlike site_url(), you can supply a string to a file, such as an image or stylesheet. For example:

    + +echo base_url("images/icons/edit.png"); + +

    This would give you something like: http://example.com/images/icons/edit.png

    + + +

    current_url()

    +

    Returns the full URL (including segments) of the page being currently viewed.

    + + +

    uri_string()

    +

    Returns the URI segments of any page that contains this function. For example, if your URL was this:

    +http://some-site.com/blog/comments/123 + +

    The function would return:

    +/blog/comments/123 + + +

    index_page()

    +

    Returns your site "index" page, as specified in your config file. Example:

    +echo index_page(); + + + +

    anchor()

    + +

    Creates a standard HTML anchor link based on your local site URL:

    + +<a href="http://example.com">Click Here</a> + +

    The tag has three optional parameters:

    + +anchor(uri segments, text, attributes) + +

    The first parameter can contain any segments you wish appended to the URL. As with the site_url() function above, +segments can be a string or an array.

    + +

    Note:  If you are building links that are internal to your application do not include the base URL (http://...). This +will be added automatically from the information specified in your config file. Include only the URI segments you wish appended to the URL.

    + +

    The second segment is the text you would like the link to say. If you leave it blank, the URL will be used.

    + +

    The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple string or an associative array.

    + +

    Here are some examples:

    + +echo anchor('news/local/123', 'My News', 'title="News title"'); + +

    Would produce: <a href="http://example.com/index.php/news/local/123" title="News title">My News</a>

    + +echo anchor('news/local/123', 'My News', array('title' => 'The best news!')); + +

    Would produce: <a href="http://example.com/index.php/news/local/123" title="The best news!">My News</a>

    + + +

    anchor_popup()

    + +

    Nearly identical to the anchor() function except that it opens the URL in a new window. + +You can specify JavaScript window attributes in the third parameter to control how the window is opened. If +the third parameter is not set it will simply open a new window with your own browser settings. Here is an example +with attributes:

    + + + +$atts = array(
    +              'width'      => '800',
    +              'height'     => '600',
    +              'scrollbars' => 'yes',
    +              'status'     => 'yes',
    +              'resizable'  => 'yes',
    +              'screenx'    => '0',
    +              'screeny'    => '0'
    +            );
    +
    +echo anchor_popup('news/local/123', 'Click Me!', $atts);
    + +

    Note: The above attributes are the function defaults so you only need to set the ones that are different from what you need. +If you want the function to use all of its defaults simply pass an empty array in the third parameter:

    + +echo anchor_popup('news/local/123', 'Click Me!', array()); + + +

    mailto()

    + +

    Creates a standard HTML email link. Usage example:

    + +echo mailto('me@my-site.com', 'Click Here to Contact Me'); + +

    As with the anchor() tab above, you can set attributes using the third parameter.

    + + +

    safe_mailto()

    + +

    Identical to the above function except it writes an obfuscated version of the mailto tag using ordinal numbers +written with JavaScript to help prevent the email address from being harvested by spam bots.

    + + +

    auto_link()

    + +

    Automatically turns URLs and email addresses contained in a string into links. Example:

    + +$string = auto_link($string); + +

    The second parameter determines whether URLs and emails are converted or just one or the other. Default behavior is both +if the parameter is not specified. Email links are encoded as safe_mailto() as shown above.

    + +

    Converts only URLs:

    +$string = auto_link($string, 'url'); + +

    Converts only Email addresses:

    +$string = auto_link($string, 'email'); + +

    The third parameter determines whether links are shown in a new window. The value can be TRUE or FALSE (boolean):

    +$string = auto_link($string, 'both', TRUE); + + +

    url_title()

    +

    Takes a string as input and creates a human-friendly URL string. This is useful if, for example, you have a blog +in which you'd like to use the title of your entries in the URL. Example:

    + +$title = "What's wrong with CSS?";
    +
    +$url_title = url_title($title);
    +
    +// Produces: Whats-wrong-with-CSS +
    + + +

    The second parameter determines the word delimiter. By default dashes are used.

    + +$title = "What's wrong with CSS?";
    +
    +$url_title = url_title($title, '_');
    +
    +// Produces: Whats_wrong_with_CSS +
    + +

    The third parameter determines whether or not lowercase characters are forced. By default they are not. Options are boolean TRUE/FALSE:

    + +$title = "What's wrong with CSS?";
    +
    +$url_title = url_title($title, '_', TRUE);
    +
    +// Produces: whats_wrong_with_css +
    + +

    prep_url()

    +

    This function will add http:// in the event that a scheme is missing from a URL. Pass the URL string to the function like this:

    + +$url = "example.com";

    +$url = prep_url($url);
    + + + + +

    redirect()

    + +

    Does a "header redirect" to the URI specified. If you specify the full site URL that link will be build, but for local links simply providing the URI segments +to the controller you want to direct to will create the link. The function will build the URL based on your config file values.

    + +

    The optional second parameter allows you to choose between the "location" +method (default) or the "refresh" method. Location is faster, but on Windows servers it can sometimes be a problem. The optional third parameter allows you to send a specific HTTP Response Code - this could be used for example to create 301 redirects for search engine purposes. The default Response Code is 302. The third parameter is only available with 'location' redirects, and not 'refresh'. Examples:

    + +if ($logged_in == FALSE)
    +{
    +     redirect('/login/form/', 'refresh');
    +}
    +
    +// with 301 redirect
    +redirect('/article/13', 'location', 301);
    + +

    Note: In order for this function to work it must be used before anything is outputted +to the browser since it utilizes server headers.
    +Note: For very fine grained control over headers, you should use the Output Library's set_header() function.

    + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/helpers/xml_helper.html b/api/user_guide/helpers/xml_helper.html new file mode 100644 index 0000000..3ca9519 --- /dev/null +++ b/api/user_guide/helpers/xml_helper.html @@ -0,0 +1,105 @@ + + + + + +XML Helper : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    XML Helper

    + +

    The XML Helper file contains functions that assist in working with XML data.

    + + +

    Loading this Helper

    + +

    This helper is loaded using the following code:

    +$this->load->helper('xml'); + +

    The following functions are available:

    + +

    xml_convert('string')

    + +

    Takes a string as input and converts the following reserved XML characters to entities:

    + +

    +Ampersands: &
    +Less then and greater than characters: < >
    +Single and double quotes: '  "
    +Dashes: -

    + +

    This function ignores ampersands if they are part of existing character entities. Example:

    + +$string = xml_convert($string); + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/images/appflowchart.gif b/api/user_guide/images/appflowchart.gif new file mode 100644 index 0000000..4328e48 Binary files /dev/null and b/api/user_guide/images/appflowchart.gif differ diff --git a/api/user_guide/images/arrow.gif b/api/user_guide/images/arrow.gif new file mode 100644 index 0000000..9e9c79a Binary files /dev/null and b/api/user_guide/images/arrow.gif differ diff --git a/api/user_guide/images/ci_logo.jpg b/api/user_guide/images/ci_logo.jpg new file mode 100644 index 0000000..3ae0eee Binary files /dev/null and b/api/user_guide/images/ci_logo.jpg differ diff --git a/api/user_guide/images/ci_logo_flame.jpg b/api/user_guide/images/ci_logo_flame.jpg new file mode 100644 index 0000000..17e9c58 Binary files /dev/null and b/api/user_guide/images/ci_logo_flame.jpg differ diff --git a/api/user_guide/images/ci_quick_ref.png b/api/user_guide/images/ci_quick_ref.png new file mode 100644 index 0000000..c07d6b4 Binary files /dev/null and b/api/user_guide/images/ci_quick_ref.png differ diff --git a/api/user_guide/images/codeigniter_1.7.1_helper_reference.pdf b/api/user_guide/images/codeigniter_1.7.1_helper_reference.pdf new file mode 100644 index 0000000..85af7c8 Binary files /dev/null and b/api/user_guide/images/codeigniter_1.7.1_helper_reference.pdf differ diff --git a/api/user_guide/images/codeigniter_1.7.1_helper_reference.png b/api/user_guide/images/codeigniter_1.7.1_helper_reference.png new file mode 100644 index 0000000..15a7c15 Binary files /dev/null and b/api/user_guide/images/codeigniter_1.7.1_helper_reference.png differ diff --git a/api/user_guide/images/codeigniter_1.7.1_library_reference.pdf b/api/user_guide/images/codeigniter_1.7.1_library_reference.pdf new file mode 100644 index 0000000..13cb360 Binary files /dev/null and b/api/user_guide/images/codeigniter_1.7.1_library_reference.pdf differ diff --git a/api/user_guide/images/codeigniter_1.7.1_library_reference.png b/api/user_guide/images/codeigniter_1.7.1_library_reference.png new file mode 100644 index 0000000..7f054f9 Binary files /dev/null and b/api/user_guide/images/codeigniter_1.7.1_library_reference.png differ diff --git a/api/user_guide/images/file.gif b/api/user_guide/images/file.gif new file mode 100644 index 0000000..8141e03 Binary files /dev/null and b/api/user_guide/images/file.gif differ diff --git a/api/user_guide/images/folder.gif b/api/user_guide/images/folder.gif new file mode 100644 index 0000000..fef31a6 Binary files /dev/null and b/api/user_guide/images/folder.gif differ diff --git a/api/user_guide/images/nav_bg_darker.jpg b/api/user_guide/images/nav_bg_darker.jpg new file mode 100644 index 0000000..816efad Binary files /dev/null and b/api/user_guide/images/nav_bg_darker.jpg differ diff --git a/api/user_guide/images/nav_separator_darker.jpg b/api/user_guide/images/nav_separator_darker.jpg new file mode 100644 index 0000000..a09bd5a Binary files /dev/null and b/api/user_guide/images/nav_separator_darker.jpg differ diff --git a/api/user_guide/images/nav_toggle_darker.jpg b/api/user_guide/images/nav_toggle_darker.jpg new file mode 100644 index 0000000..eff33de Binary files /dev/null and b/api/user_guide/images/nav_toggle_darker.jpg differ diff --git a/api/user_guide/images/reactor-bullet.png b/api/user_guide/images/reactor-bullet.png new file mode 100644 index 0000000..89c8129 Binary files /dev/null and b/api/user_guide/images/reactor-bullet.png differ diff --git a/api/user_guide/images/smile.gif b/api/user_guide/images/smile.gif new file mode 100644 index 0000000..bf09225 Binary files /dev/null and b/api/user_guide/images/smile.gif differ diff --git a/api/user_guide/images/transparent.gif b/api/user_guide/images/transparent.gif new file mode 100644 index 0000000..b740647 Binary files /dev/null and b/api/user_guide/images/transparent.gif differ diff --git a/api/user_guide/index.html b/api/user_guide/index.html new file mode 100644 index 0000000..793a7ca --- /dev/null +++ b/api/user_guide/index.html @@ -0,0 +1,98 @@ + + + + + +Welcome to CodeIgniter : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + +
    + + + +
    + +
    CodeIgniter
    + + + +
    + + + +

    Welcome to CodeIgniter

    + +

    CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. +Its goal is to enable you to develop projects much faster than you could if you were writing code +from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and +logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by +minimizing the amount of code needed for a given task.

    + + +

    Who is CodeIgniter For?

    + +

    CodeIgniter is right for you if:

    + +
      +
    • You want a framework with a small footprint.
    • +
    • You need exceptional performance.
    • +
    • You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations.
    • +
    • You want a framework that requires nearly zero configuration.
    • +
    • You want a framework that does not require you to use the command line.
    • +
    • You want a framework that does not require you to adhere to restrictive coding rules.
    • +
    • You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
    • +
    • You eschew complexity, favoring simple solutions.
    • +
    • You need clear, thorough documentation.
    • +
    + + +
    + + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/downloads.html b/api/user_guide/installation/downloads.html new file mode 100644 index 0000000..01a4a58 --- /dev/null +++ b/api/user_guide/installation/downloads.html @@ -0,0 +1,120 @@ + + + + + +Downloading CodeIgniter : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Downloading CodeIgniter

    + + + + + + +

    Git Server

    +

    Git is a distributed version control system.

    + +

    Public Git access is available at GitHub. + Please note that while every effort is made to keep this code base functional, we cannot guarantee the functionality of code taken + from the tip.

    + +

    Beginning with version 2.0.3, stable tags are also available via GitHub, simply select the version from the Tags dropdown.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/index.html b/api/user_guide/installation/index.html new file mode 100644 index 0000000..ff9d830 --- /dev/null +++ b/api/user_guide/installation/index.html @@ -0,0 +1,108 @@ + + + + + +Installation Instructions : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Installation Instructions

    + +

    CodeIgniter is installed in four steps:

    + +
      +
    1. Unzip the package.
    2. +
    3. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
    4. +
    5. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
    6. +
    7. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
    8. +
    + +

    If you wish to increase security by hiding the location of your CodeIgniter files you can rename the system and application folders +to something more private. If you do rename them, you must open your main index.php file and set the $system_folder and $application_folder +variables at the top of the file with the new name you've chosen.

    + +

    For the best security, both the system and any application folders should be placed above web root so that they are not directly accessible via a browser. By default, .htaccess files are included in each folder to help prevent direct access, but it is best to remove them from public access entirely in case the web server configuration changes or doesn't abide by the .htaccess.

    + +

    After moving them, open your main index.php file and set the $system_folder and $application_folder variables, preferably with a full path, e.g. '/www/MyUser/system'.

    + +

    + One additional measure to take in production environments is to disable + PHP error reporting and any other development-only functionality. In CodeIgniter, + this can be done by setting the ENVIRONMENT constant, which is + more fully described on the security page. +

    + +

    That's it!

    + +

    If you're new to CodeIgniter, please read the Getting Started section of the User Guide to begin learning how +to build dynamic PHP applications. Enjoy!

    + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/troubleshooting.html b/api/user_guide/installation/troubleshooting.html new file mode 100644 index 0000000..85d9f7f --- /dev/null +++ b/api/user_guide/installation/troubleshooting.html @@ -0,0 +1,90 @@ + + + + + +Troubleshooting : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Troubleshooting

    + +

    If you find that no matter what you put in your URL only your default page is loading, it might be that your server +does not support the PATH_INFO variable needed to serve search-engine friendly URLs. + +As a first step, open your application/config/config.php file and look for the URI Protocol +information. It will recommend that you try a couple alternate settings. If it still doesn't work after you've tried this you'll need +to force CodeIgniter to add a question mark to your URLs. To do this open your application/config/config.php file and change this:

    + +$config['index_page'] = "index.php"; + +

    To this:

    + +$config['index_page'] = "index.php?"; + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_120.html b/api/user_guide/installation/upgrade_120.html new file mode 100644 index 0000000..38ede12 --- /dev/null +++ b/api/user_guide/installation/upgrade_120.html @@ -0,0 +1,92 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading From Beta 1.0 to Final 1.2

    + +

    To upgrade to Version 1.2 please replace the following directories with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • drivers
    • +
    • helpers
    • +
    • init
    • +
    • language
    • +
    • libraries
    • +
    • plugins
    • +
    • scaffolding
    • +
    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_130.html b/api/user_guide/installation/upgrade_130.html new file mode 100644 index 0000000..f448377 --- /dev/null +++ b/api/user_guide/installation/upgrade_130.html @@ -0,0 +1,203 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.2 to 1.3

    + +

    Note: The instructions on this page assume you are running version 1.2. If you +have not upgraded to that version please do so first.

    + + +

    Before performing an update you should take your site offline by replacing the index.php file +with a static one.

    + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace the following directories in your "system" folder with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • application/models/   (new for 1.3)
    • +
    • codeigniter   (new for 1.3)
    • +
    • drivers
    • +
    • helpers
    • +
    • init
    • +
    • language
    • +
    • libraries
    • +
    • plugins
    • +
    • scaffolding
    • +
    + + +

    Step 2: Update your error files

    + +

    Version 1.3 contains two new error templates located in application/errors, and for naming consistency the other error templates have +been renamed.

    + +

    If you have not customized any of the error templates simply +replace this folder:

    + +
      +
    • application/errors/
    • +
    + +

    If you have customized your error templates, rename them as follows:

    + + +
      +
    • 404.php   =  error_404.php
    • +
    • error.php   =  error_general.php
    • +
    • error_db.php   (new)
    • +
    • error_php.php   (new)
    • +
    + + +

    Step 3: Update your index.php file

    + +

    Please open your main index.php file (located at your root). At the very bottom of the file, change this:

    + +require_once BASEPATH.'libraries/Front_controller'.EXT; + +

    To this:

    + +require_once BASEPATH.'codeigniter/CodeIgniter'.EXT; + + +

    Step 4: Update your config.php file

    + +

    Open your application/config/config.php file and add these new items:

    + +
    +/*
    +|------------------------------------------------
    +| URL suffix
    +|------------------------------------------------
    +|
    +| This option allows you to add a suffix to all URLs.
    +| For example, if a URL is this:
    +|
    +| example.com/index.php/products/view/shoes
    +|
    +| You can optionally add a suffix, like ".html",
    +| making the page appear to be of a certain type:
    +|
    +| example.com/index.php/products/view/shoes.html
    +|
    +*/
    +$config['url_suffix'] = "";
    +
    +
    +/*
    +|------------------------------------------------
    +| Enable Query Strings
    +|------------------------------------------------
    +|
    +| By default CodeIgniter uses search-engine and
    +| human-friendly segment based URLs:
    +|
    +| example.com/who/what/where/
    +|
    +| You can optionally enable standard query string
    +| based URLs:
    +|
    +| example.com?who=me&what=something&where=here
    +|
    +| Options are: TRUE or FALSE (boolean)
    +|
    +| The two other items let you set the query string "words"
    +| that will invoke your controllers and functions:
    +| example.com/index.php?c=controller&m=function
    +|
    +*/
    +$config['enable_query_strings'] = FALSE;
    +$config['controller_trigger'] = 'c';
    +$config['function_trigger'] = 'm';
    +
    + + +

    Step 5: Update your database.php file

    + +

    Open your application/config/database.php file and add these new items:

    + +
    +$db['default']['dbprefix'] = "";
    +$db['default']['active_r'] = TRUE;
    +
    + + +

    Step 6: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_131.html b/api/user_guide/installation/upgrade_131.html new file mode 100644 index 0000000..fa123d1 --- /dev/null +++ b/api/user_guide/installation/upgrade_131.html @@ -0,0 +1,102 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.3 to 1.3.1

    + +

    Note: The instructions on this page assume you are running version 1.3. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace the following directories in your "system" folder with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • drivers
    • +
    • init/init_unit_test.php (new for 1.3.1)
    • +
    • language/
    • +
    • libraries
    • +
    • scaffolding
    • +
    + + +

    Step 2: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_132.html b/api/user_guide/installation/upgrade_132.html new file mode 100644 index 0000000..b0ab815 --- /dev/null +++ b/api/user_guide/installation/upgrade_132.html @@ -0,0 +1,100 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.3.1 to 1.3.2

    + +

    Note: The instructions on this page assume you are running version 1.3.1. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace the following directories in your "system" folder with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • drivers
    • +
    • init
    • +
    • libraries
    • +
    + + +

    Step 2: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_133.html b/api/user_guide/installation/upgrade_133.html new file mode 100644 index 0000000..badd6dc --- /dev/null +++ b/api/user_guide/installation/upgrade_133.html @@ -0,0 +1,112 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.3.2 to 1.3.3

    + +

    Note: The instructions on this page assume you are running version 1.3.2. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace the following directories in your "system" folder with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • codeigniter
    • +
    • drivers
    • +
    • helpers
    • +
    • init
    • +
    • libraries
    • +
    + + +

    Step 2: Update your Models

    + +

    If you are NOT using CodeIgniter's Models feature disregard this step.

    + +

    As of version 1.3.3, CodeIgniter does not connect automatically to your database when a model is loaded. This +allows you greater flexibility in determining which databases you would like used with your models. If your application is not connecting +to your database prior to a model being loaded you will have to update your code. There are several options for connecting, +as described here.

    + + +

    Step 3: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_140.html b/api/user_guide/installation/upgrade_140.html new file mode 100644 index 0000000..339befd --- /dev/null +++ b/api/user_guide/installation/upgrade_140.html @@ -0,0 +1,145 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.3.3 to 1.4.0

    + +

    Note: The instructions on this page assume you are running version 1.3.3. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace the following directories in your "system" folder with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • application/config/hooks.php
    • +
    • application/config/mimes.php
    • +
    • codeigniter
    • +
    • drivers
    • +
    • helpers
    • +
    • init
    • +
    • language
    • +
    • libraries
    • +
    • scaffolding
    • +
    + + +

    Step 2: Update your config.php file

    + +

    Open your application/config/config.php file and add these new items:

    + +
    +
    +/*
    +|--------------------------------------------------------------------------
    +| Enable/Disable System Hooks
    +|--------------------------------------------------------------------------
    +|
    +| If you would like to use the "hooks" feature you must enable it by
    +| setting this variable to TRUE (boolean).  See the user guide for details.
    +|
    +*/
    +$config['enable_hooks'] = FALSE;
    +
    +
    +/*
    +|--------------------------------------------------------------------------
    +| Allowed URL Characters
    +|--------------------------------------------------------------------------
    +|
    +| This lets you specify which characters are permitted within your URLs.
    +| When someone tries to submit a URL with disallowed characters they will
    +| get a warning message.
    +|
    +| As a security measure you are STRONGLY encouraged to restrict URLs to
    +| as few characters as possible.  By default only these are allowed: a-z 0-9~%.:_-
    +|
    +| Leave blank to allow all characters -- but only if you are insane.
    +|
    +| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
    +|
    +*/
    +$config['permitted_uri_chars'] = 'a-z 0-9~%.:_-';
    +
    + + +

    Step 3: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_141.html b/api/user_guide/installation/upgrade_141.html new file mode 100644 index 0000000..064fd66 --- /dev/null +++ b/api/user_guide/installation/upgrade_141.html @@ -0,0 +1,148 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.4.0 to 1.4.1

    + +

    Note: The instructions on this page assume you are running version 1.4.0. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace the following directories in your "system" folder with the new versions:

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
      +
    • codeigniter
    • +
    • drivers
    • +
    • helpers
    • +
    • libraries
    • +
    + + +

    Step 2: Update your config.php file

    + +

    Open your application/config/config.php file and add this new item:

    + +
    +
    +/*
    +|--------------------------------------------------------------------------
    +| Output Compression
    +|--------------------------------------------------------------------------
    +|
    +| Enables Gzip output compression for faster page loads.  When enabled,
    +| the output class will test whether your server supports Gzip.
    +| Even if it does, however, not all browsers support compression
    +| so enable only if you are reasonably sure your visitors can handle it.
    +|
    +| VERY IMPORTANT:  If you are getting a blank page when compression is enabled it
    +| means you are prematurely outputting something to your browser. It could
    +| even be a line of whitespace at the end of one of your scripts.  For
    +| compression to work, nothing can be sent before the output buffer is called
    +| by the output class.  Do not "echo" any values with compression enabled.
    +|
    +*/
    +$config['compress_output'] = FALSE;
    +
    +
    + + + +

    Step 3: Rename an Autoload Item

    + +

    Open the following file: application/config/autoload.php

    + +

    Find this array item:

    + +$autoload['core'] = array(); + +

    And rename it to this:

    + +$autoload['libraries'] = array(); + +

    This change was made to improve clarity since some users were not sure that their own libraries could be auto-loaded.

    + + + + + + +

    Step 4: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_150.html b/api/user_guide/installation/upgrade_150.html new file mode 100644 index 0000000..c41e139 --- /dev/null +++ b/api/user_guide/installation/upgrade_150.html @@ -0,0 +1,178 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.4.1 to 1.5.0

    + +

    Note: The instructions on this page assume you are running version 1.4.1. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • application/config/user_agents.php (new file for 1.5)
    • +
    • application/config/smileys.php (new file for 1.5)
    • +
    • codeigniter/
    • +
    • database/ (new folder for 1.5. Replaces the "drivers" folder)
    • +
    • helpers/
    • +
    • language/
    • +
    • libraries/
    • +
    • scaffolding/
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Update your database.php file

    + +

    Open your application/config/database.php file and add these new items:

    + +
    +$db['default']['cache_on'] = FALSE;
    +$db['default']['cachedir'] = '';
    +
    + + + +

    Step 3: Update your config.php file

    + +

    Open your application/config/config.php file and ADD these new items:

    + +
    +/*
    +|--------------------------------------------------------------------------
    +| Class Extension Prefix
    +|--------------------------------------------------------------------------
    +|
    +| This item allows you to set the filename/classname prefix when extending
    +| native libraries.  For more information please see the user guide:
    +|
    +| http://codeigniter.com/user_guide/general/core_classes.html
    +| http://codeigniter.com/user_guide/general/creating_libraries.html
    +|
    +*/
    +$config['subclass_prefix'] = 'MY_';
    +
    +/*
    +|--------------------------------------------------------------------------
    +| Rewrite PHP Short Tags
    +|--------------------------------------------------------------------------
    +|
    +| If your PHP installation does not have short tag support enabled CI
    +| can rewrite the tags on-the-fly, enabling you to utilize that syntax
    +| in your view files.  Options are TRUE or FALSE (boolean)
    +|
    +*/
    +$config['rewrite_short_tags'] = FALSE;
    +
    + +

    In that same file REMOVE this item:

    + + +
    +/*
    +|--------------------------------------------------------------------------
    +| Enable/Disable Error Logging
    +|--------------------------------------------------------------------------
    +|
    +| If you would like errors or debug messages logged set this variable to
    +| TRUE (boolean).  Note: You must set the file permissions on the "logs" folder
    +| such that it is writable.
    +|
    +*/
    +$config['log_errors'] = FALSE;
    +
    + +

    Error logging is now disabled simply by setting the threshold to zero.

    + + + +

    Step 4: Update your main index.php file

    + +

    If you are running a stock index.php file simply replace your version with the new one.

    + +

    If your index.php file has internal modifications, please add your modifications to the new file and use it.

    + + + +

    Step 5: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_152.html b/api/user_guide/installation/upgrade_152.html new file mode 100644 index 0000000..eb1ec3b --- /dev/null +++ b/api/user_guide/installation/upgrade_152.html @@ -0,0 +1,111 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.5.0 to 1.5.2

    + +

    Note: The instructions on this page assume you are running version 1.5.0 or 1.5.1. If you +have not upgraded to that version please do so first.

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/helpers/download_helper.php
    • +
    • system/helpers/form_helper.php
    • +
    • system/libraries/Table.php
    • +
    • system/libraries/User_agent.php
    • +
    • system/libraries/Exceptions.php
    • +
    • system/libraries/Input.php
    • +
    • system/libraries/Router.php
    • +
    • system/libraries/Loader.php
    • +
    • system/libraries/Image_lib.php
    • +
    • system/language/english/unit_test_lang.php
    • +
    • system/database/DB_active_rec.php
    • +
    • system/database/drivers/mysqli/mysqli_driver.php
    • +
    • codeigniter/
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_153.html b/api/user_guide/installation/upgrade_153.html new file mode 100644 index 0000000..f26aa8a --- /dev/null +++ b/api/user_guide/installation/upgrade_153.html @@ -0,0 +1,100 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.5.2 to 1.5.3

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/database/drivers
    • +
    • system/helpers
    • +
    • system/libraries/Input.php
    • +
    • system/libraries/Loader.php
    • +
    • system/libraries/Profiler.php
    • +
    • system/libraries/Table.php
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Update your user guide

    + +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_154.html b/api/user_guide/installation/upgrade_154.html new file mode 100644 index 0000000..d721ff2 --- /dev/null +++ b/api/user_guide/installation/upgrade_154.html @@ -0,0 +1,116 @@ + + + + + +Upgrading from 1.5.3 to 1.5.4 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.5.3 to 1.5.4

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • application/config/mimes.php
    • +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/libraries
    • +
    • system/plugins
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Add charset to your config.php

    +

    Add the following to application/config/config.php

    +/*
    + |--------------------------------------------------------------------------
    + | Default Character Set
    + |--------------------------------------------------------------------------
    + |
    + | This determines which character set is used by default in various methods
    + | that require a character set to be provided.
    + |
    + */
    + $config['charset'] = "UTF-8";
    + +

    Step 3: Autoloading language files

    +

    If you want to autoload any language files, add this line to application/config/autoload.php

    +$autoload['language'] = array(); + +

    Step 4: Update your user guide

    +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_160.html b/api/user_guide/installation/upgrade_160.html new file mode 100644 index 0000000..fb11ee3 --- /dev/null +++ b/api/user_guide/installation/upgrade_160.html @@ -0,0 +1,125 @@ + + + + + +Upgrading from 1.5.4 to 1.6.0 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.5.4 to 1.6.0

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/libraries
    • +
    • system/plugins
    • +
    • system/language
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Add time_to_update to your config.php

    +

    Add the following to application/config/config.php with the other session configuration options

    +

    $config['sess_time_to_update'] = 300;

    +

    Step 3: Add $autoload['model']

    +

    Add the following to application/config/autoload.php

    +

    /*
    + | -------------------------------------------------------------------
    + | Auto-load Model files
    + | -------------------------------------------------------------------
    + | Prototype:
    + |
    + | $autoload['model'] = array('my_model');
    + |
    + */
    +
    + $autoload['model'] = array();

    +

    Step 4: Add to your database.php

    +

    Make the following changes to your application/config/database.php file:

    +

    Add the following variable above the database configuration options, with $active_group

    +

    $active_record = TRUE;

    +

    Remove the following from your database configuration options

    +

    $db['default']['active_r'] = TRUE;

    +

    Add the following to your database configuration options

    +

    $db['default']['char_set'] = "utf8";
    +$db['default']['dbcollat'] = "utf8_general_ci";

    + +

    Step 5: Update your user guide

    +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_161.html b/api/user_guide/installation/upgrade_161.html new file mode 100644 index 0000000..7f40355 --- /dev/null +++ b/api/user_guide/installation/upgrade_161.html @@ -0,0 +1,98 @@ + + + + + +Upgrading from 1.6.0 to 1.6.1 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.6.0 to 1.6.1

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/language
    • +
    • system/libraries
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Update your user guide

    +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_162.html b/api/user_guide/installation/upgrade_162.html new file mode 100644 index 0000000..4237857 --- /dev/null +++ b/api/user_guide/installation/upgrade_162.html @@ -0,0 +1,106 @@ + + + + + +Upgrading from 1.6.1 to 1.6.2 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.6.1 to 1.6.2

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/language
    • +
    • system/libraries
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Encryption Key

    +

    If you are using sessions, open up application/config/config.php and verify you've set an encryption key.

    + +

    Step 3: Constants File

    +

    Copy /application/config/constants.php to your installation, and modify if necessary.

    +

    Step 4: Mimes File

    +

    Replace /application/config/mimes.php with the dowloaded version. If you've added custom mime types, you'll need to re-add them.

    +

    Step 5: Update your user guide

    +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_163.html b/api/user_guide/installation/upgrade_163.html new file mode 100644 index 0000000..edfa420 --- /dev/null +++ b/api/user_guide/installation/upgrade_163.html @@ -0,0 +1,99 @@ + + + + + +Upgrading from 1.6.2 to 1.6.3 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.6.2 to 1.6.3

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/language
    • +
    • system/libraries
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Update your user guide

    +

    Please also replace your local copy of the user guide with the new version.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_170.html b/api/user_guide/installation/upgrade_170.html new file mode 100644 index 0000000..6fea1da --- /dev/null +++ b/api/user_guide/installation/upgrade_170.html @@ -0,0 +1,121 @@ + + + + + +Upgrading from 1.6.3 to 1.7.0 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.6.3 to 1.7.0

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/language
    • +
    • system/libraries
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Update your Session Table

    + +

    If you are using the Session class in your application, AND if you are storing session data to a database, you must add a new column named user_data to your session table. +Here is an example of what this column might look like for MySQL:

    + +user_data text NOT NULL + +

    To add this column you will run a query similar to this:

    + +ALTER TABLE `ci_sessions` ADD `user_data` text NOT NULL + +

    You'll find more information regarding the new Session functionality in the Session class page.

    + + +

    Step 3: Update your Validation Syntax

    + +

    This is an optional, but recommended step, for people currently using the Validation class. CI 1.7 introduces a new Form Validation class, which +deprecates the old Validation library. We have left the old one in place so that existing applications that use it will not break, but you are encouraged to +migrate to the new version as soon as possible. Please read the user guide carefully as the new library works a little differently, and has several new features.

    + + + +

    Step 4: Update your user guide

    +

    Please replace your local copy of the user guide with the new version, including the image files.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_171.html b/api/user_guide/installation/upgrade_171.html new file mode 100644 index 0000000..45347be --- /dev/null +++ b/api/user_guide/installation/upgrade_171.html @@ -0,0 +1,98 @@ + + + + + +Upgrading from 1.7.0 to 1.7.1 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.7.0 to 1.7.1

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/language
    • +
    • system/libraries
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Update your user guide

    +

    Please replace your local copy of the user guide with the new version, including the image files.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_172.html b/api/user_guide/installation/upgrade_172.html new file mode 100644 index 0000000..cad36b1 --- /dev/null +++ b/api/user_guide/installation/upgrade_172.html @@ -0,0 +1,109 @@ + + + + + +Upgrading from 1.7.1 to 1.7.2 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.7.1 to 1.7.2

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace these files and directories in your "system" folder with the new versions:

    + +
      + +
    • system/codeigniter
    • +
    • system/database
    • +
    • system/helpers
    • +
    • system/language
    • +
    • system/libraries
    • +
    • index.php
    • +
    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Remove header() from 404 error template

    +

    If you are using header() in your 404 error template, such as the case with the default error_404.php template shown below, remove that line of code.

    + +<?php header("HTTP/1.1 404 Not Found"); ?> + +

    404 status headers are now properly handled in the show_404() method itself.

    + +

    Step 3: Confirm your system_path

    +

    In your updated index.php file, confirm that the $system_path variable is set to your application's system folder.

    + +

    Step 4: Update your user guide

    +

    Please replace your local copy of the user guide with the new version, including the image files.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_200.html b/api/user_guide/installation/upgrade_200.html new file mode 100644 index 0000000..daf6522 --- /dev/null +++ b/api/user_guide/installation/upgrade_200.html @@ -0,0 +1,131 @@ + + + + + +Upgrading from 1.7.2 to 2.0.0 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 1.7.2 to 2.0.0

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder except your application folder.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Adjust get_dir_file_info() where necessary

    + +

    Version 2.0.0 brings a non-backwards compatible change to get_dir_file_info() in the File Helper. Non-backwards compatible changes are extremely rare + in CodeIgniter, but this one we feel was warranted due to how easy it was to create serious server performance issues. If you need + recursiveness where you are using this helper function, change such instances, setting the second parameter, $top_level_only to FALSE:

    + +get_dir_file_info('/path/to/directory', FALSE); + +

    + +

    Step 3: Convert your Plugins to Helpers

    + +

    2.0.0 gets rid of the "Plugin" system as their functionality was identical to Helpers, but non-extensible. You will need to rename your plugin files from filename_pi.php to filename_helper.php, move them to your helpers folder, and change all instances of: + + $this->load->plugin('foo'); + +to + + $this->load->helper('foo'); + +

    + +

    Step 4: Update stored encrypted data

    + +

    Note: If your application does not use the Encryption library, does not store Encrypted data permanently, or is on an environment that does not support Mcrypt, you may skip this step.

    + +

    The Encryption library has had a number of improvements, some for encryption strength and some for performance, that has an unavoidable consequence of + making it no longer possible to decode encrypted data produced by the original version of this library. To help with the transition, a new method has + been added, encode_from_legacy() that will decode the data with the original algorithm and return a re-encoded string using the improved methods. + This will enable you to easily replace stale encrypted data with fresh in your applications, either on the fly or en masse.

    + +

    Please read how to use this method in the Encryption library documentation.

    + +

    Step 5: Remove loading calls for the compatibility helper.

    +

    The compatibility helper has been removed from the CodeIgniter core. All methods in it should be natively available in supported PHP versions.

    + +

    Step 6: Update Class extension

    +

    All core classes are now prefixed with CI_. Update Models and Controllers to extend CI_Model and CI_Controller, respectively.

    + +

    Step 7: Update Parent Constructor calls

    +

    All native CodeIgniter classes now use the PHP 5 __construct() convention. Please update extended libraries to call parent::__construct().

    + +

    Step 8: Update your user guide

    +

    Please replace your local copy of the user guide with the new version, including the image files.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_201.html b/api/user_guide/installation/upgrade_201.html new file mode 100644 index 0000000..1b30752 --- /dev/null +++ b/api/user_guide/installation/upgrade_201.html @@ -0,0 +1,105 @@ + + + + + +Upgrading from 2.0.0 to 2.0.1 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.0.0 to 2.0.1

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Replace config/mimes.php

    + +

    This config file has been updated to contain more mime types, please copy it to application/config/mimes.php.

    + + +

    Step 3: Check for forms posting to default controller

    + +

    + The default behavior for form_open() when called with no parameters used to be to post to the default controller, but it will now just leave an empty action="" meaning the form will submit to the current URL. + If submitting to the default controller was the expected behavior it will need to be changed from: +

    + +echo form_open(); //<form action="" method="post" accept-charset="utf-8"> + +

    to use either a / or base_url():

    + +echo form_open('/'); //<form action="http://example.com/index.php/" method="post" accept-charset="utf-8">
    +echo form_open(base_url()); //<form action="http://example.com/" method="post" accept-charset="utf-8">
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_202.html b/api/user_guide/installation/upgrade_202.html new file mode 100644 index 0000000..7814de8 --- /dev/null +++ b/api/user_guide/installation/upgrade_202.html @@ -0,0 +1,97 @@ + + + + + +Upgrading from 2.0.1 to 2.0.2 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.0.1 to 2.0.2

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + + +

    Step 2: Remove loading calls for the Security Library

    + +

    Security has been moved to the core and is now always loaded automatically. Make sure you remove any loading calls as they will result in PHP errors.

    + + +

    Step 3: Move MY_Security

    + +

    If you are overriding or extending the Security library, you will need to move it to application/core.

    + +

    csrf_token_name and csrf_hash have changed to protected class properties. Please use security->get_csrf_hash() and security->get_csrf_token_name() to access those values.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_203.html b/api/user_guide/installation/upgrade_203.html new file mode 100644 index 0000000..4f58706 --- /dev/null +++ b/api/user_guide/installation/upgrade_203.html @@ -0,0 +1,121 @@ + + + + + +Upgrading from 2.0.2 to 2.0.3 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.0.2 to 2.0.3

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Update your main index.php file

    + +

    If you are running a stock index.php file simply replace your version with the new one.

    + +

    If your index.php file has internal modifications, please add your modifications to the new file and use it.

    + +

    Step 3: Replace config/user_agents.php

    + +

    This config file has been updated to contain more user agent types, please copy it to application/config/user_agents.php.

    + +

    Step 4: Change references of the EXT constant to ".php"

    +

    Note: The EXT Constant has been marked as deprecated, but has not been removed from the application. You are encouraged to make the changes sooner rather than later.

    + +

    Step 5: Remove APPPATH.'third_party' from autoload.php

    + +

    Open application/autoload.php, and look for the following:

    + +$autoload['packages'] = array(APPPATH.'third_party'); + +

    If you have not chosen to load any additional packages, that line can be changed to:

    +$autoload['packages'] = array(); + +

    Which should provide for nominal performance gains if not autoloading packages.

    + +

    Update Sessions Database Tables

    + +

    If you are using database sessions with the CI Session Library, please update your ci_sessions database table as follows:

    + + + CREATE INDEX last_activity_idx ON ci_sessions(last_activity); + ALTER TABLE ci_sessions MODIFY user_agent VARCHAR(120); + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_210.html b/api/user_guide/installation/upgrade_210.html new file mode 100644 index 0000000..16ad69d --- /dev/null +++ b/api/user_guide/installation/upgrade_210.html @@ -0,0 +1,89 @@ + + + + + +Upgrading from 2.0.3 to 2.1.0 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.0.3 to 2.1.0

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Replace config/user_agents.php

    + +

    This config file has been updated to contain more user agent types, please copy it to application/config/user_agents.php.

    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_211.html b/api/user_guide/installation/upgrade_211.html new file mode 100644 index 0000000..9480be2 --- /dev/null +++ b/api/user_guide/installation/upgrade_211.html @@ -0,0 +1,94 @@ + + + + + +Upgrading from 2.1.0 to 2.1.1 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.1.0 to 2.1.1

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +

    Step 2: Replace config/mimes.php

    + +

    This config file has been updated to contain more user mime-types, please copy it to application/config/mimes.php.

    + +

    Step 3: Update your IP address tables:

    + +

    This upgrade adds support for IPv6 IP addresses. In order to store them, you need to enlarge your ip_address columns to 45 characters. For example, CodeIgniter's session table will need to change:

    + +ALTER TABLE ci_sessions CHANGE ip_address ip_address varchar(45) default '0' NOT NULL + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_212.html b/api/user_guide/installation/upgrade_212.html new file mode 100644 index 0000000..f71e5cf --- /dev/null +++ b/api/user_guide/installation/upgrade_212.html @@ -0,0 +1,84 @@ + + + + + +Upgrading from 2.1.1 to 2.1.2 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.1.1 to 2.1.2

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_213.html b/api/user_guide/installation/upgrade_213.html new file mode 100644 index 0000000..cd1e48c --- /dev/null +++ b/api/user_guide/installation/upgrade_213.html @@ -0,0 +1,84 @@ + + + + + +Upgrading from 2.1.2 to 2.1.3 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.1.2 to 2.1.3

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_214.html b/api/user_guide/installation/upgrade_214.html new file mode 100644 index 0000000..6e5dc99 --- /dev/null +++ b/api/user_guide/installation/upgrade_214.html @@ -0,0 +1,84 @@ + + + + + +Upgrading from 2.1.3 to 2.1.4 : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading from 2.1.3 to 2.1.4

    + +

    Before performing an update you should take your site offline by replacing the index.php file with a static one.

    + +

    Step 1: Update your CodeIgniter files

    + +

    Replace all files and directories in your "system" folder and replace your index.php file. If any modifications were made to your index.php they will need to be made fresh in this new one.

    + +

    Note: If you have any custom developed files in these folders please make copies of them first.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrade_b11.html b/api/user_guide/installation/upgrade_b11.html new file mode 100644 index 0000000..e85d5d2 --- /dev/null +++ b/api/user_guide/installation/upgrade_b11.html @@ -0,0 +1,144 @@ + + + + + +CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Upgrading From Beta 1.0 to Beta 1.1

    + +

    To upgrade to Beta 1.1 please perform the following steps:

    + +

    Step 1: Replace your index file

    + +

    Replace your main index.php file with the new index.php file. Note: If you have renamed your "system" folder you will need to edit this info in the new file.

    + +

    Step 2: Relocate your config folder

    + +

    This version of CodeIgniter now permits multiple sets of "applications" to all share a common set of backend files. In order to enable +each application to have its own configuration values, the config directory must now reside +inside of your application folder, so please move it there.

    + + +

    Step 3: Replace directories

    + +

    Replace the following directories with the new versions:

    + +
      +
    • drivers
    • +
    • helpers
    • +
    • init
    • +
    • libraries
    • +
    • scaffolding
    • +
    + + +

    Step 4: Add the calendar language file

    + +

    There is a new language file corresponding to the new calendaring class which must be added to your language folder. Add +the following item to your version: language/english/calendar_lang.php

    + + +

    Step 5: Edit your config file

    + +

    The original application/config/config.php file has a typo in it Open the file and look for the items related to cookies:

    + +$conf['cookie_prefix'] = "";
    +$conf['cookie_domain'] = "";
    +$conf['cookie_path'] = "/";
    + +

    Change the array name from $conf to $config, like this:

    + +$config['cookie_prefix'] = "";
    +$config['cookie_domain'] = "";
    +$config['cookie_path'] = "/";
    + +

    Lastly, add the following new item to the config file (and edit the option if needed):

    + +
    +/*
    +|------------------------------------------------
    +| URI PROTOCOL
    +|------------------------------------------------
    +|
    +| This item determines which server global
    +| should be used to retrieve the URI string. The
    +| default setting of "auto" works for most servers.
    +| If your links do not seem to work, try one of
    +| the other delicious flavors:
    +|
    +| 'auto' Default - auto detects
    +| 'path_info' Uses the PATH_INFO
    +| 'query_string' Uses the QUERY_STRING
    +*/
    +
    +$config['uri_protocol'] = "auto";
    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/installation/upgrading.html b/api/user_guide/installation/upgrading.html new file mode 100644 index 0000000..a0c241f --- /dev/null +++ b/api/user_guide/installation/upgrading.html @@ -0,0 +1,110 @@ + + + + + +Upgrading From a Previous Version : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/benchmark.html b/api/user_guide/libraries/benchmark.html new file mode 100644 index 0000000..5ece98b --- /dev/null +++ b/api/user_guide/libraries/benchmark.html @@ -0,0 +1,198 @@ + + + + + +Benchmarking Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Benchmarking Class

    + +

    CodeIgniter has a Benchmarking class that is always active, enabling the time difference between any +two marked points to be calculated.

    + +

    Note: This class is initialized automatically by the system so there is no need to do it manually.

    + + +

    In addition, the benchmark is always started the moment the framework is +invoked, and ended by the output class right before sending the final view to the browser, enabling a very accurate +timing of the entire system execution to be shown.

    + + +

    Table of Contents

    + + + + + + +

    Using the Benchmark Class

    + +

    The Benchmark class can be used within your controllers, views, or your models. The process for usage is this:

    + +
      +
    1. Mark a start point
    2. +
    3. Mark an end point
    4. +
    5. Run the "elapsed time" function to view the results
    6. +
    + +

    Here's an example using real code:

    + +$this->benchmark->mark('code_start');
    +
    +// Some code happens here
    +
    +$this->benchmark->mark('code_end');
    +
    +echo $this->benchmark->elapsed_time('code_start', 'code_end');
    + +

    Note: The words "code_start" and "code_end" are arbitrary. They are simply words used to set two markers. You can +use any words you want, and you can set multiple sets of markers. Consider this example:

    + +$this->benchmark->mark('dog');
    +
    +// Some code happens here
    +
    +$this->benchmark->mark('cat');
    +
    +// More code happens here
    +
    +$this->benchmark->mark('bird');
    +
    +echo $this->benchmark->elapsed_time('dog', 'cat');
    +echo $this->benchmark->elapsed_time('cat', 'bird');
    +echo $this->benchmark->elapsed_time('dog', 'bird');
    + + + +

    Profiling Your Benchmark Points

    + +

    If you want your benchmark data to be available to the +Profiler all of your marked points must be set up in pairs, and +each mark point name must end with _start and _end. +Each pair of points must otherwise be named identically. Example:

    + + +$this->benchmark->mark('my_mark_start');
    +
    +// Some code happens here...
    +
    +$this->benchmark->mark('my_mark_end'); +

    + +$this->benchmark->mark('another_mark_start');
    +
    +// Some more code happens here...
    +
    +$this->benchmark->mark('another_mark_end'); +
    + +

    Please read the Profiler page for more information.

    + + + +

    Displaying Total Execution Time

    + +

    If you would like to display the total elapsed time from the moment CodeIgniter starts to the moment the final output +is sent to the browser, simply place this in one of your view templates:

    + +<?php echo $this->benchmark->elapsed_time();?> + +

    You'll notice that it's the same function used in the examples above to calculate the time between two point, except you are +not using any parameters. When the parameters are absent, CodeIgniter does not stop the benchmark until right before the final +output is sent to the browser. It doesn't matter where you use the function call, the timer will continue to run until the very end.

    + +

    An alternate way to show your elapsed time in your view files is to use this pseudo-variable, if you prefer not to use the pure PHP:

    +{elapsed_time} + +

    Note: If you want to benchmark anything within your controller +functions you must set your own start/end points.

    + + +

    Displaying Memory Consumption

    + +

    If your PHP installation is configured with --enable-memory-limit, you can display the amount of memory consumed by the entire +system using the following code in one of your view file:

    + +<?php echo $this->benchmark->memory_usage();?> +

    Note: This function can only be used in your view files. The consumption will reflect the total memory used by the entire app.

    + +

    An alternate way to show your memory usage in your view files is to use this pseudo-variable, if you prefer not to use the pure PHP:

    +{memory_usage} + + + + +
    + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/caching.html b/api/user_guide/libraries/caching.html new file mode 100644 index 0000000..95ded23 --- /dev/null +++ b/api/user_guide/libraries/caching.html @@ -0,0 +1,193 @@ + + + + + +Caching Driver : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Caching Driver

    + +

    CodeIgniter features wrappers around some of the most popular forms of fast and dynamic caching. All but file-based caching require specific server requirements, and a Fatal Exception will be thrown if server requirements are not met.

    + +

    Table of Contents

    + + +

    Available Drivers

    + + +

    Example Usage

    + +

    The following example will load the cache driver, specify APC as the driver to use, and fall back to file-based caching if APC is not available in the hosting environment.

    + + +$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
    +
    +if ( ! $foo = $this->cache->get('foo'))
    +{
    +     echo 'Saving to the cache!<br />';
    +     $foo = 'foobarbaz!';
    +
    +     // Save into the cache for 5 minutes
    +     $this->cache->save('foo', $foo, 300);
    +}
    +
    +echo $foo; +
    + +

    Function Reference

    + +

    is_supported(driver['string'])

    + +

    This function is automatically called when accessing drivers via $this->cache->get(). However, if the individual drivers are used, make sure to call this function to ensure the driver is supported in the hosting environment.

    + + +if ($this->cache->apc->is_supported())
    +{
    +     if ($data = $this->cache->apc->get('my_cache'))
    +     {
    +          // do things.
    +     }
    +} +
    + +

    get(id['string'])

    + +

    This function will attempt to fetch an item from the cache store. If the item does not exist, the function will return FALSE.

    +$foo = $this->cache->get('my_cached_item'); + +

    save(id['string'], data['mixed'], ttl['int'])

    + +

    This function will save an item to the cache store. If saving fails, the function will return FALSE.

    +

    The optional third parameter (Time To Live) defaults to 60 seconds.

    +$this->cache->save('cache_item_id', 'data_to_cache'); + +

    delete(id['string'])

    + +

    This function will delete a specific item from the cache store. If item deletion fails, the function will return FALSE.

    +$this->cache->delete('cache_item_id'); + +

    clean()

    + +

    This function will 'clean' the entire cache. If the deletion of the cache files fails, the function will return FALSE.

    + +$this->cache->clean(); + +

    cache_info()

    + +

    This function will return information on the entire cache.

    + +var_dump($this->cache->cache_info()); + +

    get_metadata(id['string'])

    + +

    This function will return detailed information on a specific item in the cache.

    + +var_dump($this->cache->get_metadata('my_cached_item')); + +

    Drivers

    + +

    Alternative PHP Cache (APC) Caching

    + +

    All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:

    +$this->load->driver('cache');
    + $this->cache->apc->save('foo', 'bar', 10);
    +

    For more information on APC, please see http://php.net/apc

    + +

    File-based Caching

    + +

    Unlike caching from the Output Class, the driver file-based caching allows for pieces of view files to be cached. Use this with care, and make sure to benchmark your application, as a point can come where disk I/O will negate positive gains by caching.

    + +

    All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:

    +$this->load->driver('cache');
    + $this->cache->file->save('foo', 'bar', 10);
    + +

    Memcached Caching

    + +

    Multiple Memcached servers can be specified in the memcached.php configuration file, located in the application/config/ directory. + +

    All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:

    +$this->load->driver('cache');
    + $this->cache->memcached->save('foo', 'bar', 10);
    + +

    For more information on Memcached, please see http://php.net/memcached

    + +

    Dummy Cache

    + +

    This is a caching backend that will always 'miss.' It stores no data, but lets you keep your caching code in place in environments that don't support your chosen cache.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/calendar.html b/api/user_guide/libraries/calendar.html new file mode 100644 index 0000000..b42e22c --- /dev/null +++ b/api/user_guide/libraries/calendar.html @@ -0,0 +1,249 @@ + + + + + +Calendaring Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + + + +

    Calendaring Class

    + +

    The Calendar class enables you to dynamically create calendars. Your calendars can be formatted through the use of a calendar +template, allowing 100% control over every aspect of its design. In addition, you can pass data to your calendar cells.

    + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Calendar class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('calendar'); +

    Once loaded, the Calendar object will be available using: $this->calendar

    + + +

    Displaying a Calendar

    + +

    Here is a very simple example showing how you can display a calendar:

    + +$this->load->library('calendar');
    +
    +echo $this->calendar->generate();
    + +

    The above code will generate a calendar for the current month/year based on your server time. +To show a calendar for a specific month and year you will pass this information to the calendar generating function:

    + +$this->load->library('calendar');
    +
    +echo $this->calendar->generate(2006, 6);
    + +

    The above code will generate a calendar showing the month of June in 2006. The first parameter specifies the year, the second parameter specifies the month.

    + +

    Passing Data to your Calendar Cells

    + +

    To add data to your calendar cells involves creating an associative array in which the keys correspond to the days +you wish to populate and the array value contains the data. The array is passed to the third parameter of the calendar +generating function. Consider this example:

    + +$this->load->library('calendar');
    +
    +$data = array(
    +               3  => 'http://example.com/news/article/2006/03/',
    +               7  => 'http://example.com/news/article/2006/07/',
    +               13 => 'http://example.com/news/article/2006/13/',
    +               26 => 'http://example.com/news/article/2006/26/'
    +             );
    +
    +echo $this->calendar->generate(2006, 6, $data);
    + +

    Using the above example, day numbers 3, 7, 13, and 26 will become links pointing to the URLs you've provided.

    + +

    Note: By default it is assumed that your array will contain links. +In the section that explains the calendar template below you'll see how you can customize +how data passed to your cells is handled so you can pass different types of information.

    + + +

    Setting Display Preferences

    + +

    There are seven preferences you can set to control various aspects of the calendar. Preferences are set by passing an +array of preferences in the second parameter of the loading function. Here is an example:

    + + + +$prefs = array (
    +               'start_day'    => 'saturday',
    +               'month_type'   => 'long',
    +               'day_type'     => 'short'
    +             );
    +
    +$this->load->library('calendar', $prefs);
    +
    +echo $this->calendar->generate();
    + +

    The above code would start the calendar on saturday, use the "long" month heading, and the "short" day names. More information +regarding preferences below.

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    templateNoneNoneA string containing your calendar template. See the template section below.
    local_timetime()NoneA Unix timestamp corresponding to the current time.
    start_daysundayAny week day (sunday, monday, tuesday, etc.)Sets the day of the week the calendar should start on.
    month_typelonglong, shortDetermines what version of the month name to use in the header. long = January, short = Jan.
    day_typeabrlong, short, abrDetermines what version of the weekday names to use in the column headers. long = Sunday, short = Sun, abr = Su.
    show_next_prevFALSETRUE/FALSE (boolean)Determines whether to display links allowing you to toggle to next/previous months. See information on this feature below.
    next_prev_urlNoneA URLSets the basepath used in the next/previous calendar links.
    + + + +

    Showing Next/Previous Month Links

    + +

    To allow your calendar to dynamically increment/decrement via the next/previous links requires that you set up your calendar +code similar to this example:

    + + +$prefs = array (
    +               'show_next_prev'  => TRUE,
    +               'next_prev_url'   => 'http://example.com/index.php/calendar/show/'
    +             );
    +
    +$this->load->library('calendar', $prefs);
    +
    +echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
    + +

    You'll notice a few things about the above example:

    + +
      +
    • You must set the "show_next_prev" to TRUE.
    • +
    • You must supply the URL to the controller containing your calendar in the "next_prev_url" preference.
    • +
    • You must supply the "year" and "month" to the calendar generating function via the URI segments where they appear (Note: The calendar class automatically adds the year/month to the base URL you provide.).
    • +
    + + + +

    Creating a Calendar Template

    + +

    By creating a calendar template you have 100% control over the design of your calendar. Each component of your +calendar will be placed within a pair of pseudo-variables as shown here:

    + + + +$prefs['template'] = '

    +   {table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}
    +
    +   {heading_row_start}<tr>{/heading_row_start}
    +
    +   {heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
    +   {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
    +   {heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}
    +
    +   {heading_row_end}</tr>{/heading_row_end}
    +
    +   {week_row_start}<tr>{/week_row_start}
    +   {week_day_cell}<td>{week_day}</td>{/week_day_cell}
    +   {week_row_end}</tr>{/week_row_end}
    +
    +   {cal_row_start}<tr>{/cal_row_start}
    +   {cal_cell_start}<td>{/cal_cell_start}
    +
    +   {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
    +   {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}
    +
    +   {cal_cell_no_content}{day}{/cal_cell_no_content}
    +   {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
    +
    +   {cal_cell_blank}&nbsp;{/cal_cell_blank}
    +
    +   {cal_cell_end}</td>{/cal_cell_end}
    +   {cal_row_end}</tr>{/cal_row_end}
    +
    +   {table_close}</table>{/table_close}
    +';
    +
    +$this->load->library('calendar', $prefs);
    +
    +echo $this->calendar->generate();
    + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/cart.html b/api/user_guide/libraries/cart.html new file mode 100644 index 0000000..d0efa5f --- /dev/null +++ b/api/user_guide/libraries/cart.html @@ -0,0 +1,346 @@ + + + + + +Shopping Cart Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Shopping Cart Class

    + +

    The Cart Class permits items to be added to a session that stays active while a user is browsing your site. +These items can be retrieved and displayed in a standard "shopping cart" format, allowing the user to update the quantity or remove items from the cart.

    + +

    Please note that the Cart Class ONLY provides the core "cart" functionality. It does not provide shipping, credit card authorization, or other processing components.

    + + +

    Initializing the Shopping Cart Class

    + +

    Important: The Cart class utilizes CodeIgniter's +Session Class to save the cart information to a database, so before using the Cart class you must set up a database table +as indicated in the Session Documentation , and set the session preferences in your application/config/config.php file to utilize a database.

    + +

    To initialize the Shopping Cart Class in your controller constructor, use the $this->load->library function:

    + +$this->load->library('cart'); +

    Once loaded, the Cart object will be available using: $this->cart

    + +

    Note: The Cart Class will load and initialize the Session Class automatically, so unless you are using sessions elsewhere in your application, you do not need to load the Session class.

    + +

    Adding an Item to The Cart

    + +

    To add an item to the shopping cart, simply pass an array with the product information to the $this->cart->insert() function, as shown below:

    + + +$data = array(
    +               'id'      => 'sku_123ABC',
    +               'qty'     => 1,
    +               'price'   => 39.95,
    +               'name'    => 'T-Shirt',
    +               'options' => array('Size' => 'L', 'Color' => 'Red')
    +            );
    +
    + +$this->cart->insert($data); + +
    + +

    Important: The first four array indexes above (id, qty, price, and name) are required. +If you omit any of them the data will not be saved to the cart. The fifth index (options) is optional. +It is intended to be used in cases where your product has options associated with it. Use an array for options, as shown above.

    + +

    The five reserved indexes are:

    + +
      +
    • id - Each product in your store must have a unique identifier. Typically this will be an "sku" or other such identifier.
    • +
    • qty - The quantity being purchased. +
    • price - The price of the item. +
    • name - The name of the item. +
    • options - Any additional attributes that are needed to identify the product. These must be passed via an array. +
    + +

    In addition to the five indexes above, there are two reserved words: rowid and subtotal. These are used internally by the Cart class, so +please do NOT use those words as index names when inserting data into the cart.

    + +

    Your array may contain additional data. Anything you include in your array will be stored in the session. However, it is best to standardize your data among all your products in order to make displaying the information in a table easier.

    + +

    The insert() method will return the $rowid if you successfully insert a single item.

    + + +

    Adding Multiple Items to The Cart

    + +

    By using a multi-dimensional array, as shown below, it is possible to add multiple products to the cart in one action. This is useful in cases where you wish to allow people to select from among several items on the same page.

    + + + +$data = array(
    + +               array(
    +                       'id'      => 'sku_123ABC',
    +                       'qty'     => 1,
    +                       'price'   => 39.95,
    +                       'name'    => 'T-Shirt',
    +                       'options' => array('Size' => 'L', 'Color' => 'Red')
    +                    ),
    + +               array(
    +                       'id'      => 'sku_567ZYX',
    +                       'qty'     => 1,
    +                       'price'   => 9.95,
    +                       'name'    => 'Coffee Mug'
    +                    ),
    + +               array(
    +                       'id'      => 'sku_965QRS',
    +                       'qty'     => 1,
    +                       'price'   => 29.95,
    +                       'name'    => 'Shot Glass'
    +                    )
    + +            );
    +
    + +$this->cart->insert($data); + +
    + + + + +

    Displaying the Cart

    + +

    To display the cart you will create a view file with code similar to the one shown below.

    + +

    Please note that this example uses the form helper.

    + + + + + + + +

    Updating The Cart

    + +

    To update the information in your cart, you must pass an array containing the Row ID and quantity to the $this->cart->update() function:

    + +

    Note: If the quantity is set to zero, the item will be removed from the cart.

    + + +$data = array(
    +               'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
    +               'qty'   => 3
    +            );
    +
    + +$this->cart->update($data); +

    +// Or a multi-dimensional array

    +$data = array(
    + +               array(
    +                       'rowid'   => 'b99ccdf16028f015540f341130b6d8ec',
    +                       'qty'     => 3
    +                    ),
    + +               array(
    +                       'rowid'   => 'xw82g9q3r495893iajdh473990rikw23',
    +                       'qty'     => 4
    +                    ),
    + +               array(
    +                       'rowid'   => 'fh4kdkkkaoe30njgoe92rkdkkobec333',
    +                       'qty'     => 2
    +                    )
    + +            );
    +
    + +$this->cart->update($data); + + + + +
    + +

    What is a Row ID?  The row ID is a unique identifier that is generated by the cart code when an item is added to the cart. The reason a +unique ID is created is so that identical products with different options can be managed by the cart.

    + +

    For example, let's say someone buys two identical t-shirts (same product ID), but in different sizes. The product ID (and other attributes) will be +identical for both sizes because it's the same shirt. The only difference will be the size. The cart must therefore have a means of identifying this +difference so that the two sizes of shirts can be managed independently. It does so by creating a unique "row ID" based on the product ID and any options associated with it.

    + +

    In nearly all cases, updating the cart will be something the user does via the "view cart" page, so as a developer, it is unlikely that you will ever have to concern yourself +with the "row ID", other then making sure your "view cart" page contains this information in a hidden form field, and making sure it gets passed to the update +function when the update form is submitted. Please examine the construction of the "view cart" page above for more information.

    + + + +

     

    + + +

    Function Reference

    + +

    $this->cart->insert();

    + +

    Permits you to add items to the shopping cart, as outlined above.

    + + +

    $this->cart->update();

    + +

    Permits you to update items in the shopping cart, as outlined above.

    + + +

    $this->cart->total();

    + +

    Displays the total amount in the cart.

    + + +

    $this->cart->total_items();

    + +

    Displays the total number of items in the cart.

    + + +

    $this->cart->contents();

    + +

    Returns an array containing everything in the cart.

    + + + +

    $this->cart->has_options(rowid);

    + +

    Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.

    + + +

    $this->cart->product_options(rowid);

    + +

    Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.

    + + + +

    $this->cart->destroy();

    + +

    Permits you to destroy the cart. This function will likely be called when you are finished processing the customer's order.

    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/config.html b/api/user_guide/libraries/config.html new file mode 100644 index 0000000..1fabc95 --- /dev/null +++ b/api/user_guide/libraries/config.html @@ -0,0 +1,222 @@ + + + + + +Config Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Config Class

    + +

    The Config class provides a means to retrieve configuration preferences. These preferences can +come from the default config file (application/config/config.php) or from your own custom config files.

    + +

    Note: This class is initialized automatically by the system so there is no need to do it manually.

    + + +

    Anatomy of a Config File

    + +

    By default, CodeIgniter has one primary config file, located at application/config/config.php. If you open the file using +your text editor you'll see that config items are stored in an array called $config.

    + +

    You can add your own config items to +this file, or if you prefer to keep your configuration items separate (assuming you even need config items), +simply create your own file and save it in config folder.

    + +

    Note: If you do create your own config files use the same format as the primary one, storing your items in +an array called $config. CodeIgniter will intelligently manage these files so there will be no conflict even though +the array has the same name (assuming an array index is not named the same as another).

    + +

    Loading a Config File

    + +

    Note: CodeIgniter automatically loads the primary config file (application/config/config.php), +so you will only need to load a config file if you have created your own.

    + +

    There are two ways to load a config file:

    + +
    1. Manual Loading + +

      To load one of your custom config files you will use the following function within the controller that needs it:

      + +$this->config->load('filename'); + +

      Where filename is the name of your config file, without the .php file extension.

      + +

      If you need to load multiple config files normally they will be merged into one master config array. Name collisions can occur, however, if +you have identically named array indexes in different config files. To avoid collisions you can set the second parameter to TRUE +and each config file will be stored in an array index corresponding to the name of the config file. Example:

      + + +// Stored in an array with this prototype: $this->config['blog_settings'] = $config
      +$this->config->load('blog_settings', TRUE);
      + +

      Please see the section entitled Fetching Config Items below to learn how to retrieve config items set this way.

      + +

      The third parameter allows you to suppress errors in the event that a config file does not exist:

      + +$this->config->load('blog_settings', FALSE, TRUE); + +
    2. +
    3. Auto-loading + +

      If you find that you need a particular config file globally, you can have it loaded automatically by the system. To do this, +open the autoload.php file, located at application/config/autoload.php, and add your config file as +indicated in the file.

      +
    4. +
    + + +

    Fetching Config Items

    + +

    To retrieve an item from your config file, use the following function:

    + +$this->config->item('item name'); + +

    Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you'll do this:

    + +$lang = $this->config->item('language'); + +

    The function returns FALSE (boolean) if the item you are trying to fetch does not exist.

    + +

    If you are using the second parameter of the $this->config->load function in order to assign your config items to a specific index +you can retrieve it by specifying the index name in the second parameter of the $this->config->item() function. Example:

    + + +// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
    +$this->config->load('blog_settings', TRUE);

    + +// Retrieve a config item named site_name contained within the blog_settings array
    +$site_name = $this->config->item('site_name', 'blog_settings');

    + +// An alternate way to specify the same item:
    +$blog_config = $this->config->item('blog_settings');
    +$site_name = $blog_config['site_name'];
    + +

    Setting a Config Item

    + +

    If you would like to dynamically set a config item or change an existing one, you can do so using:

    + +$this->config->set_item('item_name', 'item_value'); + +

    Where item_name is the $config array index you want to change, and item_value is its value.

    + + +

    Environments

    + +

    + You may load different configuration files depending on the current environment. + The ENVIRONMENT constant is defined in index.php, and is described + in detail in the Handling Environments + section. +

    + +

    + To create an environment-specific configuration file, + create or copy a configuration file in application/config/{ENVIRONMENT}/{FILENAME}.php +

    + +

    For example, to create a production-only config.php, you would:

    + +
      +
    1. Create the directory application/config/production/
    2. +
    3. Copy your existing config.php into the above directory
    4. +
    5. Edit application/config/production/config.php so it contains your production settings
    6. +
    + +

    + When you set the ENVIRONMENT constant to 'production', the settings + for your new production-only config.php will be loaded. +

    + +

    You can place the following configuration files in environment-specific folders:

    + +
      +
    • Default CodeIgniter configuration files
    • +
    • Your own custom configuration files
    • +
    + +

    Note: CodeIgniter always tries to load the configuration files for the current environment first. If the file does not exist, the global config file (i.e., the one in application/config/) is loaded. This means you are not obligated to place all of your configuration files in an environment folder − only the files that change per environment.

    + +

    Helper Functions

    + +

    The config class has the following helper functions:

    + +

    $this->config->site_url();

    +

    This function retrieves the URL to your site, along with the "index" value you've specified in the config file.

    + +

    $this->config->base_url();

    +

    This function retrieves the URL to your site, plus an optional path such as to a stylesheet or image.

    + +

    The two functions above are normally accessed via the corresponding functions in the URL Helper.

    + +

    $this->config->system_url();

    +

    This function retrieves the URL to your system folder.

    + + +
    + + + + + + + diff --git a/api/user_guide/libraries/email.html b/api/user_guide/libraries/email.html new file mode 100644 index 0000000..d286ffe --- /dev/null +++ b/api/user_guide/libraries/email.html @@ -0,0 +1,307 @@ + + + + + +Email Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Email Class

    + +

    CodeIgniter's robust Email Class supports the following features:

    + + +
      +
    • Multiple Protocols: Mail, Sendmail, and SMTP
    • +
    • Multiple recipients
    • +
    • CC and BCCs
    • +
    • HTML or Plaintext email
    • +
    • Attachments
    • +
    • Word wrapping
    • +
    • Priorities
    • +
    • BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
    • +
    • Email Debugging tools
    • +
    + + +

    Sending Email

    + +

    Sending email is not only simple, but you can configure it on the fly or set your preferences in a config file.

    + +

    Here is a basic example demonstrating how you might send email. Note: This example assumes you are sending the email from one of your +controllers.

    + +$this->load->library('email');
    +
    +$this->email->from('your@example.com', 'Your Name');
    +$this->email->to('someone@example.com');
    +$this->email->cc('another@another-example.com');
    +$this->email->bcc('them@their-example.com');
    +
    +$this->email->subject('Email Test');
    +$this->email->message('Testing the email class.');
    +
    +$this->email->send();
    +
    +echo $this->email->print_debugger();
    + + + + +

    Setting Email Preferences

    + +

    There are 17 different preferences available to tailor how your email messages are sent. You can either set them manually +as described here, or automatically via preferences stored in your config file, described below:

    + +

    Preferences are set by passing an array of preference values to the email initialize function. Here is an example of how you might set some preferences:

    + +$config['protocol'] = 'sendmail';
    +$config['mailpath'] = '/usr/sbin/sendmail';
    +$config['charset'] = 'iso-8859-1';
    +$config['wordwrap'] = TRUE;
    +
    +$this->email->initialize($config);
    + +

    Note: Most of the preferences have default values that will be used if you do not set them.

    Setting Email Preferences in a Config File

    + +

    If you prefer not to set preferences using the above method, you can instead put them into a config file. +Simply create a new file called the email.php, add the $config +array in that file. Then save the file at config/email.php and it will be used automatically. You +will NOT need to use the $this->email->initialize() function if you save your preferences in a config file.

    + + + + +

    Email Preferences

    + +

    The following is a list of all the preferences that can be set when sending email.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    useragentCodeIgniterNoneThe "user agent".
    protocolmailmail, sendmail, or smtpThe mail sending protocol.
    mailpath/usr/sbin/sendmailNoneThe server path to Sendmail.
    smtp_hostNo DefaultNoneSMTP Server Address.
    smtp_userNo DefaultNoneSMTP Username.
    smtp_passNo DefaultNoneSMTP Password.
    smtp_port25NoneSMTP Port.
    smtp_timeout5NoneSMTP Timeout (in seconds).
    wordwrapTRUETRUE or FALSE (boolean)Enable word-wrap.
    wrapchars76 Character count to wrap at.
    mailtypetexttext or htmlType of mail. If you send HTML email you must send it as a complete web page. Make sure you don't have any relative links or relative image paths otherwise they will not work.
    charsetutf-8Character set (utf-8, iso-8859-1, etc.).
    validateFALSETRUE or FALSE (boolean)Whether to validate the email address.
    priority31, 2, 3, 4, 5Email Priority. 1 = highest. 5 = lowest. 3 = normal.
    crlf\n"\r\n" or "\n" or "\r"Newline character. (Use "\r\n" to comply with RFC 822).
    newline\n"\r\n" or "\n" or "\r"Newline character. (Use "\r\n" to comply with RFC 822).
    bcc_batch_modeFALSETRUE or FALSE (boolean)Enable BCC Batch Mode.
    bcc_batch_size200NoneNumber of emails in each BCC batch.
    + + +

    Email Function Reference

    + +

    $this->email->from()

    +

    Sets the email address and name of the person sending the email:

    +$this->email->from('you@example.com', 'Your Name'); + +

    $this->email->reply_to()

    +

    Sets the reply-to address. If the information is not provided the information in the "from" function is used. Example:

    +$this->email->reply_to('you@example.com', 'Your Name'); + + +

    $this->email->to()

    +

    Sets the email address(s) of the recipient(s). Can be a single email, a comma-delimited list or an array:

    + +$this->email->to('someone@example.com'); +$this->email->to('one@example.com, two@example.com, three@example.com'); + +$list = array('one@example.com', 'two@example.com', 'three@example.com');
    +
    +$this->email->to($list);
    + +

    $this->email->cc()

    +

    Sets the CC email address(s). Just like the "to", can be a single email, a comma-delimited list or an array.

    + +

    $this->email->bcc()

    +

    Sets the BCC email address(s). Just like the "to", can be a single email, a comma-delimited list or an array.

    + + +

    $this->email->subject()

    +

    Sets the email subject:

    +$this->email->subject('This is my subject'); + +

    $this->email->message()

    +

    Sets the email message body:

    +$this->email->message('This is my message'); + +

    $this->email->set_alt_message()

    +

    Sets the alternative email message body:

    +$this->email->set_alt_message('This is the alternative message'); + +

    This is an optional message string which can be used if you send HTML formatted email. It lets you specify an alternative +message with no HTML formatting which is added to the header string for people who do not accept HTML email. +If you do not set your own message CodeIgniter will extract the message from your HTML email and strip the tags.

    + + + +

    $this->email->clear()

    +

    Initializes all the email variables to an empty state. This function is intended for use if you run the email sending function +in a loop, permitting the data to be reset between cycles.

    +foreach ($list as $name => $address)
    +{
    +    $this->email->clear();

    + +    $this->email->to($address);
    +    $this->email->from('your@example.com');
    +    $this->email->subject('Here is your info '.$name);
    +    $this->email->message('Hi '.$name.' Here is the info you requested.');
    +    $this->email->send();
    +}
    + +

    If you set the parameter to TRUE any attachments will be cleared as well:

    + +$this->email->clear(TRUE); + + +

    $this->email->send()

    +

    The Email sending function. Returns boolean TRUE or FALSE based on success or failure, enabling it to be used +conditionally:

    + +if ( ! $this->email->send())
    +{
    +    // Generate error
    +}
    + + +

    $this->email->attach()

    +

    Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. +For multiple attachments use the function multiple times. For example:

    + +$this->email->attach('/path/to/photo1.jpg');
    +$this->email->attach('/path/to/photo2.jpg');
    +$this->email->attach('/path/to/photo3.jpg');
    +
    +$this->email->send();
    + + +

    $this->email->print_debugger()

    +

    Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging.

    + + +

    Overriding Word Wrapping

    + +

    If you have word wrapping enabled (recommended to comply with RFC 822) and you have a very long link in your email it can +get wrapped too, causing it to become un-clickable by the person receiving it. CodeIgniter lets you manually override +word wrapping within part of your message like this:

    + +The text of your email that
    +gets wrapped normally.
    +
    +{unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}
    +
    +More text that will be
    +wrapped normally.
    + +

    Place the item you do not want word-wrapped between: {unwrap} {/unwrap}

    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/encryption.html b/api/user_guide/libraries/encryption.html new file mode 100644 index 0000000..cd59a6c --- /dev/null +++ b/api/user_guide/libraries/encryption.html @@ -0,0 +1,224 @@ + + + + + +Encryption Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Encryption Class

    + +

    The Encryption Class provides two-way data encryption. It uses a scheme that either compiles +the message using a randomly hashed bitwise XOR encoding scheme, or is encrypted using +the Mcrypt library. If Mcrypt is not available on your server the encoded message will +still provide a reasonable degree of security for encrypted sessions or other such "light" purposes. +If Mcrypt is available, you'll be provided with a high degree of security appropriate for storage.

    + + +

    Setting your Key

    + +

    A key is a piece of information that controls the cryptographic process and permits an encrypted string to be decoded. +In fact, the key you chose will provide the only means to decode data that was encrypted with that key, +so not only must you choose the key carefully, you must never change it if you intend use it for persistent data.

    + +

    It goes without saying that you should guard your key carefully. +Should someone gain access to your key, the data will be easily decoded. If your server is not totally under your control +it's impossible to ensure key security so you may want to think carefully before using it for anything +that requires high security, like storing credit card numbers.

    + +

    To take maximum advantage of the encryption algorithm, your key should be 32 characters in length (128 bits). +The key should be as random a string as you can concoct, with numbers and uppercase and lowercase letters. +Your key should not be a simple text string. In order to be cryptographically secure it +needs to be as random as possible.

    + +

    Your key can be either stored in your application/config/config.php, or you can design your own +storage mechanism and pass the key dynamically when encoding/decoding.

    + +

    To save your key to your application/config/config.php, open the file and set:

    +$config['encryption_key'] = "YOUR KEY"; + + +

    Message Length

    + +

    It's important for you to know that the encoded messages the encryption function generates will be approximately 2.6 times longer than the original +message. For example, if you encrypt the string "my super secret data", which is 21 characters in length, you'll end up +with an encoded string that is roughly 55 characters (we say "roughly" because the encoded string length increments in +64 bit clusters, so it's not exactly linear). Keep this information in mind when selecting your data storage mechanism. Cookies, +for example, can only hold 4K of information.

    + + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Encryption class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('encrypt'); +

    Once loaded, the Encrypt library object will be available using: $this->encrypt

    + + +

    $this->encrypt->encode()

    + +

    Performs the data encryption and returns it as a string. Example:

    + +$msg = 'My secret message';
    +
    +$encrypted_string = $this->encrypt->encode($msg);
    + +

    You can optionally pass your encryption key via the second parameter if you don't want to use the one in your config file:

    + + +$msg = 'My secret message';
    +$key = 'super-secret-key';
    +
    +$encrypted_string = $this->encrypt->encode($msg, $key);
    + + +

    $this->encrypt->decode()

    + +

    Decrypts an encoded string. Example:

    + + +$encrypted_string = 'APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84';
    +
    +$plaintext_string = $this->encrypt->decode($encrypted_string);
    + +

    You can optionally pass your encryption key via the second parameter if you don't want to use the one in your config file:

    + + +$msg = 'My secret message';
    +$key = 'super-secret-key';
    +
    +$encrypted_string = $this->encrypt->decode($msg, $key);
    + + +

    $this->encrypt->set_cipher();

    + +

    Permits you to set an Mcrypt cipher. By default it uses MCRYPT_RIJNDAEL_256. Example:

    +$this->encrypt->set_cipher(MCRYPT_BLOWFISH); +

    Please visit php.net for a list of available ciphers.

    + +

    If you'd like to manually test whether your server supports Mcrypt you can use:

    +echo ( ! function_exists('mcrypt_encrypt')) ? 'Nope' : 'Yup'; + + +

    $this->encrypt->set_mode();

    + +

    Permits you to set an Mcrypt mode. By default it uses MCRYPT_MODE_CBC. Example:

    +$this->encrypt->set_mode(MCRYPT_MODE_CFB); +

    Please visit php.net for a list of available modes.

    + + +

    $this->encrypt->sha1();

    +

    SHA1 encoding function. Provide a string and it will return a 160 bit one way hash. Note: SHA1, just like MD5 is non-decodable. Example:

    +$hash = $this->encrypt->sha1('Some string'); + +

    Many PHP installations have SHA1 support by default so if all you need is to encode a hash it's simpler to use the native +function:

    + +$hash = sha1('Some string'); + +

    If your server does not support SHA1 you can use the provided function.

    + +

    $this->encrypt->encode_from_legacy($orig_data, $legacy_mode = MCRYPT_MODE_ECB, $key = '');

    +

    Enables you to re-encode data that was originally encrypted with CodeIgniter 1.x to be compatible with the Encryption library in CodeIgniter 2.x. It is only + necessary to use this method if you have encrypted data stored permanently such as in a file or database and are on a server that supports Mcrypt. "Light" use encryption + such as encrypted session data or transitory encrypted flashdata require no intervention on your part. However, existing encrypted Sessions will be + destroyed since data encrypted prior to 2.x will not be decoded.

    + +

    Why only a method to re-encode the data instead of maintaining legacy methods for both encoding and decoding? The algorithms in + the Encryption library have improved in CodeIgniter 2.x both for performance and security, and we do not wish to encourage continued use of the older methods. + You can of course extend the Encryption library if you wish and replace the new methods with the old and retain seamless compatibility with CodeIgniter 1.x + encrypted data, but this a decision that a developer should make cautiously and deliberately, if at all.

    + +$new_data = $this->encrypt->encode_from_legacy($old_encrypted_string); + + + + + + + + + + + + + + + + + + + + + + +
    ParameterDefaultDescription
    $orig_datan/aThe original encrypted data from CodeIgniter 1.x's Encryption library
    $legacy_modeMCRYPT_MODE_ECBThe Mcrypt mode that was used to generate the original encrypted data. CodeIgniter 1.x's default was MCRYPT_MODE_ECB, and it will + assume that to be the case unless overridden by this parameter.
    $keyn/aThe encryption key. This it typically specified in your config file as outlined above.
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/file_uploading.html b/api/user_guide/libraries/file_uploading.html new file mode 100644 index 0000000..9759d0c --- /dev/null +++ b/api/user_guide/libraries/file_uploading.html @@ -0,0 +1,451 @@ + + + + + +File Uploading Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    File Uploading Class

    + +

    CodeIgniter's File Uploading Class permits files to be uploaded. You can set various +preferences, restricting the type and size of the files.

    + + +

    The Process

    + +

    Uploading a file involves the following general process:

    + + +
      +
    • An upload form is displayed, allowing a user to select a file and upload it.
    • +
    • When the form is submitted, the file is uploaded to the destination you specify.
    • +
    • Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set.
    • +
    • Once uploaded, the user will be shown a success message.
    • +
    + +

    To demonstrate this process here is brief tutorial. Afterward you'll find reference information.

    + +

    Creating the Upload Form

    + + + +

    Using a text editor, create a form called upload_form.php. In it, place this code and save it to your applications/views/ +folder:

    + + + + +

    You'll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper +creates the proper syntax for you. You'll also notice we have an $error variable. This is so we can show error messages in the event +the user does something wrong.

    + + +

    The Success Page

    + +

    Using a text editor, create a form called upload_success.php. +In it, place this code and save it to your applications/views/ folder:

    + + + + +

    The Controller

    + +

    Using a text editor, create a controller called upload.php. In it, place this code and save it to your applications/controllers/ +folder:

    + + + + + +

    The Upload Folder

    + +

    You'll need a destination folder for your uploaded images. Create a folder at the root of your CodeIgniter installation called +uploads and set its file permissions to 777.

    + + +

    Try it!

    + +

    To try your form, visit your site using a URL similar to this one:

    + +example.com/index.php/upload/ + +

    You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your +controller is correct it should work.

    + + +

     

    + +

    Reference Guide

    + + +

    Initializing the Upload Class

    + +

    Like most other classes in CodeIgniter, the Upload class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('upload'); +

    Once the Upload class is loaded, the object will be available using: $this->upload

    + + +

    Setting Preferences

    + +

    Similar to other libraries, you'll control what is allowed to be upload based on your preferences. In the controller you +built above you set the following preferences:

    + +$config['upload_path'] = './uploads/';
    +$config['allowed_types'] = 'gif|jpg|png';
    +$config['max_size'] = '100';
    +$config['max_width'] = '1024';
    +$config['max_height'] = '768';
    +
    +$this->load->library('upload', $config);

    + +// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
    +$this->upload->initialize($config);
    + +

    The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.

    + + +

    Preferences

    + +

    The following preferences are available. The default value indicates what will be used if you do not specify that preference.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    upload_pathNoneNoneThe path to the folder where the upload should be placed. The folder must be writable and the path can be absolute or relative.
    allowed_typesNoneNoneThe mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Separate multiple types with a pipe.
    file_nameNoneDesired file name +

    If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type.

    +
    overwriteFALSETRUE/FALSE (boolean)If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists.
    max_size0NoneThe maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.
    max_width0NoneThe maximum width (in pixels) that the file can be. Set to zero for no limit.
    max_height0NoneThe maximum height (in pixels) that the file can be. Set to zero for no limit.
    max_filename0NoneThe maximum length that a file name can be. Set to zero for no limit.
    encrypt_nameFALSETRUE/FALSE (boolean)If set to TRUE the file name will be converted to a random encrypted string. This can be useful if you would like the file saved with a name that can not be discerned by the person uploading it.
    remove_spacesTRUETRUE/FALSE (boolean)If set to TRUE, any spaces in the file name will be converted to underscores. This is recommended.
    + + +

    Setting preferences in a config file

    + +

    If you prefer not to set preferences using the above method, you can instead put them into a config file. +Simply create a new file called the upload.php, add the $config +array in that file. Then save the file in: config/upload.php and it will be used automatically. You +will NOT need to use the $this->upload->initialize function if you save your preferences in a config file.

    + + +

    Function Reference

    + +

    The following functions are available

    + + +

    $this->upload->do_upload()

    + +

    Performs the upload based on the preferences you've set. Note: By default the upload routine expects the file to come from a form field +called userfile, and the form must be a "multipart type:

    + +<form method="post" action="some_action" enctype="multipart/form-data" /> + +

    If you would like to set your own field name simply pass its value to the do_upload function:

    + + +$field_name = "some_field_name";
    +$this->upload->do_upload($field_name)
    + + +

    $this->upload->display_errors()

    + +

    Retrieves any error messages if the do_upload() function returned false. The function does not echo automatically, it +returns the data so you can assign it however you need.

    + +

    Formatting Errors

    +

    By default the above function wraps any errors within <p> tags. You can set your own delimiters like this:

    + +$this->upload->display_errors('<p>', '</p>'); + +

    $this->upload->data()

    + +

    This is a helper function that returns an array containing all of the data related to the file you uploaded. +Here is the array prototype:

    + +Array
    +(
    +    [file_name]    => mypic.jpg
    +    [file_type]    => image/jpeg
    +    [file_path]    => /path/to/your/upload/
    +    [full_path]    => /path/to/your/upload/jpg.jpg
    +    [raw_name]     => mypic
    +    [orig_name]    => mypic.jpg
    +    [client_name]  => mypic.jpg
    +    [file_ext]     => .jpg
    +    [file_size]    => 22.2
    +    [is_image]     => 1
    +    [image_width]  => 800
    +    [image_height] => 600
    +    [image_type]   => jpeg
    +    [image_size_str] => width="800" height="200"
    +)
    + +

    Explanation

    + +

    Here is an explanation of the above array items.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ItemDescription
    file_nameThe name of the file that was uploaded including the file extension.
    file_typeThe file's Mime type
    file_pathThe absolute server path to the file
    full_pathThe absolute server path including the file name
    raw_nameThe file name without the extension
    orig_nameThe original file name. This is only useful if you use the encrypted name option.
    client_nameThe file name as supplied by the client user agent, prior to any file name preparation or incrementing.
    file_extThe file extension with period
    file_sizeThe file size in kilobytes
    is_imageWhether the file is an image or not. 1 = image. 0 = not.
    image_widthImage width.
    image_heightImage height
    image_typeImage type. Typically the file extension without the period.
    image_size_strA string containing the width and height. Useful to put into an image tag.
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/form_validation.html b/api/user_guide/libraries/form_validation.html new file mode 100644 index 0000000..b04dac2 --- /dev/null +++ b/api/user_guide/libraries/form_validation.html @@ -0,0 +1,1250 @@ + + + + + +Form Validation : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Form Validation

    + +

    CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you'll write.

    + + + + + + + + +

     

    + + +

    Overview

    + + +

    Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:

    + +
      +
    1. A form is displayed.
    2. +
    3. You fill it in and submit it.
    4. +
    5. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data +along with an error message describing the problem.
    6. +
    7. This process continues until you have submitted a valid form.
    8. +
    + +

    On the receiving end, the script must:

    + +
      +
    1. Check for required data.
    2. +
    3. Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted +it must be validated to contain only permitted characters. It must be of a minimum length, +and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.
    4. +
    5. Sanitize the data for security.
    6. +
    7. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)
    8. +
    9. Prep the data for insertion in the database.
    10. +
    + + +

    Although there is nothing terribly complex about the above process, it usually requires a significant +amount of code, and to display error messages, various control structures are usually placed within the form HTML. +Form validation, while simple to create, is generally very messy and tedious to implement.

    + +

     

    + + + +

    Form Validation Tutorial

    + +

    What follows is a "hands on" tutorial for implementing CodeIgniters Form Validation.

    + + +

    In order to implement form validation you'll need three things:

    + +
      +
    1. A View file containing a form.
    2. +
    3. A View file containing a "success" message to be displayed upon successful submission.
    4. +
    5. A controller function to receive and process the submitted data.
    6. +
    + +

    Let's create those three things, using a member sign-up form as the example.

    + + + + + +

    The Form

    + +

    Using a text editor, create a form called myform.php. In it, place this code and save it to your applications/views/ +folder:

    + + + + + + + + +

    The Success Page

    + + +

    Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your applications/views/ +folder:

    + + + + + + + +

    The Controller

    + +

    Using a text editor, create a controller called form.php. In it, place this code and save it to your applications/controllers/ +folder:

    + + + + + +

    Try it!

    + +

    To try your form, visit your site using a URL similar to this one:

    + +example.com/index.php/form/ + +

    If you submit the form you should simply see the form reload. That's because you haven't set up any validation +rules yet.

    + +

    Since you haven't told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default. The run() +function only returns TRUE if it has successfully applied your rules without any of them failing.

    + + +

    Explanation

    + +

    You'll notice several things about the above pages:

    + +

    The form (myform.php) is a standard web form with a couple exceptions:

    + +
      +
    1. It uses a form helper to create the form opening. +Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper +is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable in the event your URLs change.
    2. + +
    3. At the top of the form you'll notice the following function call: +<?php echo validation_errors(); ?> + +

      This function will return any error messages sent back by the validator. If there are no messages it returns an empty string.

      +
    4. +
    + +

    The controller (form.php) has one function: index(). This function initializes the validation class and +loads the form helper and URL helper used by your view files. It also runs +the validation routine. Based on +whether the validation was successful it either presents the form or the success page.

    + + + + + + +

    Setting Validation Rules

    + +

    CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data +at the same time. To set validation rules you will use the set_rules() function:

    + +$this->form_validation->set_rules(); + +

    The above function takes three parameters as input:

    + +
      +
    1. The field name - the exact name you've given the form field.
    2. +
    3. A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
    4. +
    5. The validation rules for this form field.
    6. +
    + + +


    Here is an example. In your controller (form.php), add this code just below the validation initialization function:

    + + +$this->form_validation->set_rules('username', 'Username', 'required');
    +$this->form_validation->set_rules('password', 'Password', 'required');
    +$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
    +$this->form_validation->set_rules('email', 'Email', 'required');
    +
    + +

    Your controller should now look like this:

    + + + +

    Now submit the form with the fields blank and you should see the error messages. +If you submit the form with all the fields populated you'll see your success page.

    + +

    Note: The form fields are not yet being re-populated with the data when +there is an error. We'll get to that shortly.

    + + + + + +

    Setting Rules Using an Array

    + +

    Before moving on it should be noted that the rule setting function can be passed an array if you prefer to set all your rules in one action. +If you use this approach you must name your array keys as indicated:

    + + +$config = array(
    +               array(
    +                     'field'   => 'username',
    +                     'label'   => 'Username',
    +                     'rules'   => 'required'
    +                  ),
    +               array(
    +                     'field'   => 'password',
    +                     'label'   => 'Password',
    +                     'rules'   => 'required'
    +                  ),
    +               array(
    +                     'field'   => 'passconf',
    +                     'label'   => 'Password Confirmation',
    +                     'rules'   => 'required'
    +                  ),   
    +               array(
    +                     'field'   => 'email',
    +                     'label'   => 'Email',
    +                     'rules'   => 'required'
    +                  )
    +            );
    +
    +$this->form_validation->set_rules($config); +
    + + + + + + + +

    Cascading Rules

    + +

    CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules in the third parameter of rule setting function, like this:

    + + +$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');
    +$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
    +$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
    +$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
    +
    + +

    The above code sets the following rules:

    + +
      +
    1. The username field be no shorter than 5 characters and no longer than 12.
    2. +
    3. The password field must match the password confirmation field.
    4. +
    5. The email field must contain a valid email address.
    6. +
    + +

    Give it a try! Submit your form without the proper data and you'll see new error messages that correspond to your new rules. +There are numerous rules available which you can read about in the validation reference.

    + + + + +

    Prepping Data

    + +

    In addition to the validation functions like the ones we used above, you can also prep your data in various ways. +For example, you can set up rules like this:

    + + +$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
    +$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
    +$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
    +$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
    +
    + + +

    In the above example, we are "trimming" the fields, converting the password to MD5, and running the username through +the "xss_clean" function, which removes malicious data.

    + +

    Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, +trim, MD5, etc.

    + +

    Note: You will generally want to use the prepping functions after +the validation rules so if there is an error, the original data will be shown in the form.

    + + + + + +

    Re-populating the form

    + +

    Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. CodeIgniter offers several helper functions +that permit you to do this. The one you will use most commonly is:

    + +set_value('field name') + + +

    Open your myform.php view file and update the value in each field using the set_value() function:

    + +

    Don't forget to include each field name in the set_value() functions!

    + + + + + +

    Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated

    + +

    Note: The Function Reference section below contains functions that +permit you to re-populate <select> menus, radio buttons, and checkboxes.

    + + +

    Important Note: If you use an array as the name of a form field, you must supply it as an array to the function. Example:

    + +<input type="text" name="colors[]" value="<?php echo set_value('colors[]'); ?>" size="50" /> + +

    For more info please see the Using Arrays as Field Names section below.

    + + + + + + +

    Callbacks: Your own Validation Functions

    + +

    The validation system supports callbacks to your own validation functions. This permits you to extend the validation class +to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can +create a callback function that does that. Let's create a example of this.

    + +

    In your controller, change the "username" rule to this:

    + +$this->form_validation->set_rules('username', 'Username', 'callback_username_check'); + +

    Then add a new function called username_check to your controller. Here's how your controller should now look:

    + + + +

    Reload your form and submit it with the word "test" as the username. You can see that the form field data was passed to your +callback function for you to process.

    + +

    To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix. If you need +to receive an extra parameter in your callback function, just add it normally after the function name between square brackets, +as in: "callback_foo[bar]", then it will be passed as the second argument of your callback function.

    + +

    Note: You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE +it is assumed that the data is your newly processed form data.

    + + +

    Setting Error Messages

    + + +

    All of the native error messages are located in the following language file: language/english/form_validation_lang.php

    + +

    To set your own custom message you can either edit that file, or use the following function:

    + +$this->form_validation->set_message('rule', 'Error Message'); + +

    Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.

    + +

    If you include %s in your error string, it will be replaced with the "human" name you used for your field when you set your rules.

    + +

    In the "callback" example above, the error message was set by passing the name of the function:

    + +$this->form_validation->set_message('username_check') + +

    You can also override any error message found in the language file. For example, to change the message for the "required" rule you will do this:

    + +$this->form_validation->set_message('required', 'Your custom message here'); + + + + +

    Translating Field Names

    + +

    If you would like to store the "human" name you passed to the set_rules() function in a language file, and therefore make the name able to be translated, here's how:

    + +

    First, prefix your "human" name with lang:, as in this example:

    + + +$this->form_validation->set_rules('first_name', 'lang:first_name', 'required');
    +
    + +

    Then, store the name in one of your language file arrays (without the prefix):

    + +$lang['first_name'] = 'First Name'; + +

    Note: If you store your array item in a language file that is not loaded automatically by CI, you'll need to remember to load it in your controller using:

    + +$this->lang->load('file_name'); + +

    See the Language Class page for more info regarding language files.

    + + + +

    Changing the Error Delimiters

    + +

    By default, the Form Validation class adds a paragraph tag (<p>) around each error message shown. You can either change these delimiters globally or +individually.

    + +
      + +
    1. Changing delimiters Globally + +

      To globally change the error delimiters, in your controller function, just after loading the Form Validation class, add this:

      + +$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); + +

      In this example, we've switched to using div tags.

      + +
    2. + +
    3. Changing delimiters Individually + +

      Each of the two error generating functions shown in this tutorial can be supplied their own delimiters as follows:

      + +<?php echo form_error('field name', '<div class="error">', '</div>'); ?> + +

      Or:

      + +<?php echo validation_errors('<div class="error">', '</div>'); ?> + +
    4. +
    + + + + + +

    Showing Errors Individually

    + +

    If you prefer to show an error message next to each form field, rather than as a list, you can use the form_error() function.

    + +

    Try it! Change your form so that it looks like this:

    + + + +

    If there are no errors, nothing will be shown. If there is an error, the message will appear.

    + +

    Important Note: If you use an array as the name of a form field, you must supply it as an array to the function. Example:

    + +<?php echo form_error('options[size]'); ?>
    +<input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /> +
    + +

    For more info please see the Using Arrays as Field Names section below.

    + + + + +

     

    + + + +

    Saving Sets of Validation Rules to a Config File

    + +

    A nice feature of the Form Validation class is that it permits you to store all your validation rules for your entire application in a config file. You +can organize these rules into "groups". These groups can either be loaded automatically when a matching controller/function is called, or +you can manually call each set as needed.

    + +

    How to save your rules

    + +

    To store your validation rules, simply create a file named form_validation.php in your application/config/ folder. +In that file you will place an array named $config with your rules. As shown earlier, the validation array will have this prototype:

    + + +$config = array(
    +               array(
    +                     'field'   => 'username',
    +                     'label'   => 'Username',
    +                     'rules'   => 'required'
    +                  ),
    +               array(
    +                     'field'   => 'password',
    +                     'label'   => 'Password',
    +                     'rules'   => 'required'
    +                  ),
    +               array(
    +                     'field'   => 'passconf',
    +                     'label'   => 'Password Confirmation',
    +                     'rules'   => 'required'
    +                  ),   
    +               array(
    +                     'field'   => 'email',
    +                     'label'   => 'Email',
    +                     'rules'   => 'required'
    +                  )
    +            );
    +
    + +

    Your validation rule file will be loaded automatically and used when you call the run() function.

    + +

    Please note that you MUST name your array $config.

    + +

    Creating Sets of Rules

    + +

    In order to organize your rules into "sets" requires that you place them into "sub arrays". Consider the following example, showing two sets of rules. +We've arbitrarily called these two rules "signup" and "email". You can name your rules anything you want:

    + + +$config = array(
    +                 'signup' => array(
    +                                    array(
    +                                            'field' => 'username',
    +                                            'label' => 'Username',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'password',
    +                                            'label' => 'Password',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'passconf',
    +                                            'label' => 'PasswordConfirmation',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'email',
    +                                            'label' => 'Email',
    +                                            'rules' => 'required'
    +                                         )
    +                                    ),
    +                 'email' => array(
    +                                    array(
    +                                            'field' => 'emailaddress',
    +                                            'label' => 'EmailAddress',
    +                                            'rules' => 'required|valid_email'
    +                                         ),
    +                                    array(
    +                                            'field' => 'name',
    +                                            'label' => 'Name',
    +                                            'rules' => 'required|alpha'
    +                                         ),
    +                                    array(
    +                                            'field' => 'title',
    +                                            'label' => 'Title',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'message',
    +                                            'label' => 'MessageBody',
    +                                            'rules' => 'required'
    +                                         )
    +                                    )                          
    +               );
    +
    + + +

    Calling a Specific Rule Group

    + +

    In order to call a specific group you will pass its name to the run() function. For example, to call the signup rule you will do this:

    + + +if ($this->form_validation->run('signup') == FALSE)
    +{
    +   $this->load->view('myform');
    +}
    +else
    +{
    +   $this->load->view('formsuccess');
    +}
    +
    + + + +

    Associating a Controller Function with a Rule Group

    + +

    An alternate (and more automatic) method of calling a rule group is to name it according to the controller class/function you intend to use it with. For example, let's say you +have a controller named Member and a function named signup. Here's what your class might look like:

    + + +<?php

    +class Member extends CI_Controller {
    +
    +   function signup()
    +   {      
    +      $this->load->library('form_validation');
    +            
    +      if ($this->form_validation->run() == FALSE)
    +      {
    +         $this->load->view('myform');
    +      }
    +      else
    +      {
    +         $this->load->view('formsuccess');
    +      }
    +   }
    +}
    +?>
    + +

    In your validation config file, you will name your rule group member/signup:

    + + +$config = array(
    +           'member/signup' => array(
    +                                    array(
    +                                            'field' => 'username',
    +                                            'label' => 'Username',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'password',
    +                                            'label' => 'Password',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'passconf',
    +                                            'label' => 'PasswordConfirmation',
    +                                            'rules' => 'required'
    +                                         ),
    +                                    array(
    +                                            'field' => 'email',
    +                                            'label' => 'Email',
    +                                            'rules' => 'required'
    +                                         )
    +                                    )
    +               );
    +
    + +

    When a rule group is named identically to a controller class/function it will be used automatically when the run() function is invoked from that class/function.

    + +

     

    + + + +

    Using Arrays as Field Names

    + +

    The Form Validation class supports the use of arrays as field names. Consider this example:

    + +<input type="text" name="options[]" value="" size="50" /> + +

    If you do use an array as a field name, you must use the EXACT array name in the Helper Functions that require the field name, +and as your Validation Rule field name.

    + +

    For example, to set a rule for the above field you would use:

    + +$this->form_validation->set_rules('options[]', 'Options', 'required'); + +

    Or, to show an error for the above field you would use:

    + +<?php echo form_error('options[]'); ?> + +

    Or to re-populate the field you would use:

    + +<input type="text" name="options[]" value="<?php echo set_value('options[]'); ?>" size="50" /> + +

    You can use multidimensional arrays as field names as well. For example:

    + +<input type="text" name="options[size]" value="" size="50" /> + +

    Or even:

    + +<input type="text" name="sports[nba][basketball]" value="" size="50" /> + +

    As with our first example, you must use the exact array name in the helper functions:

    + +<?php echo form_error('sports[nba][basketball]'); ?> + +

    If you are using checkboxes (or other fields) that have multiple options, don't forget to leave an empty bracket after each option, so that all selections will be added to the +POST array:

    + + +<input type="checkbox" name="options[]" value="red" />
    +<input type="checkbox" name="options[]" value="blue" />
    +<input type="checkbox" name="options[]" value="green" /> +
    + +

    Or if you use a multidimensional array:

    + + +<input type="checkbox" name="options[color][]" value="red" />
    +<input type="checkbox" name="options[color][]" value="blue" />
    +<input type="checkbox" name="options[color][]" value="green" /> +
    + +

    When you use a helper function you'll include the bracket as well:

    + +<?php echo form_error('options[color][]'); ?> + + + + +

     

    + + + +

    Rule Reference

    + +

    The following is a list of all the native rules that are available to use:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    RuleParameterDescriptionExample
    requiredNoReturns FALSE if the form element is empty. 
    matchesYesReturns FALSE if the form element does not match the one in the parameter.matches[form_item]
    is_uniqueYesReturns FALSE if the form element is not unique to the table and field name in the parameter.is_unique[table.field]
    min_lengthYesReturns FALSE if the form element is shorter then the parameter value.min_length[6]
    max_lengthYesReturns FALSE if the form element is longer then the parameter value.max_length[12]
    exact_lengthYesReturns FALSE if the form element is not exactly the parameter value.exact_length[8]
    greater_thanYesReturns FALSE if the form element is less than the parameter value or not numeric.greater_than[8]
    less_thanYesReturns FALSE if the form element is greater than the parameter value or not numeric.less_than[8]
    alphaNoReturns FALSE if the form element contains anything other than alphabetical characters. 
    alpha_numericNoReturns FALSE if the form element contains anything other than alpha-numeric characters. 
    alpha_dashNoReturns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes. 
    numericNoReturns FALSE if the form element contains anything other than numeric characters. 
    integerNoReturns FALSE if the form element contains anything other than an integer. 
    decimalYesReturns FALSE if the form element is not exactly the parameter value. 
    is_naturalNoReturns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc. 
    is_natural_no_zeroNoReturns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc. 
    valid_emailNoReturns FALSE if the form element does not contain a valid email address. 
    valid_emailsNoReturns FALSE if any value provided in a comma separated list is not a valid email. 
    valid_ipNoReturns FALSE if the supplied IP is not valid. Accepts an optional parameter of "IPv4" or "IPv6" to specify an IP format. 
    valid_base64NoReturns FALSE if the supplied string contains anything other than valid Base64 characters. 
    + +

    Note: These rules can also be called as discrete functions. For example:

    + +$this->form_validation->required($string); + +

    Note: You can also use any native PHP functions that permit one parameter.

    + + + +

     

    + + +

    Prepping Reference

    + +

    The following is a list of all the prepping functions that are available to use:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameParameterDescription
    xss_cleanNoRuns the data through the XSS filtering function, described in the Input Class page.
    prep_for_formNoConverts special characters so that HTML data can be shown in a form field without breaking it.
    prep_urlNoAdds "http://" to URLs if missing.
    strip_image_tagsNoStrips the HTML from image tags leaving the raw URL.
    encode_php_tagsNoConverts PHP tags to entities.
    + +

    Note: You can also use any native PHP functions that permit one parameter, +like trim, htmlspecialchars, urldecode, etc.

    + + + + + + + +

     

    + + +

    Function Reference

    + +

    The following functions are intended for use in your controller functions.

    + +

    $this->form_validation->set_rules();

    + +

    Permits you to set validation rules, as described in the tutorial sections above:

    + + + + +

    $this->form_validation->run();

    + +

    Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation +group via the function, as described in: Saving Groups of Validation Rules to a Config File.

    + + +

    $this->form_validation->set_message();

    + +

    Permits you to set custom error messages. See Setting Error Messages above.

    + + +

     

    + + +

    Helper Reference

    + +

    The following helper functions are available for use in the view files containing your forms. Note that these are procedural functions, so they +do not require you to prepend them with $this->form_validation.

    + +

    form_error()

    + +

    Shows an individual error message associated with the field name supplied to the function. Example:

    + +<?php echo form_error('username'); ?> + +

    The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.

    + + + +

    validation_errors()

    +

    Shows all error messages as a string: Example:

    + +<?php echo validation_errors(); ?> + +

    The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.

    + + + +

    set_value()

    + +

    Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. +The second (optional) parameter allows you to set a default value for the form. Example:

    + +<input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" /> + +

    The above form will show "0" when loaded for the first time.

    + +

    set_select()

    + +

    If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter +must contain the name of the select menu, the second parameter must contain the value of +each item, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).

    + +

    Example:

    + + +<select name="myselect">
    +<option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
    +<option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
    +<option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
    +</select> +
    + + +

    set_checkbox()

    + +

    Permits you to display a checkbox in the state it was submitted. The first parameter +must contain the name of the checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE). Example:

    + +<input type="checkbox" name="mycheck[]" value="1" <?php echo set_checkbox('mycheck[]', '1'); ?> />
    +<input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> />
    + + +

    set_radio()

    + +

    Permits you to display radio buttons in the state they were submitted. This function is identical to the set_checkbox() function above.

    + +<input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> />
    +<input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />
    + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/ftp.html b/api/user_guide/libraries/ftp.html new file mode 100644 index 0000000..67c0ce7 --- /dev/null +++ b/api/user_guide/libraries/ftp.html @@ -0,0 +1,315 @@ + + + + + +FTP Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    FTP Class

    + +

    CodeIgniter's FTP Class permits files to be transfered to a remote server. Remote files can also be moved, renamed, +and deleted. The FTP class also includes a "mirroring" function that permits an entire local directory to be recreated remotely via FTP.

    + +

    Note:  SFTP and SSL FTP protocols are not supported, only standard FTP.

    + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the FTP class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('ftp'); +

    Once loaded, the FTP object will be available using: $this->ftp

    + + +

    Usage Examples

    + +

    In this example a connection is opened to the FTP server, and a local file is read and uploaded in ASCII mode. The +file permissions are set to 755.

    + + +$this->load->library('ftp');
    +
    +$config['hostname'] = 'ftp.example.com';
    +$config['username'] = 'your-username';
    +$config['password'] = 'your-password';
    +$config['debug'] = TRUE;
    +
    +$this->ftp->connect($config);
    +
    +$this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775);
    +
    +$this->ftp->close(); + +
    + + +

    In this example a list of files is retrieved from the server.

    + + +$this->load->library('ftp');
    +
    +$config['hostname'] = 'ftp.example.com';
    +$config['username'] = 'your-username';
    +$config['password'] = 'your-password';
    +$config['debug'] = TRUE;
    +
    +$this->ftp->connect($config);
    +
    +$list = $this->ftp->list_files('/public_html/');
    +
    +print_r($list);
    +
    +$this->ftp->close(); +
    + +

    In this example a local directory is mirrored on the server.

    + + + +$this->load->library('ftp');
    +
    +$config['hostname'] = 'ftp.example.com';
    +$config['username'] = 'your-username';
    +$config['password'] = 'your-password';
    +$config['debug'] = TRUE;
    +
    +$this->ftp->connect($config);
    +
    +$this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/');
    +
    +$this->ftp->close(); +
    + + +

    Function Reference

    + +

    $this->ftp->connect()

    + +

    Connects and logs into to the FTP server. Connection preferences are set by passing an array +to the function, or you can store them in a config file.

    + + +

    Here is an example showing how you set preferences manually:

    + + +$this->load->library('ftp');
    +
    +$config['hostname'] = 'ftp.example.com';
    +$config['username'] = 'your-username';
    +$config['password'] = 'your-password';
    +$config['port']     = 21;
    +$config['passive']  = FALSE;
    +$config['debug']    = TRUE;
    +
    +$this->ftp->connect($config);
    +
    + +

    Setting FTP Preferences in a Config File

    + +

    If you prefer you can store your FTP preferences in a config file. +Simply create a new file called the ftp.php, add the $config +array in that file. Then save the file at config/ftp.php and it will be used automatically.

    + +

    Available connection options:

    + + +
      +
    • hostname - the FTP hostname. Usually something like:  ftp.example.com
    • +
    • username - the FTP username.
    • +
    • password - the FTP password.
    • +
    • port - The port number. Set to 21 by default.
    • +
    • debug - TRUE/FALSE (boolean). Whether to enable debugging to display error messages.
    • +
    • passive - TRUE/FALSE (boolean). Whether to use passive mode. Passive is set automatically by default.
    • +
    + + + +

    $this->ftp->upload()

    + +

    Uploads a file to your server. You must supply the local path and the remote path, and you can optionally set the mode and permissions. +Example:

    + + +$this->ftp->upload('/local/path/to/myfile.html', '/public_html/myfile.html', 'ascii', 0775); + +

    Mode options are:  ascii, binary, and auto (the default). If +auto is used it will base the mode on the file extension of the source file.

    + +

    Permissions can be passed as an octal value in the fourth parameter.

    + +

    $this->ftp->download()

    + +

    Downloads a file from your server. You must supply the remote path and the local path, and you can optionally set the mode. +Example:

    + +$this->ftp->download('/public_html/myfile.html', '/local/path/to/myfile.html', 'ascii'); + +

    Mode options are:  ascii, binary, and auto (the default). If +auto is used it will base the mode on the file extension of the source file.

    + +

    Returns FALSE if the download does not execute successfully (including if PHP does not have permission to write the local file)

    + + +

    $this->ftp->rename()

    +

    Permits you to rename a file. Supply the source file name/path and the new file name/path.

    + + +// Renames green.html to blue.html
    +$this->ftp->rename('/public_html/foo/green.html', '/public_html/foo/blue.html'); +
    + +

    $this->ftp->move()

    +

    Lets you move a file. Supply the source and destination paths:

    + + +// Moves blog.html from "joe" to "fred"
    +$this->ftp->move('/public_html/joe/blog.html', '/public_html/fred/blog.html'); +
    + +

    Note: if the destination file name is different the file will be renamed.

    + + +

    $this->ftp->delete_file()

    +

    Lets you delete a file. Supply the source path with the file name.

    + + +$this->ftp->delete_file('/public_html/joe/blog.html'); + + + +

    $this->ftp->delete_dir()

    +

    Lets you delete a directory and everything it contains. Supply the source path to the directory with a trailing slash.

    + +

    Important  Be VERY careful with this function. It will recursively delete +everything within the supplied path, including sub-folders and all files. Make absolutely sure your path is correct. +Try using the list_files() function first to verify that your path is correct.

    + + +$this->ftp->delete_dir('/public_html/path/to/folder/'); + + + + +

    $this->ftp->list_files()

    +

    Permits you to retrieve a list of files on your server returned as an array. You must supply +the path to the desired directory.

    + + +$list = $this->ftp->list_files('/public_html/');
    +
    +print_r($list); +
    + + +

    $this->ftp->mirror()

    + +

    Recursively reads a local folder and everything it contains (including sub-folders) and creates a +mirror via FTP based on it. Whatever the directory structure of the original file path will be recreated on the server. +You must supply a source path and a destination path:

    + + +$this->ftp->mirror('/path/to/myfolder/', '/public_html/myfolder/'); + + + + +

    $this->ftp->mkdir()

    + +

    Lets you create a directory on your server. Supply the path ending in the folder name you wish to create, with a trailing slash. +Permissions can be set by passed an octal value in the second parameter.

    + + +// Creates a folder named "bar"
    +$this->ftp->mkdir('/public_html/foo/bar/', DIR_WRITE_MODE); +
    + + +

    $this->ftp->chmod()

    + +

    Permits you to set file permissions. Supply the path to the file or folder you wish to alter permissions on:

    + + +// Chmod "bar" to 777
    +$this->ftp->chmod('/public_html/foo/bar/', DIR_WRITE_MODE); +
    + + + + +

    $this->ftp->close();

    +

    Closes the connection to your server. It's recommended that you use this when you are finished uploading.

    + + + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/image_lib.html b/api/user_guide/libraries/image_lib.html new file mode 100644 index 0000000..4f01bde --- /dev/null +++ b/api/user_guide/libraries/image_lib.html @@ -0,0 +1,667 @@ + + + + + +Image Manipulation Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Image Manipulation Class

    + +

    CodeIgniter's Image Manipulation class lets you perform the following actions:

    + +
      +
    • Image Resizing
    • +
    • Thumbnail Creation
    • +
    • Image Cropping
    • +
    • Image Rotating
    • +
    • Image Watermarking
    • +
    + +

    All three major image libraries are supported: GD/GD2, NetPBM, and ImageMagick

    + +

    Note: Watermarking is only available using the GD/GD2 library. +In addition, even though other libraries are supported, GD is required in +order for the script to calculate the image properties. The image processing, however, will be performed with the +library you specify.

    + + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the image class is initialized in your controller +using the $this->load->library function:

    +$this->load->library('image_lib'); + +

    Once the library is loaded it will be ready for use. The image library object you will use to call all functions is: $this->image_lib

    + + +

    Processing an Image

    + +

    Regardless of the type of processing you would like to perform (resizing, cropping, rotation, or watermarking), the general process is +identical. You will set some preferences corresponding to the action you intend to perform, then +call one of four available processing functions. For example, to create an image thumbnail you'll do this:

    + +$config['image_library'] = 'gd2';
    +$config['source_image'] = '/path/to/image/mypic.jpg';
    +$config['create_thumb'] = TRUE;
    +$config['maintain_ratio'] = TRUE;
    +$config['width'] = 75;
    +$config['height'] = 50;
    +
    +$this->load->library('image_lib', $config); +
    +
    +$this->image_lib->resize();
    + +

    The above code tells the image_resize function to look for an image called mypic.jpg +located in the source_image folder, then create a thumbnail that is 75 X 50 pixels using the GD2 image_library. +Since the maintain_ratio option is enabled, the thumb will be as close to the target width and +height as possible while preserving the original aspect ratio. The thumbnail will be called mypic_thumb.jpg +

    + +

    Note: In order for the image class to be allowed to do any processing, the +folder containing the image files must have write permissions.

    + +

    Note: Image processing can require a considerable amount of server memory for some operations. If you are experiencing out of memory errors while processing images you may need to limit their maximum size, and/or adjust PHP memory limits.

    + +

    Processing Functions

    + +

    There are four available processing functions:

    + +
      +
    • $this->image_lib->resize()
    • +
    • $this->image_lib->crop()
    • +
    • $this->image_lib->rotate()
    • +
    • $this->image_lib->watermark()
    • +
    • $this->image_lib->clear()
    • +
    + +

    These functions return boolean TRUE upon success and FALSE for failure. If they fail you can retrieve the +error message using this function:

    + +echo $this->image_lib->display_errors(); + +

    A good practice is use the processing function conditionally, showing an error upon failure, like this:

    + +if ( ! $this->image_lib->resize())
    +{
    +    echo $this->image_lib->display_errors();
    +}
    + +

    Note: You can optionally specify the HTML formatting to be applied to the errors, by submitting the opening/closing +tags in the function, like this:

    + +$this->image_lib->display_errors('<p>', '</p>'); + + +

    Preferences

    + +

    The preferences described below allow you to tailor the image processing to suit your needs.

    + +

    Note that not all preferences are available for every +function. For example, the x/y axis preferences are only available for image cropping. Likewise, the width and height +preferences have no effect on cropping. The "availability" column indicates which functions support a given preference.

    + +

    Availability Legend:

    + +
      +
    • R - Image Resizing
    • +
    • C - Image Cropping
    • +
    • X - Image Rotation
    • +
    • W - Image Watermarking
    • + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescriptionAvailability
    image_libraryGD2GD, GD2, ImageMagick, NetPBMSets the image library to be used.R, C, X, W
    library_pathNoneNoneSets the server path to your ImageMagick or NetPBM library. If you use either of those libraries you must supply the path.R, C, X
    source_imageNoneNoneSets the source image name/path. The path must be a relative or absolute server path, not a URL.R, C, S, W
    dynamic_outputFALSETRUE/FALSE (boolean)Determines whether the new image file should be written to disk or generated dynamically. Note: If you choose the dynamic setting, only one image can be shown at a time, and it can't be positioned on the page. It simply outputs the raw image dynamically to your browser, along with image headers.R, C, X, W
    quality90%1 - 100%Sets the quality of the image. The higher the quality the larger the file size.R, C, X, W
    new_imageNoneNoneSets the destination image name/path. You'll use this preference when creating an image copy. The path must be a relative or absolute server path, not a URL.R, C, X, W
    widthNoneNoneSets the width you would like the image set to.R, C
    heightNoneNoneSets the height you would like the image set to.R, C
    create_thumbFALSETRUE/FALSE (boolean)Tells the image processing function to create a thumb.R
    thumb_marker_thumbNoneSpecifies the thumbnail indicator. It will be inserted just before the file extension, so mypic.jpg would become mypic_thumb.jpgR
    maintain_ratioTRUETRUE/FALSE (boolean)Specifies whether to maintain the original aspect ratio when resizing or use hard values.R, C
    master_dimautoauto, width, heightSpecifies what to use as the master axis when resizing or creating thumbs. For example, let's say you want to resize an image to 100 X 75 pixels. If the source image size does not allow perfect resizing to those dimensions, this setting determines which axis should be used as the hard value. "auto" sets the axis automatically based on whether the image is taller then wider, or vice versa.R
    rotation_angleNone90, 180, 270, vrt, horSpecifies the angle of rotation when rotating images. Note that PHP rotates counter-clockwise, so a 90 degree rotation to the right must be specified as 270.X
    x_axisNoneNoneSets the X coordinate in pixels for image cropping. For example, a setting of 30 will crop an image 30 pixels from the left.C
    y_axisNoneNoneSets the Y coordinate in pixels for image cropping. For example, a setting of 30 will crop an image 30 pixels from the top.C
    + + +

    Setting preferences in a config file

    + +

    If you prefer not to set preferences using the above method, you can instead put them into a config file. +Simply create a new file called image_lib.php, add the $config +array in that file. Then save the file in: config/image_lib.php and it will be used automatically. You +will NOT need to use the $this->image_lib->initialize function if you save your preferences in a config file.

    + + +

    $this->image_lib->resize()

    + +

    The image resizing function lets you resize the original image, create a copy (with or without resizing), +or create a thumbnail image.

    + +

    For practical purposes there is no difference between creating a copy and creating +a thumbnail except a thumb will have the thumbnail marker as part of the name (ie, mypic_thumb.jpg).

    + +

    All preferences listed in the table above are available for this function except these three: rotation_angle, x_axis, and y_axis.

    + +

    Creating a Thumbnail

    + +

    The resizing function will create a thumbnail file (and preserve the original) if you set this preference to TRUE:

    + +$config['create_thumb'] = TRUE; + +

    This single preference determines whether a thumbnail is created or not.

    + +

    Creating a Copy

    + +

    The resizing function will create a copy of the image file (and preserve the original) if you set +a path and/or a new filename using this preference:

    + +$config['new_image'] = '/path/to/new_image.jpg'; + +

    Notes regarding this preference:

    +
      +
    • If only the new image name is specified it will be placed in the same folder as the original
    • +
    • If only the path is specified, the new image will be placed in the destination with the same name as the original.
    • +
    • If both the path and image name are specified it will placed in its own destination and given the new name.
    • +
    + + +

    Resizing the Original Image

    + +

    If neither of the two preferences listed above (create_thumb, and new_image) are used, the resizing function will instead +target the original image for processing.

    + + +

    $this->image_lib->crop()

    + +

    The cropping function works nearly identically to the resizing function except it requires that you set +preferences for the X and Y axis (in pixels) specifying where to crop, like this:

    + +$config['x_axis'] = '100';
    +$config['y_axis'] = '40';
    + +

    All preferences listed in the table above are available for this function except these: rotation_angle, width, height, create_thumb, new_image.

    + +

    Here's an example showing how you might crop an image:

    + +$config['image_library'] = 'imagemagick';
    +$config['library_path'] = '/usr/X11R6/bin/';
    +$config['source_image'] = '/path/to/image/mypic.jpg';
    +$config['x_axis'] = '100';
    +$config['y_axis'] = '60';
    +
    +$this->image_lib->initialize($config); +
    +
    +if ( ! $this->image_lib->crop())
    +{
    +    echo $this->image_lib->display_errors();
    +}
    + + +

    Note: Without a visual interface it is difficult to crop images, so this function is not very useful +unless you intend to build such an interface. That's exactly what we did using for the photo +gallery module in ExpressionEngine, the CMS we develop. We added a JavaScript UI that lets the cropping +area be selected.

    + +

    $this->image_lib->rotate()

    + +

    The image rotation function requires that the angle of rotation be set via its preference:

    + +$config['rotation_angle'] = '90'; + +

    There are 5 rotation options:

    + +
      +
    1. 90 - rotates counter-clockwise by 90 degrees.
    2. +
    3. 180 - rotates counter-clockwise by 180 degrees.
    4. +
    5. 270 - rotates counter-clockwise by 270 degrees.
    6. +
    7. hor - flips the image horizontally.
    8. +
    9. vrt - flips the image vertically.
    10. +
    + +

    Here's an example showing how you might rotate an image:

    + +$config['image_library'] = 'netpbm';
    +$config['library_path'] = '/usr/bin/';
    +$config['source_image'] = '/path/to/image/mypic.jpg';
    +$config['rotation_angle'] = 'hor';
    +
    +$this->image_lib->initialize($config); +
    +
    +if ( ! $this->image_lib->rotate())
    +{
    +    echo $this->image_lib->display_errors();
    +}
    + + + +

    $this->image_lib->clear()

    +

    The clear function resets all of the values used when processing an image. You will want to call this if you are processing images in a loop.

    +

    $this->image_lib->clear();

    +

     

    +

    Image Watermarking

    + +

    The Watermarking feature requires the GD/GD2 library.

    + + +

    Two Types of Watermarking

    + +

    There are two types of watermarking that you can use:

    + +
      +
    • Text: The watermark message will be generating using text, either with a True Type font that you specify, or +using the native text output that the GD library supports. If you use the True Type version your GD installation +must be compiled with True Type support (most are, but not all).
    • + +
    • Overlay: The watermark message will be generated by overlaying an image (usually a transparent PNG or GIF) +containing your watermark over the source image.
    • + +
    + + +

    Watermarking an Image

    + +

    Just as with the other functions (resizing, cropping, and rotating) the general process for watermarking +involves setting the preferences corresponding to the action you intend to perform, then +calling the watermark function. Here is an example:

    + + +$config['source_image'] = '/path/to/image/mypic.jpg';
    +$config['wm_text'] = 'Copyright 2006 - John Doe';
    +$config['wm_type'] = 'text';
    +$config['wm_font_path'] = './system/fonts/texb.ttf';
    +$config['wm_font_size'] = '16';
    +$config['wm_font_color'] = 'ffffff';
    +$config['wm_vrt_alignment'] = 'bottom';
    +$config['wm_hor_alignment'] = 'center';
    +$config['wm_padding'] = '20';
    +
    +$this->image_lib->initialize($config); +
    +
    +$this->image_lib->watermark();
    + + +

    The above example will use a 16 pixel True Type font to create the text "Copyright 2006 - John Doe". The watermark +will be positioned at the bottom/center of the image, 20 pixels from the bottom of the image.

    + +

    Note: In order for the image class to be allowed to do any processing, the image file must have "write" file permissions. For example, 777.

    + + +

    Watermarking Preferences

    + +

    This table shown the preferences that are available for both types of watermarking (text or overlay)

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    wm_typetexttext, overlaySets the type of watermarking that should be used.
    source_imageNoneNoneSets the source image name/path. The path must be a relative or absolute server path, not a URL.
    dynamic_outputFALSETRUE/FALSE (boolean)Determines whether the new image file should be written to disk or generated dynamically. Note: If you choose the dynamic setting, only one image can be shown at a time, and it can't be positioned on the page. It simply outputs the raw image dynamically to your browser, along with image headers.
    quality90%1 - 100%Sets the quality of the image. The higher the quality the larger the file size.
    paddingNoneA numberThe amount of padding, set in pixels, that will be applied to the watermark to set it away from the edge of your images.
    wm_vrt_alignmentbottomtop, middle, bottomSets the vertical alignment for the watermark image.
    wm_hor_alignmentcenterleft, center, rightSets the horizontal alignment for the watermark image.
    wm_hor_offsetNoneNoneYou may specify a horizontal offset (in pixels) to apply to the watermark position. The offset normally moves the watermark to the right, except if you have your alignment set to "right" then your offset value will move the watermark toward the left of the image.
    wm_vrt_offsetNoneNoneYou may specify a vertical offset (in pixels) to apply to the watermark position. The offset normally moves the watermark down, except if you have your alignment set to "bottom" then your offset value will move the watermark toward the top of the image.
    + + + +

    Text Preferences

    +

    This table shown the preferences that are available for the text type of watermarking.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    wm_textNoneNoneThe text you would like shown as the watermark. Typically this will be a copyright notice.
    wm_font_pathNoneNoneThe server path to the True Type Font you would like to use. If you do not use this option, the native GD font will be used.
    wm_font_size16NoneThe size of the text. Note: If you are not using the True Type option above, the number is set using a range of 1 - 5. Otherwise, you can use any valid pixel size for the font you're using.
    wm_font_colorffffffNoneThe font color, specified in hex. Note, you must use the full 6 character hex value (ie, 993300), rather than the three character abbreviated version (ie fff).
    wm_shadow_colorNoneNoneThe color of the drop shadow, specified in hex. If you leave this blank a drop shadow will not be used. Note, you must use the full 6 character hex value (ie, 993300), rather than the three character abbreviated version (ie fff).
    wm_shadow_distance3NoneThe distance (in pixels) from the font that the drop shadow should appear.
    + + + + +

    Overlay Preferences

    +

    This table shown the preferences that are available for the overlay type of watermarking.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    wm_overlay_pathNoneNoneThe server path to the image you wish to use as your watermark. Required only if you are using the overlay method.
    wm_opacity501 - 100Image opacity. You may specify the opacity (i.e. transparency) of your watermark image. This allows the watermark to be faint and not completely obscure the details from the original image behind it. A 50% opacity is typical.
    wm_x_transp4A numberIf your watermark image is a PNG or GIF image, you may specify a color on the image to be "transparent". This setting (along with the next) will allow you to specify that color. This works by specifying the "X" and "Y" coordinate pixel (measured from the upper left) within the image that corresponds to a pixel representative of the color you want to be transparent.
    wm_y_transp4A numberAlong with the previous setting, this allows you to specify the coordinate to a pixel representative of the color you want to be transparent.
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/input.html b/api/user_guide/libraries/input.html new file mode 100644 index 0000000..f5049e1 --- /dev/null +++ b/api/user_guide/libraries/input.html @@ -0,0 +1,295 @@ + + + + + +Input Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Input Class

    + +

    The Input Class serves two purposes:

    + +
      +
    1. It pre-processes global input data for security.
    2. +
    3. It provides some helper functions for fetching input data and pre-processing it.
    4. +
    + +

    Note: This class is initialized automatically by the system so there is no need to do it manually.

    + + +

    Security Filtering

    + +

    The security filtering function is called automatically when a new controller is invoked. It does the following:

    + +
      +
    • If $config['allow_get_array'] is FALSE(default is TRUE), destroys the global GET array.
    • +
    • Destroys all global variables in the event register_globals is turned on.
    • +
    • Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric (and a few other) characters.
    • +
    • Provides XSS (Cross-site Scripting Hacks) filtering. This can be enabled globally, or upon request.
    • +
    • Standardizes newline characters to \n(In Windows \r\n)
    • +
    + + +

    XSS Filtering

    + +

    The Input class has the ability to filter input automatically to prevent cross-site scripting attacks. If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your +application/config/config.php file and setting this:

    + +$config['global_xss_filtering'] = TRUE; + +

    Please refer to the Security class documentation for information on using XSS Filtering in your application.

    + + +

    Using POST, COOKIE, or SERVER Data

    + +

    CodeIgniter comes with three helper functions that let you fetch POST, COOKIE or SERVER items. The main advantage of using the provided +functions rather than fetching an item directly ($_POST['something']) is that the functions will check to see if the item is set and +return false (boolean) if not. This lets you conveniently use data without having to test whether an item exists first. +In other words, normally you might do something like this:

    + + +if ( ! isset($_POST['something']))
    +{
    +    $something = FALSE;
    +}
    +else
    +{
    +    $something = $_POST['something'];
    +}
    + +

    With CodeIgniter's built in functions you can simply do this:

    + +$something = $this->input->post('something'); + +

    The three functions are:

    + +
      +
    • $this->input->post()
    • +
    • $this->input->cookie()
    • +
    • $this->input->server()
    • +
    + +

    $this->input->post()

    + +

    The first parameter will contain the name of the POST item you are looking for:

    + +$this->input->post('some_data'); + +

    The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist.

    + +

    The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE;

    + +$this->input->post('some_data', TRUE); + +

    To return an array of all POST items call without any parameters.

    +

    To return all POST items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean;

    +

    The function returns FALSE (boolean) if there are no items in the POST.

    + + + $this->input->post(NULL, TRUE); // returns all POST items with XSS filter +
    + $this->input->post(); // returns all POST items without XSS filter +
    + +

    $this->input->get()

    + +

    This function is identical to the post function, only it fetches get data:

    + +$this->input->get('some_data', TRUE); + +

    To return an array of all GET items call without any parameters.

    +

    To return all GET items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean;

    +

    The function returns FALSE (boolean) if there are no items in the GET.

    + + + $this->input->get(NULL, TRUE); // returns all GET items with XSS filter +
    + $this->input->get(); // returns all GET items without XSS filtering +
    + +

    $this->input->get_post()

    + +

    This function will search through both the post and get streams for data, looking first in post, and then in get:

    + +$this->input->get_post('some_data', TRUE); + +

    $this->input->cookie()

    + +

    This function is identical to the post function, only it fetches cookie data:

    + +$this->input->cookie('some_data', TRUE); + +

    $this->input->server()

    + +

    This function is identical to the above functions, only it fetches server data:

    + +$this->input->server('some_data'); + + +

    $this->input->set_cookie()

    + +

    Sets a cookie containing the values you specify. There are two ways to pass information to this function so that a cookie can be set: +Array Method, and Discrete Parameters:

    + +

    Array Method

    + +

    Using this method, an associative array is passed to the first parameter:

    + +$cookie = array(
    +    'name'   => 'The Cookie Name',
    +    'value'  => 'The Value',
    +    'expire' => '86500',
    +    'domain' => '.some-domain.com',
    +    'path'   => '/',
    +    'prefix' => 'myprefix_',
    +    'secure' => TRUE
    +);
    +
    +$this->input->set_cookie($cookie); +
    + +

    Notes:

    + +

    Only the name and value are required. To delete a cookie set it with the expiration blank.

    + +

    The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the +number of seconds from now that you wish the cookie to be valid. If the expiration is set to +zero the cookie will only last as long as the browser is open.

    +

    For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period, like this: .your-domain.com

    +

    The path is usually not needed since the function sets a root path.

    +

    The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server.

    +

    The secure boolean is only needed if you want to make it a secure cookie by setting it to TRUE.

    + +

    Discrete Parameters

    + +

    If you prefer, you can set the cookie by passing data using individual parameters:

    + +$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); + +

    $this->input->cookie()

    + +

    Lets you fetch a cookie. The first parameter will contain the name of the cookie you are looking for (including any prefixes):

    + +cookie('some_cookie'); + +

    The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist.

    + +

    The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE;

    + +

    cookie('some_cookie', TRUE);

    + + +

    $this->input->ip_address()

    +

    Returns the IP address for the current user. If the IP address is not valid, the function will return an IP of: 0.0.0.0

    +echo $this->input->ip_address(); + + +

    $this->input->valid_ip($ip)

    + +

    Takes an IP address as input and returns TRUE or FALSE (boolean) if it is valid or not. Note: The $this->input->ip_address() function above +validates the IP automatically.

    + +if ( ! $this->input->valid_ip($ip))
    +{
    +     echo 'Not Valid';
    +}
    +else
    +{
    +     echo 'Valid';
    +}
    +

    Accepts an optional second string parameter of "IPv4" or "IPv6" to specify an IP format. The default checks for both formats.

    + +

    $this->input->user_agent()

    +

    Returns the user agent (web browser) being used by the current user. Returns FALSE if it's not available.

    +echo $this->input->user_agent(); +

    See the User Agent Class for methods which extract information from the user agent string.

    + +

    $this->input->request_headers()

    +

    Useful if running in a non-Apache environment where apache_request_headers() will not be supported. Returns an array of headers.

    + +$headers = $this->input->request_headers(); + +

    $this->input->get_request_header();

    +

    Returns a single member of the request headers array.

    + +$this->input->get_request_header('some-header', TRUE); + + +

    $this->input->is_ajax_request()

    +

    Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns a boolean response.

    + + +

    $this->input->is_cli_request()

    +

    Checks to see if the STDIN constant is set, which is a failsafe way to see if PHP is being run on the command line.

    + +$this->input->is_cli_request() + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/javascript.html b/api/user_guide/libraries/javascript.html new file mode 100644 index 0000000..f9d73f2 --- /dev/null +++ b/api/user_guide/libraries/javascript.html @@ -0,0 +1,247 @@ + + + + +JavaScript Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Note: This driver is experimental. Its feature set and implementation may change in future releases.


    + +

    Javascript Class

    +

    CodeIgniter provides a library to help you with certain common functions that you may want to use with Javascript. Please note that CodeIgniter does not require the jQuery library to run, and that any scripting library will work equally well. The jQuery library is simply presented as a convenience if you choose to use it.

    +

    Initializing the Class

    +

    To initialize the Javascript class manually in your controller constructor, use the $this->load->library function. Currently, the only available library is jQuery, which will automatically be loaded like this:

    + +$this->load->library('javascript'); + +

    The Javascript class also accepts parameters, js_library_driver (string) default 'jquery' and autoload (bool) default TRUE. You may override the defaults if you wish by sending an associative array:

    + +$this->load->library('javascript', array('js_library_driver' => 'scripto', 'autoload' => FALSE)); + +

    Again, presently only 'jquery' is available. You may wish to set autoload to FALSE, though, if you do not want the jQuery library to automatically include a script tag for the main jQuery script file. This is useful if you are loading it from a location outside of CodeIgniter, or already have the script tag in your markup.

    + +

    Once loaded, the jQuery library object will be available using: $this->javascript

    +

    Setup and Configuration

    +

    Set these variables in your view

    +

    As a Javascript library, your files must be available to your application.

    +

    As Javascript is a client side language, the library must be able to write content into your final output. This generally means a view. You'll need to include the following variables in the <head> sections of your output.

    +

    <?php echo $library_src;?>
    +<?php echo $script_head;?> +

    +

    $library_src, is where the actual library file will be loaded, as well as any subsequent plugin script calls; $script_head is where specific events, functions and other commands will be rendered.

    +

    Set the path to the librarys with config items

    +

    There are some configuration items in Javascript library. These can either be set in application/config.php, within its own config/javascript.php file, or within any controller usings the set_item() function.

    +

    An image to be used as an "ajax loader", or progress indicator. Without one, the simple text message of "loading" will appear when Ajax calls need to be made.

    +

    $config['javascript_location'] = 'http://localhost/codeigniter/themes/js/jquery/';
    + $config['javascript_ajax_img'] = 'images/ajax-loader.gif';

    +

    If you keep your files in the same directories they were downloaded from, then you need not set this configuration items.

    + +

    The jQuery Class

    + +

    To initialize the jQuery class manually in your controller constructor, use the $this->load->library function:

    + +$this->load->library('jquery'); + +

    You may send an optional parameter to determine whether or not a script tag for the main jQuery file will be automatically included when loading the library. It will be created by default. To prevent this, load the library as follows:

    + +$this->load->library('jquery', FALSE); + +

    Once loaded, the jQuery library object will be available using: $this->jquery

    + +

    jQuery Events

    + +

    Events are set using the following syntax.

    + +

    $this->jquery->event('element_path', code_to_run());

    + +

    In the above example:

    + +
      +
    • "event" is any of blur, change, click, dblclick, error, focus, hover, keydown, keyup, load, mousedown, mouseup, mouseover, mouseup, resize, scroll, or unload.
    • +
    • "element_path" is any valid jQuery selector. Due to jQuery's unique selector syntax, this is usually an element id, or CSS selector. For example "#notice_area" would effect <div id="notice_area">, and "#content a.notice" would effect all anchors with a class of "notice" in the div with id "content".
    • +
    • "code_to_run()" is script your write yourself, or an action such as an effect from the jQuery library below.
    • +
    + +

    Effects

    + +

    The query library supports a powerful Effects repertoire. Before an effect can be used, it must be loaded:

    + +

    $this->jquery->effect([optional path] plugin name); +// for example +$this->jquery->effect('bounce'); +

    + +

    hide() / show()

    + +

    Each of this functions will affect the visibility of an item on your page. hide() will set an item invisible, show() will reveal it.

    +

    $this->jquery->hide(target, optional speed, optional extra information);
    + $this->jquery->show(target, optional speed, optional extra information);

    + +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "speed" is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
    • +
    • "extra information" is optional, and could include a callback, or other additional information.
    • +
    + +

    toggle()

    + +

    toggle() will change the visibility of an item to the opposite of its current state, hiding visible elements, and revealing hidden ones.

    +

    $this->jquery->toggle(target);

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    + +

    animate()

    + +

    $this->jquery->animate(target, parameters, optional speed, optional extra information);

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "parameters" in jQuery would generally include a series of CSS properties that you wish to change.
    • +
    • "speed" is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
    • +
    • "extra information" is optional, and could include a callback, or other additional information.
    • +
    +

    For a full summary, see http://docs.jquery.com/Effects/animate

    +

    Here is an example of an animate() called on a div with an id of "note", and triggered by a click using the jQuery library's click() event.

    +

    $params = array(
    + 'height' => 80,
    + 'width' => '50%',
    + 'marginLeft' => 125
    +);
    +$this->jquery->click('#trigger', $this->jquery->animate('#note', $params, normal));

    + +

    fadeIn() / fadeOut()

    + +

    $this->jquery->fadeIn(target, optional speed, optional extra information);
    + $this->jquery->fadeOut(target, optional speed, optional extra information);

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "speed" is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
    • +
    • "extra information" is optional, and could include a callback, or other additional information.
    • +
    + +

    toggleClass()

    + +

    This function will add or remove a CSS class to its target.

    +

    $this->jquery->toggleClass(target, class)

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "class" is any CSS classname. Note that this class must be defined and available in a CSS that is already loaded.
    • +
    + +

    fadeIn() / fadeOut()

    + +

    These effects cause an element(s) to disappear or reappear over time.

    +

    $this->jquery->fadeIn(target, optional speed, optional extra information);
    + $this->jquery->fadeOut(target, optional speed, optional extra information);

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "speed" is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
    • +
    • "extra information" is optional, and could include a callback, or other additional information.
    • +
    + +

    slideUp() / slideDown() / slideToggle()

    + +

    These effects cause an element(s) to slide.

    +

    $this->jquery->slideUp(target, optional speed, optional extra information);
    + $this->jquery->slideDown(target, optional speed, optional extra information);
    +$this->jquery->slideToggle(target, optional speed, optional extra information);

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "speed" is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
    • +
    • "extra information" is optional, and could include a callback, or other additional information.
    • +
    + +

    Plugins

    + +

    + +

    Some select jQuery plugins are made available using this library.

    + +

    corner()

    +

    Used to add distinct corners to page elements. For full details see http://www.malsup.com/jquery/corner/

    +

    $this->jquery->corner(target, corner_style);

    +
      +
    • "target" will be any valid jQuery selector or selectors.
    • +
    • "corner_style" is optional, and can be set to any valid style such as round, sharp, bevel, bite, dog, etc. Individual corners can be set by following the style with a space and using "tl" (top left), "tr" (top right), "bl" (bottom left), or "br" (bottom right).
    • +
    +

    $this->jquery->corner("#note", "cool tl br");

    + +

    tablesorter()

    + +

    description to come

    + +

    modal()

    + +

    description to come

    + +

    calendar()

    + +

    description to come

    + +
    + + + + + + + diff --git a/api/user_guide/libraries/language.html b/api/user_guide/libraries/language.html new file mode 100644 index 0000000..09287ff --- /dev/null +++ b/api/user_guide/libraries/language.html @@ -0,0 +1,137 @@ + + + + + +Language Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Language Class

    + +

    The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.

    + +

    In your CodeIgniter system folder you'll find one called language containing sets of language files. You can create +your own language files as needed in order to display error and other messages in other languages.

    + +

    Language files are typically stored in your system/language directory. Alternately you can create a folder called language inside +your application folder and store them there. CodeIgniter will look first in your application/language +directory. If the directory does not exist or the specified language is not located there CI will instead look in your global +system/language folder.

    + +

    Note:  Each language should be stored in its own folder. For example, the English files are located at: +system/language/english

    + + + +

    Creating Language Files

    + +

    Language files must be named with _lang.php as the file extension. For example, let's say you want to create a file +containing error messages. You might name it: error_lang.php

    + +

    Within the file you will assign each line of text to an array called $lang with this prototype:

    + +$lang['language_key'] = "The actual message to be shown"; + +

    Note: It's a good practice to use a common prefix for all messages in a given file to avoid collisions with +similarly named items in other files. For example, if you are creating error messages you might prefix them with error_

    + +$lang['error_email_missing'] = "You must submit an email address";
    +$lang['error_url_missing'] = "You must submit a URL";
    +$lang['error_username_missing'] = "You must submit a username";
    + + +

    Loading A Language File

    + +

    In order to fetch a line from a particular file you must load the file first. Loading a language file is done with the following code:

    + +$this->lang->load('filename', 'language'); + +

    Where filename is the name of the file you wish to load (without the file extension), and language +is the language set containing it (ie, english). If the second parameter is missing, the default language set in your +application/config/config.php file will be used.

    + + +

    Fetching a Line of Text

    + +

    Once your desired language file is loaded you can access any line of text using this function:

    + +$this->lang->line('language_key'); + +

    Where language_key is the array key corresponding to the line you wish to show.

    + +

    Note: This function simply returns the line. It does not echo it for you.

    + +

    Using language lines as form labels

    + +

    This feature has been deprecated from the language library and moved to the lang() function of the Language helper.

    + +

    Auto-loading Languages

    +

    If you find that you need a particular language globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload.php file and adding the language(s) to the autoload array.

    +

     

    +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/loader.html b/api/user_guide/libraries/loader.html new file mode 100644 index 0000000..1000ca8 --- /dev/null +++ b/api/user_guide/libraries/loader.html @@ -0,0 +1,273 @@ + + + + + +Loader Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Loader Class

    + +

    Loader, as the name suggests, is used to load elements. These elements can be libraries (classes) View files, +Helpers, Models, or your own files.

    + +

    Note: This class is initialized automatically by the system so there is no need to do it manually.

    + +

    The following functions are available in this class:

    + + +

    $this->load->library('class_name', $config, 'object name')

    + + +

    This function is used to load core classes. Where class_name is the name of the class you want to load. +Note: We use the terms "class" and "library" interchangeably.

    + +

    For example, if you would like to send email with CodeIgniter, the first step is to load the email class within your controller:

    + +$this->load->library('email'); + +

    Once loaded, the library will be ready for use, using $this->email->some_function().

    + +

    Library files can be stored in subdirectories within the main "libraries" folder, or within your personal application/libraries folder. +To load a file located in a subdirectory, simply include the path, relative to the "libraries" folder. +For example, if you have file located at:

    + +libraries/flavors/chocolate.php + +

    You will load it using:

    + +$this->load->library('flavors/chocolate'); + +

    You may nest the file in as many subdirectories as you want.

    + +

    Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load function.

    + +$this->load->library(array('email', 'table')); + +

    Setting options

    + +

    The second (optional) parameter allows you to optionally pass configuration setting. You will typically pass these as an array:

    + + +$config = array (
    +                  'mailtype' => 'html',
    +                  'charset'  => 'utf-8,
    +                  'priority' => '1'
    +               );
    +
    +$this->load->library('email', $config);
    + +

    Config options can usually also be set via a config file. Each library is explained in detail in its own page, so please read the information regarding each one you would like to use.

    + +

    Please take note, when multiple libraries are supplied in an array for the first parameter, each will receive the same parameter information.

    + +

    Assigning a Library to a different object name

    + +

    If the third (optional) parameter is blank, the library will usually be assigned to an object with the same name as the library. For example, if the library is named Session, it +will be assigned to a variable named $this->session.

    + +

    If you prefer to set your own class names you can pass its value to the third parameter:

    + +$this->load->library('session', '', 'my_session');

    + +// Session class is now accessed using:

    + +$this->my_session + +
    + +

    Please take note, when multiple libraries are supplied in an array for the first parameter, this parameter is discarded.

    + + +

    $this->load->view('file_name', $data, true/false)

    + +

    This function is used to load your View files. If you haven't read the Views section of the +user guide it is recommended that you do since it shows you how this function is typically used.

    + +

    The first parameter is required. It is the name of the view file you would like to load.  Note: The .php file extension does not need to be specified unless you use something other than .php.

    + +

    The second optional parameter can take +an associative array or an object as input, which it runs through the PHP extract function to +convert to variables that can be used in your view files. Again, read the Views page to learn +how this might be useful.

    + +

    The third optional parameter lets you change the behavior of the function so that it returns data as a string +rather than sending it to your browser. This can be useful if you want to process the data in some way. If you +set the parameter to true (boolean) it will return data. The default behavior is false, which sends it +to your browser. Remember to assign it to a variable if you want the data returned:

    + +$string = $this->load->view('myfile', '', true); + + +

    $this->load->model('Model_name');

    +

    $this->load->model('Model_name');

    +

    If your model is located in a sub-folder, include the relative path from your models folder. For example, if you have a model located at application/models/blog/queries.php you'll load it using:

    +

    $this->load->model('blog/queries');

    +

    If you would like your model assigned to a different object name you can specify it via the second parameter of the loading + function:

    + $this->load->model('Model_name', 'fubar');
    +
    +$this->fubar->function();
    +

    $this->load->database('options', true/false)

    +

    This function lets you load the database class. The two parameters are optional. Please see the +database section for more info.

    + + + + +

    $this->load->vars($array)

    + +

    This function takes an associative array as input and generates variables using the PHP extract function. +This function produces the same result as using the second parameter of the $this->load->view() function above. The reason you might +want to use this function independently is if you would like to set some global variables in the constructor of your controller +and have them become available in any view file loaded from any function. You can have multiple calls to this function. The data get cached +and merged into one array for conversion to variables. +

    + + +

    $this->load->get_var($key)

    + +

    This function checks the associative array of variables available to your views. This is useful if for any reason a var is set in a library or another controller method using $this->load->vars(). +

    + + +

    $this->load->helper('file_name')

    +

    This function loads helper files, where file_name is the name of the file, without the _helper.php extension.

    + + +

    $this->load->file('filepath/filename', true/false)

    +

    This is a generic file loading function. Supply the filepath and name in the first parameter and it will open and read the file. +By default the data is sent to your browser, just like a View file, but if you set the second parameter to true (boolean) +it will instead return the data as a string.

    + + +

    $this->load->language('file_name')

    +

    This function is an alias of the language loading function: $this->lang->load()

    + +

    $this->load->config('file_name')

    +

    This function is an alias of the config file loading function: $this->config->load()

    + + +

    Application "Packages"

    + +

    An application package allows for the easy distribution of complete sets of resources in a single directory, complete with its own libraries, models, helpers, config, and language files. It is recommended that these packages be placed in the application/third_party folder. Below is a sample map of an package directory

    + + +

    Sample Package "Foo Bar" Directory Map

    + +

    The following is an example of a directory for an application package named "Foo Bar".

    + +/application/third_party/foo_bar
    +
    +config/
    +helpers/
    +language/
    +libraries/
    +models/
    +
    + +

    Whatever the purpose of the "Foo Bar" application package, it has its own config files, helpers, language files, libraries, and models. To use these resources in your controllers, you first need to tell the Loader that you are going to be loading resources from a package, by adding the package path.

    + +

    $this->load->add_package_path()

    + +

    Adding a package path instructs the Loader class to prepend a given path for subsequent requests for resources. As an example, the "Foo Bar" application package above has a library named Foo_bar.php. In our controller, we'd do the following:

    + +$this->load->add_package_path(APPPATH.'third_party/foo_bar/');
    +$this->load->library('foo_bar');
    + +

    $this->load->remove_package_path()

    + +

    When your controller is finished using resources from an application package, and particularly if you have other application packages you want to work with, you may wish to remove the package path so the Loader no longer looks in that folder for resources. To remove the last path added, simply call the method with no parameters.

    + +

    $this->load->remove_package_path()

    + +

    Or to remove a specific package path, specify the same path previously given to add_package_path() for a package.:

    + +$this->load->remove_package_path(APPPATH.'third_party/foo_bar/'); + +

    Package view files

    + +

    By Default, package view files paths are set when add_package_path() is called. View paths are looped through, and once a match is encountered that view is loaded.

    +

    In this instance, it is possible for view naming collisions within packages to occur, and possibly the incorrect package being loaded. To ensure against this, set an optional second parameter of FALSE when calling add_package_path().

    + + +$this->load->add_package_path(APPPATH.'my_app', TRUE);
    +$this->load->view('my_app_index'); // Loads
    +$this->load->view('welcome_message'); // Will not load the default welcome_message b/c the second param to add_package_path is TRUE
    +
    +// Reset things
    +$this->load->remove_package_path(APPPATH.'my_app');
    +
    +// Again without the second parameter:
    +$this->load->add_package_path(APPPATH.'my_app', TRUE);
    +$this->load->view('my_app_index'); // Loads
    +$this->load->view('welcome_message'); // Loads
    +
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/migration.html b/api/user_guide/libraries/migration.html new file mode 100644 index 0000000..018be30 --- /dev/null +++ b/api/user_guide/libraries/migration.html @@ -0,0 +1,176 @@ + + + + + +Migration Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Migration Class

    + +

    Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run them. You’d also have to keep track of which changes need to be run against the production machines next time you deploy.

    + +

    The database table migration tracks which migrations have already been run so all you have to do is update your application files and call $this->migrate->current() to work out which migrations should be run. The current version is found in config/migration.php.

    + +

    Create a Migration

    + +

    This will be the first migration for a new site which has a blog. All migrations go in the folder application/migrations/ and have names such as: 001_add_blog.php.

    + +
    +defined('BASEPATH') OR exit('No direct script access allowed');
    +
    +class Migration_Add_blog extends CI_Migration {
    +
    +	public function up()
    +	{
    +		$this->dbforge->add_field(array(
    +			'blog_id' => array(
    +				'type' => 'INT',
    +				'constraint' => 5,
    +				'unsigned' => TRUE,
    +				'auto_increment' => TRUE
    +			),
    +			'blog_title' => array(
    +				'type' => 'VARCHAR',
    +				'constraint' => '100',
    +			),
    +			'blog_description' => array(
    +				'type' => 'TEXT',
    +				'null' => TRUE,
    +			),
    +		));
    +
    +		$this->dbforge->create_table('blog');
    +	}
    +
    +	public function down()
    +	{
    +		$this->dbforge->drop_table('blog');
    +	}
    +
    + +

    Then in application/config/migration.php set $config['migration_version'] = 1;. + +

    Usage Example

    + +

    In this example some simple code is placed in application/controllers/migrate.php to update the schema.

    + +
    +$this->load->library('migration');
    +
    +if ( ! $this->migration->current())
    +{
    +	show_error($this->migration->error_string());
    +}
    +
    + + +

    Function Reference

    + +

    $this->migration->current()

    + +

    The current migration is whatever is set for $config['migration_version'] in application/config/migration.php.

    + + +

    $this->migration->latest()

    + +

    This works much the same way as current() but instead of looking for the $config['migration_version'] the Migration class will use the very newest migration found in the filesystem.

    + +

    $this->migration->version()

    + +

    Version can be used to roll back changes or step forwards programmatically to specific versions. It works just like current but ignores $config['migration_version'].

    + +
    +$this->load->library('migration');
    +
    +$this->migration->version(5);
    +
    + +

    Migration Preferences

    + +

    The following is a list of all the config options for migrations.

    + + + + + + + + + + + + + + + +
    PreferenceDefault ValueOptionsDescription
    migration_enabledFALSETRUE / FALSEEnable or disable migrations.
    migration_version0NoneThe current version your database should use.
    migration_pathAPPPATH.'migrations/'NoneThe path to your migrations folder.
    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/output.html b/api/user_guide/libraries/output.html new file mode 100644 index 0000000..072a25d --- /dev/null +++ b/api/user_guide/libraries/output.html @@ -0,0 +1,177 @@ + + + + + +Output Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Output Class

    + +

    The Output class is a small class with one main function: To send the finalized web page to the requesting browser. It is +also responsible for caching your web pages, if you use that feature.

    + +

    Note: This class is initialized automatically by the system so there is no need to do it manually.

    + +

    Under normal circumstances you won't even notice the Output class since it works transparently without your intervention. +For example, when you use the Loader class to load a view file, it's automatically +passed to the Output class, which will be called automatically by CodeIgniter at the end of system execution. +It is possible, however, for you to manually intervene with the output if you need to, using either of the two following functions:

    + +

    $this->output->set_output();

    + +

    Permits you to manually set the final output string. Usage example:

    + +$this->output->set_output($data); + +

    Important: If you do set your output manually, it must be the last thing done in the function you call it from. +For example, if you build a page in one of your controller functions, don't set the output until the end.

    + + +

    $this->output->set_content_type();

    + +

    Permits you to set the mime-type of your page so you can serve JSON data, JPEG's, XML, etc easily.

    + +$this->output
    +    ->set_content_type('application/json')
    +    ->set_output(json_encode(array('foo' => 'bar')));
    +
    +$this->output
    +    ->set_content_type('jpeg') // You could also use ".jpeg" which will have the full stop removed before looking in config/mimes.php
    +    ->set_output(file_get_contents('files/something.jpg'));
    + +

    Important: Make sure any non-mime string you pass to this method exists in config/mimes.php or it will have no effect.

    + + +

    $this->output->get_output();

    + +

    Permits you to manually retrieve any output that has been sent for storage in the output class. Usage example:

    +$string = $this->output->get_output(); + +

    Note that data will only be retrievable from this function if it has been previously sent to the output class by one of the +CodeIgniter functions like $this->load->view().

    + + +

    $this->output->append_output();

    + +

    Appends data onto the output string. Usage example:

    + +$this->output->append_output($data); + + + +

    $this->output->set_header();

    + +

    Permits you to manually set server headers, which the output class will send for you when outputting the final rendered display. Example:

    + + +$this->output->set_header("HTTP/1.0 200 OK");
    +$this->output->set_header("HTTP/1.1 200 OK");
    +$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT');
    +$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
    +$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
    +$this->output->set_header("Pragma: no-cache");
    + + +

    $this->output->set_status_header(code, 'text');

    + +

    Permits you to manually set a server status header. Example:

    + +$this->output->set_status_header('401');
    +// Sets the header as: Unauthorized
    + +

    See here for a full list of headers.

    + +

    $this->output->enable_profiler();

    + +

    Permits you to enable/disable the Profiler, which will display benchmark and other data +at the bottom of your pages for debugging and optimization purposes.

    + +

    To enable the profiler place the following function anywhere within your Controller functions:

    +$this->output->enable_profiler(TRUE); + +

    When enabled a report will be generated and inserted at the bottom of your pages.

    + +

    To disable the profiler you will use:

    +$this->output->enable_profiler(FALSE); + +

    $this->output->set_profiler_sections();

    + +

    Permits you to enable/disable specific sections of the Profiler when enabled. Please refer to the Profiler documentation for further information.

    + +

    $this->output->cache();

    +

    The CodeIgniter output library also controls caching. For more information, please see the caching documentation.

    + +

    Parsing Execution Variables

    + +

    CodeIgniter will parse the pseudo-variables {elapsed_time} and {memory_usage} in your output by default. To disable this, set the $parse_exec_vars class property to FALSE in your controller. + + $this->output->parse_exec_vars = FALSE; + +

    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/pagination.html b/api/user_guide/libraries/pagination.html new file mode 100644 index 0000000..5f1dde4 --- /dev/null +++ b/api/user_guide/libraries/pagination.html @@ -0,0 +1,233 @@ + + + + + +Pagination Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Pagination Class

    + +

    CodeIgniter's Pagination class is very easy to use, and it is 100% customizable, either dynamically or via stored preferences.

    + +

    If you are not familiar with the term "pagination", it refers to links that allows you to navigate from page to page, like this:

    + +« First  < 1 2 3 4 5 >  Last » + +

    Example

    + +

    Here is a simple example showing how to create pagination in one of your controller functions:

    + + +$this->load->library('pagination');

    +$config['base_url'] = 'http://example.com/index.php/test/page/';
    +$config['total_rows'] = 200;
    +$config['per_page'] = 20; +

    +$this->pagination->initialize($config); + +

    +echo $this->pagination->create_links();
    + +

    Notes:

    + +

    The $config array contains your configuration variables. It is passed to the $this->pagination->initialize function as shown above. Although there are some twenty items you can configure, at +minimum you need the three shown. Here is a description of what those items represent:

    + +
      +
    • base_url This is the full URL to the controller class/function containing your pagination. In the example + above, it is pointing to a controller called "Test" and a function called "page". Keep in mind that you can + re-route your URI if you need a different structure.
    • +
    • total_rows This number represents the total rows in the result set you are creating pagination for. + Typically this number will be the total rows that your database query returned. +
    • +
    • per_page The number of items you intend to show per page. In the above example, you would be showing 20 items per page.
    • +
    + +

    The create_links() function returns an empty string when there is no pagination to show.

    + + +

    Setting preferences in a config file

    + +

    If you prefer not to set preferences using the above method, you can instead put them into a config file. +Simply create a new file called pagination.php, add the $config +array in that file. Then save the file in: config/pagination.php and it will be used automatically. You +will NOT need to use the $this->pagination->initialize function if you save your preferences in a config file.

    + + +

    Customizing the Pagination

    + +

    The following is a list of all the preferences you can pass to the initialization function to tailor the display.

    + + +

    $config['uri_segment'] = 3;

    + +

    The pagination function automatically determines which segment of your URI contains the page number. If you need +something different you can specify it.

    + +

    $config['num_links'] = 2;

    + +

    The number of "digit" links you would like before and after the selected page number. For example, the number 2 + will place two digits on either side, as in the example links at the very top of this page.

    + +

    $config['use_page_numbers'] = TRUE;

    +

    By default, the URI segment will use the starting index for the items you are paginating. If you prefer to show the the actual page number, set this to TRUE.

    + +

    $config['page_query_string'] = TRUE;

    +

    By default, the pagination library assume you are using URI Segments, and constructs your links something like

    +

    http://example.com/index.php/test/page/20

    +

    If you have $config['enable_query_strings'] set to TRUE your links will automatically be re-written using Query Strings. This option can also be explictly set. Using $config['page_query_string'] set to TRUE, the pagination link will become.

    +

    http://example.com/index.php?c=test&m=page&per_page=20

    +

    Note that "per_page" is the default query string passed, however can be configured using $config['query_string_segment'] = 'your_string'

    +

    Adding Enclosing Markup

    + +

    If you would like to surround the entire pagination with some markup you can do it with these two prefs:

    + +

    $config['full_tag_open'] = '<p>';

    +

    The opening tag placed on the left side of the entire result.

    + +

    $config['full_tag_close'] = '</p>';

    +

    The closing tag placed on the right side of the entire result.

    + + +

    Customizing the First Link

    + +

    $config['first_link'] = 'First';

    +

    The text you would like shown in the "first" link on the left. If you do not want this link rendered, you can set its value to FALSE.

    + +

    $config['first_tag_open'] = '<div>';

    +

    The opening tag for the "first" link.

    + +

    $config['first_tag_close'] = '</div>';

    +

    The closing tag for the "first" link.

    + +

    Customizing the Last Link

    + +

    $config['last_link'] = 'Last';

    +

    The text you would like shown in the "last" link on the right. If you do not want this link rendered, you can set its value to FALSE.

    + +

    $config['last_tag_open'] = '<div>';

    +

    The opening tag for the "last" link.

    + +

    $config['last_tag_close'] = '</div>';

    +

    The closing tag for the "last" link.

    + +

    Customizing the "Next" Link

    + +

    $config['next_link'] = '&gt;';

    +

    The text you would like shown in the "next" page link. If you do not want this link rendered, you can set its value to FALSE.

    + +

    $config['next_tag_open'] = '<div>';

    +

    The opening tag for the "next" link.

    + +

    $config['next_tag_close'] = '</div>';

    +

    The closing tag for the "next" link.

    + +

    Customizing the "Previous" Link

    + +

    $config['prev_link'] = '&lt;';

    +

    The text you would like shown in the "previous" page link. If you do not want this link rendered, you can set its value to FALSE.

    + +

    $config['prev_tag_open'] = '<div>';

    +

    The opening tag for the "previous" link.

    + +

    $config['prev_tag_close'] = '</div>';

    +

    The closing tag for the "previous" link.

    + +

    Customizing the "Current Page" Link

    + +

    $config['cur_tag_open'] = '<b>';

    +

    The opening tag for the "current" link.

    + +

    $config['cur_tag_close'] = '</b>';

    +

    The closing tag for the "current" link.

    + + +

    Customizing the "Digit" Link

    + +

    $config['num_tag_open'] = '<div>';

    +

    The opening tag for the "digit" link.

    + +

    $config['num_tag_close'] = '</div>';

    +

    The closing tag for the "digit" link.

    + +

    Hiding the Pages

    + +

    If you wanted to not list the specific pages (for example, you only want "next" and "previous" links), you can suppress their rendering by adding:

    + + +$config['display_pages'] = FALSE; + + + +

    Adding a class to every anchor

    + +

    If you want to add a class attribute to every link rendered by the pagination class, you can set the config "anchor_class" equal to the classname you want.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/parser.html b/api/user_guide/libraries/parser.html new file mode 100644 index 0000000..0f4fce6 --- /dev/null +++ b/api/user_guide/libraries/parser.html @@ -0,0 +1,212 @@ + + + + + +Template Parser Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + + + +

    Template Parser Class

    + +

    The Template Parser Class enables you to parse pseudo-variables contained within your view files. It can parse simple +variables or variable tag pairs. If you've never used a template engine, pseudo-variables look like this:

    + +<html>
    +<head>
    +<title>{blog_title}</title>
    +</head>
    +<body>
    +
    +<h3>{blog_heading}</h3>
    +
    +{blog_entries}
    +<h5>{title}</h5>
    +<p>{body}</p>
    +{/blog_entries}
    + +</body>
    +</html>
    + +

    These variables are not actual PHP variables, but rather plain text representations that allow you to eliminate +PHP from your templates (view files).

    + +

    Note: CodeIgniter does not require you to use this class +since using pure PHP in your view pages lets them run a little faster. However, some developers prefer to use a template engine if +they work with designers who they feel would find some confusion working with PHP.

    + +

    Also Note: The Template Parser Class is not a +full-blown template parsing solution. We've kept it very lean on purpose in order to maintain maximum performance.

    + + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Parser class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('parser'); +

    Once loaded, the Parser library object will be available using: $this->parser

    + + +

    The following functions are available in this library:

    + +

    $this->parser->parse()

    + +

    This method accepts a template name and data array as input, and it generates a parsed version. Example:

    + +$this->load->library('parser');
    +
    +$data = array(
    +            'blog_title' => 'My Blog Title',
    +            'blog_heading' => 'My Blog Heading'
    +            );
    +
    +$this->parser->parse('blog_template', $data);
    + +

    The first parameter contains the name of the view file (in this example the file would be called blog_template.php), +and the second parameter contains an associative array of data to be replaced in the template. In the above example, the +template would contain two variables: {blog_title} and {blog_heading}

    + +

    There is no need to "echo" or do something with the data returned by $this->parser->parse(). It is automatically +passed to the output class to be sent to the browser. However, if you do want the data returned instead of sent to the output class you can +pass TRUE (boolean) to the third parameter:

    + +$string = $this->parser->parse('blog_template', $data, TRUE); + +

    $this->parser->parse_string()

    + +

    This method works exactly like parse(), only accepts a string as the first parameter in place of a view file.

    + + +

    Variable Pairs

    + +

    The above example code allows simple variables to be replaced. What if you would like an entire block of variables to be +repeated, with each iteration containing new values? Consider the template example we showed at the top of the page:

    + +<html>
    +<head>
    +<title>{blog_title}</title>
    +</head>
    +<body>
    +
    +<h3>{blog_heading}</h3>
    +
    +{blog_entries}
    +<h5>{title}</h5>
    +<p>{body}</p>
    +{/blog_entries}
    + +</body>
    +</html>
    + +

    In the above code you'll notice a pair of variables: {blog_entries} data... {/blog_entries}. +In a case like this, the entire chunk of data between these pairs would be repeated multiple times, corresponding +to the number of rows in a result.

    + +

    Parsing variable pairs is done using the identical code shown above to parse single variables, +except, you will add a multi-dimensional array corresponding to your variable pair data. +Consider this example:

    + + +$this->load->library('parser');
    +
    +$data = array(
    +              'blog_title'   => 'My Blog Title',
    +              'blog_heading' => 'My Blog Heading',
    +              'blog_entries' => array(
    +                                      array('title' => 'Title 1', 'body' => 'Body 1'),
    +                                      array('title' => 'Title 2', 'body' => 'Body 2'),
    +                                      array('title' => 'Title 3', 'body' => 'Body 3'),
    +                                      array('title' => 'Title 4', 'body' => 'Body 4'),
    +                                      array('title' => 'Title 5', 'body' => 'Body 5')
    +                                      )
    +            );
    +
    +$this->parser->parse('blog_template', $data);
    + +

    If your "pair" data is coming from a database result, which is already a multi-dimensional array, you can simply +use the database result_array() function:

    + + +$query = $this->db->query("SELECT * FROM blog");
    +
    +$this->load->library('parser');
    +
    +$data = array(
    +              'blog_title'   => 'My Blog Title',
    +              'blog_heading' => 'My Blog Heading',
    +              'blog_entries' => $query->result_array()
    +            );
    +
    +$this->parser->parse('blog_template', $data);
    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/security.html b/api/user_guide/libraries/security.html new file mode 100644 index 0000000..8661168 --- /dev/null +++ b/api/user_guide/libraries/security.html @@ -0,0 +1,135 @@ + + + + + +Security Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Security Class

    + +

    The Security Class contains methods that help you create a secure application, processing input data for security.

    + +

    XSS Filtering

    + +

    CodeIgniter comes with a Cross Site Scripting Hack prevention filter which can either run automatically to filter +all POST and COOKIE data that is encountered, or you can run it on a per item basis. By default it does not +run globally since it requires a bit of processing overhead, and since you may not need it in all cases.

    + +

    The XSS filter looks for commonly used techniques to trigger Javascript or other types of code that attempt to hijack cookies +or do other malicious things. If anything disallowed is encountered it is rendered safe by converting the data to character entities.

    + +

    +Note: This function should only be used to deal with data upon submission. It's not something that should be used for general runtime processing since it requires a fair amount of processing overhead.

    + + +

    To filter data through the XSS filter use this function:

    + +

    $this->security->xss_clean()

    + +

    Here is an usage example:

    + +$data = $this->security->xss_clean($data); + +

    If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your +application/config/config.php file and setting this:

    + +$config['global_xss_filtering'] = TRUE; + +

    Note: If you use the form validation class, it gives you the option of XSS filtering as well.

    + +

    An optional second parameter, is_image, allows this function to be used to test images for potential XSS attacks, useful for file upload security. When this second parameter is set to TRUE, instead of returning an altered string, the function returns TRUE if the image is safe, and FALSE if it contained potentially malicious information that a browser may attempt to execute.

    + +if ($this->security->xss_clean($file, TRUE) === FALSE)
    +{
    +    // file failed the XSS test
    +}
    + + +

    $this->security->sanitize_filename()

    + +

    When accepting filenames from user input, it is best to sanitize them to prevent directory traversal and other security related issues. To do so, use the sanitize_filename() method of the Security class. Here is an example:

    + +$filename = $this->security->sanitize_filename($this->input->post('filename')); + +

    If it is acceptable for the user input to include relative paths, e.g. file/in/some/approved/folder.txt, you can set the second optional parameter, + $relative_path to TRUE.

    + +$filename = $this->security->sanitize_filename($this->input->post('filename'), TRUE); + + + +

    Cross-site request forgery (CSRF)

    + +

    You can enable csrf protection by opening your application/config/config.php file and setting this:

    +$config['csrf_protection'] = TRUE; + +

    If you use the form helper the form_open() function will automatically insert a hidden csrf field in your forms.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/sessions.html b/api/user_guide/libraries/sessions.html new file mode 100644 index 0000000..1b7b73a --- /dev/null +++ b/api/user_guide/libraries/sessions.html @@ -0,0 +1,341 @@ + + + + + +Session Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Session Class

    + +

    The Session class permits you maintain a user's "state" and track their activity while they browse your site. +The Session class stores session information for each user as serialized (and optionally encrypted) data in a cookie. +It can also store the session data in a database table for added security, as this permits the session ID in the +user's cookie to be matched against the stored session ID. By default only the cookie is saved. If you choose to +use the database option you'll need to create the session table as indicated below. +

    + +

    Note: The Session class does not utilize native PHP sessions. It +generates its own session data, offering more flexibility for developers.

    + +

    Note: Even if you are not using encrypted sessions, you must set +an encryption key in your config file which is used to aid in preventing session data manipulation.

    + +

    Initializing a Session

    + +

    Sessions will typically run globally with each page load, so the session class must either be +initialized in your +controller constructors, or it can be +auto-loaded by the system. +For the most part the session class will run unattended in the background, so simply initializing the class +will cause it to read, create, and update sessions.

    + + +

    To initialize the Session class manually in your controller constructor, use the $this->load->library function:

    + +$this->load->library('session'); +

    Once loaded, the Sessions library object will be available using: $this->session

    + + +

    How do Sessions work?

    + +

    When a page is loaded, the session class will check to see if valid session data exists in the user's session cookie. +If sessions data does not exist (or if it has expired) a new session will be created and saved in the cookie. +If a session does exist, its information will be updated and the cookie will be updated. With each update, the session_id will be regenerated.

    + +

    It's important for you to understand that once initialized, the Session class runs automatically. There is nothing +you need to do to cause the above behavior to happen. You can, as you'll see below, work with session data or +even add your own data to a user's session, but the process of reading, writing, and updating a session is automatic.

    + + +

    What is Session Data?

    + +

    A session, as far as CodeIgniter is concerned, is simply an array containing the following information:

    + +
      +
    • The user's unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for portability, and regenerated (by default) every five minutes)
    • +
    • The user's IP Address
    • +
    • The user's User Agent data (the first 120 characters of the browser data string)
    • +
    • The "last activity" time stamp.
    • +
    + +

    The above data is stored in a cookie as a serialized array with this prototype:

    + +[array]
    +(
    +     'session_id'    => random hash,
    +     'ip_address'    => 'string - user IP address',
    +     'user_agent'    => 'string - user agent data',
    +     'last_activity' => timestamp
    +)
    + +

    If you have the encryption option enabled, the serialized array will be encrypted before being stored in the cookie, +making the data highly secure and impervious to being read or altered by someone. More info regarding encryption +can be found here, although the Session class will take care of initializing +and encrypting the data automatically.

    + +

    Note: Session cookies are only updated every five minutes by default to reduce processor load. If you repeatedly reload a page +you'll notice that the "last activity" time only updates if five minutes or more has passed since the last time +the cookie was written. This time is configurable by changing the $config['sess_time_to_update'] line in your system/config/config.php file.

    + +

    Retrieving Session Data

    + +

    Any piece of information from the session array is available using the following function:

    + +$this->session->userdata('item'); + +

    Where item is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you +will do this:

    + +$session_id = $this->session->userdata('session_id'); + +

    Note: The function returns FALSE (boolean) if the item you are trying to access does not exist.

    + + +

    Adding Custom Session Data

    + +

    A useful aspect of the session array is that you can add your own data to it and it will be stored in the user's cookie. +Why would you want to do this? Here's one example:

    + +

    Let's say a particular user logs into your site. Once authenticated, +you could add their username and email address to the session cookie, making that data globally available to you without +having to run a database query when you need it.

    + +

    To add your data to the session array involves passing an array containing your new data to this function:

    + +$this->session->set_userdata($array); + +

    Where $array is an associative array containing your new data. Here's an example:

    + + +

    $newdata = array(
    +                    'username'  => 'johndoe',
    +                    'email'     => 'johndoe@some-site.com',
    +                    'logged_in' => TRUE
    +                );
    +
    + $this->session->set_userdata($newdata);

    +

    If you want to add userdata one value at a time, set_userdata() also supports this syntax.

    +

    $this->session->set_userdata('some_name', 'some_value');

    +

    Note: Cookies can only hold 4KB of data, so be careful not to exceed the capacity. The +encryption process in particular produces a longer data string than the original so keep careful track of how much data you are storing.

    + +

    Retrieving All Session Data

    +

    An array of all userdata can be retrieved as follows:

    +$this->session->all_userdata() + +

    And returns an associative array like the following:

    + +
    +Array
    +(
    +    [session_id] => 4a5a5dca22728fb0a84364eeb405b601
    +    [ip_address] => 127.0.0.1
    +    [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
    +    [last_activity] => 1303142623
    +)
    +
    + + +

    Removing Session Data

    +

    Just as set_userdata() can be used to add information into a session, unset_userdata() can be used to remove it, by passing the session key. For example, if you wanted to remove 'some_name' from your session information:

    +

    $this->session->unset_userdata('some_name');

    +

    This function can also be passed an associative array of items to unset.

    +

    $array_items = array('username' => '', 'email' => '');
    +
    +$this->session->unset_userdata($array_items);

    +

    Flashdata

    +

    CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").

    +

    Note: Flash variables are prefaced with "flash_" so avoid this prefix in your own session names.

    +

    To add flashdata:

    +

    $this->session->set_flashdata('item', 'value');

    +

    You can also pass an array to set_flashdata(), in the same manner as set_userdata().

    +

    To read a flashdata variable:

    +

    $this->session->flashdata('item');

    +

    If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() function.

    +

    $this->session->keep_flashdata('item');

    +

    Saving Session Data to a Database

    +

    While the session data array stored in the user's cookie contains a Session ID, +unless you store session data in a database there is no way to validate it. For some applications that require little or no +security, session ID validation may not be needed, but if your application requires security, validation is mandatory. Otherwise, an old session +could be restored by a user modifying their cookies.

    + +

    When session data is available in a database, every time a valid session is found in the user's cookie, a database +query is performed to match it. If the session ID does not match, the session is destroyed. Session IDs can never +be updated, they can only be generated when a new session is created.

    + + +

    In order to store sessions, you must first create a database table for this purpose. Here is the basic +prototype (for MySQL) required by the session class:

    + + + +

    Note: By default the table is called ci_sessions, but you can name it anything you want +as long as you update the application/config/config.php file so that it contains the name you have chosen. +Once you have created your database table you can enable the database option in your config.php file as follows:

    + +$config['sess_use_database'] = TRUE; + +

    Once enabled, the Session class will store session data in the DB.

    + +

    Make sure you've specified the table name in your config file as well:

    + +$config['sess_table_name'] = 'ci_sessions'; + +

    Note: The Session class has built-in garbage collection which clears out expired sessions so you +do not need to write your own routine to do it.

    + + +

    Destroying a Session

    +

    To clear the current session:

    +$this->session->sess_destroy(); +

    Note: This function should be the last one called, and even flash variables will no longer be available. If you only want some items destroyed and not all, use unset_userdata().

    + + + +

    Session Preferences

    +

    You'll find the following Session related preferences in your application/config/config.php file:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PreferenceDefaultOptionsDescription
    sess_cookie_nameci_sessionNoneThe name you want the session cookie saved as.
    sess_expiration7200NoneThe number of seconds you would like the session to last. The default value is 2 hours (7200 seconds). If you would like a non-expiring session set the value to zero: 0
    sess_expire_on_closeFALSETRUE/FALSE (boolean)Whether to cause the session to expire automatically when the browser window is closed.
    sess_encrypt_cookieFALSETRUE/FALSE (boolean)Whether to encrypt the session data.
    sess_use_databaseFALSETRUE/FALSE (boolean)Whether to save the session data to a database. You must create the table before enabling this option.
    sess_table_nameci_sessionsAny valid SQL table nameThe name of the session database table.
    sess_time_to_update300Time in secondsThis options controls how often the session class will regenerate itself and create a new session id.
    sess_match_ipFALSETRUE/FALSE (boolean)Whether to match the user's IP address when reading the session data. Note that some ISPs dynamically + changes the IP, so if you want a non-expiring session you will likely set this to FALSE.
    sess_match_useragentTRUETRUE/FALSE (boolean)Whether to match the User Agent when reading the session data.
    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/table.html b/api/user_guide/libraries/table.html new file mode 100644 index 0000000..c951496 --- /dev/null +++ b/api/user_guide/libraries/table.html @@ -0,0 +1,315 @@ + + + + +CodeIgniter User Guide : HTML Table Class + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    HTML Table Class

    + +

    The Table Class provides functions that enable you to auto-generate HTML tables from arrays or database result sets.

    + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Table class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('table'); +

    Once loaded, the Table library object will be available using: $this->table

    + + +

    Examples

    + +

    Here is an example showing how you can create a table from a multi-dimensional array. +Note that the first array index will become the table heading (or you can set your own headings using the +set_heading() function described in the function reference below).

    + + +$this->load->library('table');
    +
    +$data = array(
    +             array('Name', 'Color', 'Size'),
    +             array('Fred', 'Blue', 'Small'),
    +             array('Mary', 'Red', 'Large'),
    +             array('John', 'Green', 'Medium')
    +             );
    +
    +echo $this->table->generate($data); +
    + +

    Here is an example of a table created from a database query result. The table class will automatically generate the +headings based on the table names (or you can set your own headings using the set_heading() function described +in the function reference below).

    + + +$this->load->library('table');
    +
    +$query = $this->db->query("SELECT * FROM my_table");
    +
    +echo $this->table->generate($query); +
    + + +

    Here is an example showing how you might create a table using discrete parameters:

    + + +$this->load->library('table');
    +
    +$this->table->set_heading('Name', 'Color', 'Size');
    +
    +$this->table->add_row('Fred', 'Blue', 'Small');
    +$this->table->add_row('Mary', 'Red', 'Large');
    +$this->table->add_row('John', 'Green', 'Medium');
    +
    +echo $this->table->generate(); +
    + +

    Here is the same example, except instead of individual parameters, arrays are used:

    + + +$this->load->library('table');
    +
    +$this->table->set_heading(array('Name', 'Color', 'Size'));
    +
    +$this->table->add_row(array('Fred', 'Blue', 'Small'));
    +$this->table->add_row(array('Mary', 'Red', 'Large'));
    +$this->table->add_row(array('John', 'Green', 'Medium'));
    +
    +echo $this->table->generate(); +
    + + +

    Changing the Look of Your Table

    + +

    The Table Class permits you to set a table template with which you can specify the design of your layout. Here is the template +prototype:

    + + +$tmpl = array (
    +                    'table_open'          => '<table border="0" cellpadding="4" cellspacing="0">',
    +
    +                    'heading_row_start'   => '<tr>',
    +                    'heading_row_end'     => '</tr>',
    +                    'heading_cell_start'  => '<th>',
    +                    'heading_cell_end'    => '</th>',
    +
    +                    'row_start'           => '<tr>',
    +                    'row_end'             => '</tr>',
    +                    'cell_start'          => '<td>',
    +                    'cell_end'            => '</td>',
    +
    +                    'row_alt_start'       => '<tr>',
    +                    'row_alt_end'         => '</tr>',
    +                    'cell_alt_start'      => '<td>',
    +                    'cell_alt_end'        => '</td>',
    +
    +                    'table_close'         => '</table>'
    +              );
    + +
    +$this->table->set_template($tmpl); +
    + +

    Note:  You'll notice there are two sets of "row" blocks in the template. These permit you to create alternating row colors or design elements that alternate with each +iteration of the row data.

    + +

    You are NOT required to submit a complete template. If you only need to change parts of the layout you can simply submit those elements. +In this example, only the table opening tag is being changed:

    + + +$tmpl = array ( 'table_open'  => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">' );
    + +
    +$this->table->set_template($tmpl); +
    + +
    +

    Function Reference

    + +

    $this->table->generate()

    +

    Returns a string containing the generated table. Accepts an optional parameter which can be an array or a database result object.

    + +

    $this->table->set_caption()

    + +

    Permits you to add a caption to the table.

    + +$this->table->set_caption('Colors'); + +

    $this->table->set_heading()

    + +

    Permits you to set the table heading. You can submit an array or discrete params:

    + +$this->table->set_heading('Name', 'Color', 'Size'); +$this->table->set_heading(array('Name', 'Color', 'Size')); + +

    $this->table->add_row()

    + +

    Permits you to add a row to your table. You can submit an array or discrete params:

    + +$this->table->add_row('Blue', 'Red', 'Green'); +$this->table->add_row(array('Blue', 'Red', 'Green')); + +

    If you would like to set an individual cell's tag attributes, you can use an associative array for that cell. The associative key 'data' defines the cell's data. Any other key => val pairs are added as key='val' attributes to the tag:

    + +$cell = array('data' => 'Blue', 'class' => 'highlight', 'colspan' => 2);
    +$this->table->add_row($cell, 'Red', 'Green');
    +
    +// generates
    +// <td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td> +
    + +

    $this->table->make_columns()

    + +

    This function takes a one-dimensional array as input and creates +a multi-dimensional array with a depth equal to the number of +columns desired. This allows a single array with many elements to be +displayed in a table that has a fixed column count. Consider this example:

    + + +$list = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve');
    +
    +$new_list = $this->table->make_columns($list, 3);
    +
    +$this->table->generate($new_list);
    +
    +// Generates a table with this prototype
    +
    +<table border="0" cellpadding="4" cellspacing="0">
    +<tr>
    +<td>one</td><td>two</td><td>three</td>
    +</tr><tr>
    +<td>four</td><td>five</td><td>six</td>
    +</tr><tr>
    +<td>seven</td><td>eight</td><td>nine</td>
    +</tr><tr>
    +<td>ten</td><td>eleven</td><td>twelve</td></tr>
    +</table>
    + + + +

    $this->table->set_template()

    + +

    Permits you to set your template. You can submit a full or partial template.

    + + +$tmpl = array ( 'table_open'  => '<table border="1" cellpadding="2" cellspacing="1" class="mytable">' );
    + +
    +$this->table->set_template($tmpl); +
    + + +

    $this->table->set_empty()

    + +

    Let's you set a default value for use in any table cells that are empty. You might, for example, set a non-breaking space:

    + + +$this->table->set_empty("&nbsp;"); + + +

    $this->table->clear()

    + +

    Lets you clear the table heading and row data. If you need to show multiple tables with different data you should +to call this function after each table has been generated to empty the previous table information. Example:

    + + +$this->load->library('table');
    +
    +$this->table->set_heading('Name', 'Color', 'Size');
    +$this->table->add_row('Fred', 'Blue', 'Small');
    +$this->table->add_row('Mary', 'Red', 'Large');
    +$this->table->add_row('John', 'Green', 'Medium');
    +
    +echo $this->table->generate();
    +
    +$this->table->clear();
    +
    +$this->table->set_heading('Name', 'Day', 'Delivery');
    +$this->table->add_row('Fred', 'Wednesday', 'Express');
    +$this->table->add_row('Mary', 'Monday', 'Air');
    +$this->table->add_row('John', 'Saturday', 'Overnight');
    +
    +echo $this->table->generate(); +
    + +

    $this->table->function

    + +

    Allows you to specify a native PHP function or a valid function array object to be applied to all cell data.

    + +$this->load->library('table');
    +
    +$this->table->set_heading('Name', 'Color', 'Size');
    +$this->table->add_row('Fred', '<strong>Blue</strong>', 'Small');
    +
    +$this->table->function = 'htmlspecialchars';
    +echo $this->table->generate();
    +
    + +

    In the above example, all cell data would be ran through PHP's htmlspecialchars() function, resulting in:

    + +<td>Fred</td><td>&lt;strong&gt;Blue&lt;/strong&gt;</td><td>Small</td> +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/trackback.html b/api/user_guide/libraries/trackback.html new file mode 100644 index 0000000..e03aad4 --- /dev/null +++ b/api/user_guide/libraries/trackback.html @@ -0,0 +1,246 @@ + + + + + +Trackback Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Trackback Class

    + +

    The Trackback Class provides functions that enable you to send and receive Trackback data.

    + + +

    If you are not familiar with Trackbacks you'll find more information here.

    + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Trackback class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('trackback'); +

    Once loaded, the Trackback library object will be available using: $this->trackback

    + + +

    Sending Trackbacks

    + +

    A Trackback can be sent from any of your controller functions using code similar to this example:

    + +$this->load->library('trackback');
    +
    +$tb_data = array(
    +                'ping_url'  => 'http://example.com/trackback/456',
    +                'url'       => 'http://www.my-example.com/blog/entry/123',
    +                'title'     => 'The Title of My Entry',
    +                'excerpt'   => 'The entry content.',
    +                'blog_name' => 'My Blog Name',
    +                'charset'   => 'utf-8'
    +                );
    +
    +if ( ! $this->trackback->send($tb_data))
    +{
    +     echo $this->trackback->display_errors();
    +}
    +else
    +{
    +     echo 'Trackback was sent!';
    +}
    + +

    Description of array data:

    + +
      +
    • ping_url - The URL of the site you are sending the Trackback to. You can send Trackbacks to multiple URLs by separating each URL with a comma.
    • +
    • url - The URL to YOUR site where the weblog entry can be seen.
    • +
    • title - The title of your weblog entry.
    • +
    • excerpt - The content of your weblog entry. Note: the Trackback class will automatically send only the first 500 characters of your entry. It will also strip all HTML.
    • +
    • blog_name - The name of your weblog.
    • +
    • charset - The character encoding your weblog is written in. If omitted, UTF-8 will be used.
    • +
    + +

    The Trackback sending function returns TRUE/FALSE (boolean) on success or failure. If it fails, you can retrieve the error message using:

    + +$this->trackback->display_errors(); + + +

    Receiving Trackbacks

    + +

    Before you can receive Trackbacks you must create a weblog. If you don't have a blog yet there's no point in continuing.

    + +

    Receiving Trackbacks is a little more complex than sending them, only because you will need a database table in which to store them, +and you will need to validate the incoming trackback data. You are encouraged to implement a thorough validation process to +guard against spam and duplicate data. You may also want to limit the number of Trackbacks you allow from a particular IP within +a given span of time to further curtail spam. The process of receiving a Trackback is quite simple; +the validation is what takes most of the effort.

    + +

    Your Ping URL

    + +

    In order to accept Trackbacks you must display a Trackback URL next to each one of your weblog entries. This will be the URL +that people will use to send you Trackbacks (we will refer to this as your "Ping URL").

    + +

    Your Ping URL must point to a controller function where your Trackback receiving code is located, and the URL +must contain the ID number for each particular entry, so that when the Trackback is received you'll be +able to associate it with a particular entry.

    + +

    For example, if your controller class is called Trackback, and the receiving function is called receive, your +Ping URLs will look something like this:

    + +http://example.com/index.php/trackback/receive/entry_id + +

    Where entry_id represents the individual ID number for each of your entries.

    + + +

    Creating a Trackback Table

    + +

    Before you can receive Trackbacks you must create a table in which to store them. Here is a basic prototype for such a table:

    + + + + +

    The Trackback specification only requires four pieces of information to be sent in a Trackback (url, title, excerpt, blog_name), +but to make the data more useful we've added a few more fields in the above table schema (date, IP address, etc.).

    + +

    Processing a Trackback

    + +

    Here is an example showing how you will receive and process a Trackback. The following +code is intended for use within the controller function where you expect to receive Trackbacks.

    + +$this->load->library('trackback');
    +$this->load->database();
    +
    +if ($this->uri->segment(3) == FALSE)
    +{
    +    $this->trackback->send_error("Unable to determine the entry ID");
    +}
    +
    +if ( ! $this->trackback->receive())
    +{
    +    $this->trackback->send_error("The Trackback did not contain valid data");
    +}
    +
    +$data = array(
    +                'tb_id'      => '',
    +                'entry_id'   => $this->uri->segment(3),
    +                'url'        => $this->trackback->data('url'),
    +                'title'      => $this->trackback->data('title'),
    +                'excerpt'    => $this->trackback->data('excerpt'),
    +                'blog_name'  => $this->trackback->data('blog_name'),
    +                'tb_date'    => time(),
    +                'ip_address' => $this->input->ip_address()
    +                );
    +
    +$sql = $this->db->insert_string('trackbacks', $data);
    +$this->db->query($sql);
    +
    +$this->trackback->send_success();
    + +

    Notes:

    + +

    The entry ID number is expected in the third segment of your URL. This is based on the URI example we gave earlier:

    + +http://example.com/index.php/trackback/receive/entry_id + +

    Notice the entry_id is in the third URI segment, which you can retrieve using:

    + +$this->uri->segment(3); + +

    In our Trackback receiving code above, if the third segment is missing, we will issue an error. Without a valid entry ID, there's no +reason to continue.

    + +

    The $this->trackback->receive() function is simply a validation function that looks at the incoming data +and makes sure it contains the four pieces of data that are required (url, title, excerpt, blog_name). +It returns TRUE on success and FALSE on failure. If it fails you will issue an error message.

    + +

    The incoming Trackback data can be retrieved using this function:

    + +$this->trackback->data('item') + +

    Where item represents one of these four pieces of info: url, title, excerpt, or blog_name

    + +

    If the Trackback data is successfully received, you will issue a success message using:

    + +$this->trackback->send_success(); + +

    Note: The above code contains no data validation, which you are encouraged to add.

    + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/typography.html b/api/user_guide/libraries/typography.html new file mode 100644 index 0000000..93e0cd4 --- /dev/null +++ b/api/user_guide/libraries/typography.html @@ -0,0 +1,160 @@ + + + + + +Typography Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Typography Class

    + +

    The Typography Class provides functions that help you format text.

    + + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Typography class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('typography'); +

    Once loaded, the Typography library object will be available using: $this->typography

    + + +

    auto_typography()

    + +

    Formats text so that it is semantically and typographically correct HTML. Takes a string as input and returns it with +the following formatting:

    + +
      +
    • Surrounds paragraphs within <p></p> (looks for double line breaks to identify paragraphs).
    • +
    • Single line breaks are converted to <br />, except those that appear within <pre> tags.
    • +
    • Block level elements, like <div> tags, are not wrapped within paragraphs, but their contained text is if it contains paragraphs.
    • +
    • Quotes are converted to correctly facing curly quote entities, except those that appear within tags.
    • +
    • Apostrophes are converted to curly apostrophe entities.
    • +
    • Double dashes (either like -- this or like--this) are converted to em—dashes.
    • +
    • Three consecutive periods either preceding or following a word are converted to ellipsis…
    • +
    • Double spaces following sentences are converted to non-breaking spaces to mimic double spacing.
    • +
    + +

    Usage example:

    + +$string = $this->typography->auto_typography($string); + +

    Parameters

    + +

    There is one optional parameters that determines whether the parser should reduce more then two consecutive line breaks down to two. Use boolean TRUE or FALSE.

    + +

    By default the parser does not reduce line breaks. In other words, if no parameters are submitted, it is the same as doing this:

    + +$string = $this->typography->auto_typography($string, FALSE); + + +

    Note: Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. +If you choose to use this function you may want to consider +caching your pages.

    + + + +

    format_characters()

    + +

    This function is similar to the auto_typography function above, except that it only does character conversion:

    + +
      +
    • Quotes are converted to correctly facing curly quote entities, except those that appear within tags.
    • +
    • Apostrophes are converted to curly apostrophe entities.
    • +
    • Double dashes (either like -- this or like--this) are converted to em—dashes.
    • +
    • Three consecutive periods either preceding or following a word are converted to ellipsis…
    • +
    • Double spaces following sentences are converted to non-breaking spaces to mimic double spacing.
    • +
    + +

    Usage example:

    + +$string = $this->typography->format_characters($string); + + +

    nl2br_except_pre()

    + +

    Converts newlines to <br /> tags unless they appear within <pre> tags. +This function is identical to the native PHP nl2br() function, except that it ignores <pre> tags.

    + +

    Usage example:

    + +$string = $this->typography->nl2br_except_pre($string); + +

    protect_braced_quotes

    + +

    When using the Typography library in conjunction with the Template Parser library it can often be desirable to protect single + and double quotes within curly braces. To enable this, set the protect_braced_quotes class property to TRUE.

    + +

    Usage example:

    + +$this->load->library('typography');
    +$this->typography->protect_braced_quotes = TRUE; +
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/unit_testing.html b/api/user_guide/libraries/unit_testing.html new file mode 100644 index 0000000..553d439 --- /dev/null +++ b/api/user_guide/libraries/unit_testing.html @@ -0,0 +1,226 @@ + + + + + +Unit Testing Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Unit Testing Class

    + +

    Unit testing is an approach to software development in which tests are written for each function in your application. +If you are not familiar with the concept you might do a little googling on the subject.

    + +

    CodeIgniter's Unit Test class is quite simple, consisting of an evaluation function and two result functions. +It's not intended to be a full-blown test suite but rather a simple mechanism to evaluate your code +to determine if it is producing the correct data type and result. +

    + + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the Unit Test class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('unit_test'); +

    Once loaded, the Unit Test object will be available using: $this->unit

    + + +

    Running Tests

    + +

    Running a test involves supplying a test and an expected result to the following function:

    + +

    $this->unit->run( test, expected result, 'test name', 'notes');

    + +

    Where test is the result of the code you wish to test, expected result is the data type you expect, +test name is an optional name you can give your test, and notes are optional notes. Example:

    + +$test = 1 + 1;
    +
    +$expected_result = 2;
    +
    +$test_name = 'Adds one plus one';
    +
    +$this->unit->run($test, $expected_result, $test_name);
    + +

    The expected result you supply can either be a literal match, or a data type match. Here's an example of a literal:

    + +$this->unit->run('Foo', 'Foo'); + +

    Here is an example of a data type match:

    + +$this->unit->run('Foo', 'is_string'); + +

    Notice the use of "is_string" in the second parameter? This tells the function to evaluate whether your test is producing a string +as the result. Here is a list of allowed comparison types:

    + +
      +
    • is_object
    • +
    • is_string
    • +
    • is_bool
    • +
    • is_true
    • +
    • is_false
    • +
    • is_int
    • +
    • is_numeric
    • +
    • is_float
    • +
    • is_double
    • +
    • is_array
    • +
    • is_null
    • +
    + + +

    Generating Reports

    + +

    You can either display results after each test, or your can run several tests and generate a report at the end. +To show a report directly simply echo or return the run function:

    + +echo $this->unit->run($test, $expected_result); + +

    To run a full report of all tests, use this:

    + +echo $this->unit->report(); + +

    The report will be formatted in an HTML table for viewing. If you prefer the raw data you can retrieve an array using:

    + +echo $this->unit->result(); + + +

    Strict Mode

    + +

    By default the unit test class evaluates literal matches loosely. Consider this example:

    + +$this->unit->run(1, TRUE); + +

    The test is evaluating an integer, but the expected result is a boolean. PHP, however, due to it's loose data-typing +will evaluate the above code as TRUE using a normal equality test:

    + +if (1 == TRUE) echo 'This evaluates as true'; + +

    If you prefer, you can put the unit test class in to strict mode, which will compare the data type as well as the value:

    + +if (1 === TRUE) echo 'This evaluates as FALSE'; + +

    To enable strict mode use this:

    + +$this->unit->use_strict(TRUE); + +

    Enabling/Disabling Unit Testing

    + +

    If you would like to leave some testing in place in your scripts, but not have it run unless you need it, you can disable +unit testing using:

    + +$this->unit->active(FALSE) + +

    Unit Test Display

    + +

    When your unit test results display, the following items show by default:

    + +
      +
    • Test Name (test_name)
    • +
    • Test Datatype (test_datatype)
    • +
    • Expected Datatype (res_datatype)
    • +
    • Result (result)
    • +
    • File Name (file)
    • +
    • Line Number (line)
    • +
    • Any notes you entered for the test (notes)
    • +
    + +You can customize which of these items get displayed by using $this->unit->set_items(). For example, if you only wanted the test name and the result displayed:

    + +

    Customizing displayed tests

    + + + $this->unit->set_test_items(array('test_name', 'result')); + + +

    Creating a Template

    + +

    If you would like your test results formatted differently then the default you can set your own template. Here is an +example of a simple template. Note the required pseudo-variables:

    + + +$str = '
    +<table border="0" cellpadding="4" cellspacing="1">
    +    {rows}
    +        <tr>
    +        <td>{item}</td>
    +        <td>{result}</td>
    +        </tr>
    +    {/rows}
    +</table>';
    +
    +$this->unit->set_template($str); +
    + +

    Note: Your template must be declared before running the unit test process.

    + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/uri.html b/api/user_guide/libraries/uri.html new file mode 100644 index 0000000..2f4f34b --- /dev/null +++ b/api/user_guide/libraries/uri.html @@ -0,0 +1,252 @@ + + + + + +URI Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    URI Class

    + +

    The URI Class provides functions that help you retrieve information from your URI strings. If you use URI routing, you can +also retrieve information about the re-routed segments.

    + +

    Note: This class is initialized automatically by the system so there is no need to do it manually.

    + +

    $this->uri->segment(n)

    + +

    Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. +Segments are numbered from left to right. For example, if your full URL is this:

    + +http://example.com/index.php/news/local/metro/crime_is_up + +

    The segment numbers would be this:

    + +
      +
    1. news
    2. +
    3. local
    4. +
    5. metro
    6. +
    7. crime_is_up
    8. +
    + +

    By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that +permits you to set your own default value if the segment is missing. +For example, this would tell the function to return the number zero in the event of failure:

    + +$product_id = $this->uri->segment(3, 0); + +

    It helps avoid having to write code like this:

    + +if ($this->uri->segment(3) === FALSE)
    +{
    +    $product_id = 0;
    +}
    +else
    +{
    +    $product_id = $this->uri->segment(3);
    +}
    +
    + +

    $this->uri->rsegment(n)

    + +

    This function is identical to the previous one, except that it lets you retrieve a specific segment from your +re-routed URI in the event you are using CodeIgniter's URI Routing feature.

    + + +

    $this->uri->slash_segment(n)

    + +

    This function is almost identical to $this->uri->segment(), except it adds a trailing and/or leading slash based on the second +parameter. If the parameter is not used, a trailing slash added. Examples:

    + +$this->uri->slash_segment(3);
    +$this->uri->slash_segment(3, 'leading');
    +$this->uri->slash_segment(3, 'both');
    + +

    Returns:

    + +
      +
    1. segment/
    2. +
    3. /segment
    4. +
    5. /segment/
    6. +
    + + +

    $this->uri->slash_rsegment(n)

    + +

    This function is identical to the previous one, except that it lets you add slashes a specific segment from your +re-routed URI in the event you are using CodeIgniter's URI Routing feature.

    + + + +

    $this->uri->uri_to_assoc(n)

    + +

    This function lets you turn URI segments into and associative array of key/value pairs. Consider this URI:

    + +index.php/user/search/name/joe/location/UK/gender/male + +

    Using this function you can turn the URI into an associative array with this prototype:

    + +[array]
    +(
    +    'name' => 'joe'
    +    'location' => 'UK'
    +    'gender' => 'male'
    +)
    + +

    The first parameter of the function lets you set an offset. By default it is set to 3 since your +URI will normally contain a controller/function in the first and second segments. Example:

    + + +$array = $this->uri->uri_to_assoc(3);
    +
    +echo $array['name']; +
    + + +

    The second parameter lets you set default key names, so that the array returned by the function will always contain expected indexes, even if missing from the URI. Example:

    + + +$default = array('name', 'gender', 'location', 'type', 'sort');
    +
    +$array = $this->uri->uri_to_assoc(3, $default);
    + +

    If the URI does not contain a value in your default, an array index will be set to that name, with a value of FALSE.

    + +

    Lastly, if a corresponding value is not found for a given key (if there is an odd number of URI segments) the value will be set to FALSE (boolean).

    + + +

    $this->uri->ruri_to_assoc(n)

    + +

    This function is identical to the previous one, except that it creates an associative array using the +re-routed URI in the event you are using CodeIgniter's URI Routing feature.

    + + +

    $this->uri->assoc_to_uri()

    + +

    Takes an associative array as input and generates a URI string from it. The array keys will be included in the string. Example:

    + +$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
    +
    +$str = $this->uri->assoc_to_uri($array);
    +
    +// Produces: product/shoes/size/large/color/red +
    + + +

    $this->uri->uri_string()

    + +

    Returns a string with the complete URI. For example, if this is your full URL:

    + +http://example.com/index.php/news/local/345 + +

    The function would return this:

    + +news/local/345 + + +

    $this->uri->ruri_string()

    + +

    This function is identical to the previous one, except that it returns the +re-routed URI in the event you are using CodeIgniter's URI Routing feature.

    + + + +

    $this->uri->total_segments()

    + +

    Returns the total number of segments.

    + + +

    $this->uri->total_rsegments()

    + +

    This function is identical to the previous one, except that it returns the total number of segments in your +re-routed URI in the event you are using CodeIgniter's URI Routing feature.

    + + + +

    $this->uri->segment_array()

    + +

    Returns an array containing the URI segments. For example:

    + + +$segs = $this->uri->segment_array();
    +
    +foreach ($segs as $segment)
    +{
    +    echo $segment;
    +    echo '<br />';
    +}
    + +

    $this->uri->rsegment_array()

    + +

    This function is identical to the previous one, except that it returns the array of segments in your +re-routed URI in the event you are using CodeIgniter's URI Routing feature.

    + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/user_agent.html b/api/user_guide/libraries/user_agent.html new file mode 100644 index 0000000..c3ff470 --- /dev/null +++ b/api/user_guide/libraries/user_agent.html @@ -0,0 +1,226 @@ + + + + + +User Agent Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    User Agent Class

    + +

    The User Agent Class provides functions that help identify information about the browser, mobile device, or robot visiting your site. +In addition you can get referrer information as well as language and supported character-set information.

    + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the User Agent class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('user_agent'); +

    Once loaded, the object will be available using: $this->agent

    + +

    User Agent Definitions

    + +

    The user agent name definitions are located in a config file located at: application/config/user_agents.php. You may add items to the +various user agent arrays if needed.

    + +

    Example

    + +

    When the User Agent class is initialized it will attempt to determine whether the user agent browsing your site is +a web browser, a mobile device, or a robot. It will also gather the platform information if it is available.

    + + + +$this->load->library('user_agent');
    +
    +if ($this->agent->is_browser())
    +{
    +    $agent = $this->agent->browser().' '.$this->agent->version();
    +}
    +elseif ($this->agent->is_robot())
    +{
    +    $agent = $this->agent->robot();
    +}
    +elseif ($this->agent->is_mobile())
    +{
    +    $agent = $this->agent->mobile();
    +}
    +else
    +{
    +    $agent = 'Unidentified User Agent';
    +}
    +
    +echo $agent;
    +
    +echo $this->agent->platform(); // Platform info (Windows, Linux, Mac, etc.) +
    + + +

    Function Reference

    + + +

    $this->agent->is_browser()

    +

    Returns TRUE/FALSE (boolean) if the user agent is a known web browser.

    + + if ($this->agent->is_browser('Safari'))
    +{
    +    echo 'You are using Safari.';
    +}
    +else if ($this->agent->is_browser())
    +{
    +    echo 'You are using a browser.';
    +}
    + +

    Note:  The string "Safari" in this example is an array key in the list of browser definitions. +You can find this list in application/config/user_agents.php if you want to add new browsers or change the stings.

    + +

    $this->agent->is_mobile()

    +

    Returns TRUE/FALSE (boolean) if the user agent is a known mobile device.

    + + if ($this->agent->is_mobile('iphone'))
    +{
    +    $this->load->view('iphone/home');
    +}
    +else if ($this->agent->is_mobile())
    +{
    +    $this->load->view('mobile/home');
    +}
    +else
    +{
    +    $this->load->view('web/home');
    +}
    + +

    $this->agent->is_robot()

    +

    Returns TRUE/FALSE (boolean) if the user agent is a known robot.

    + +

    Note:  The user agent library only contains the most common robot +definitions. It is not a complete list of bots. There are hundreds of them so searching for each one would not be +very efficient. If you find that some bots that commonly visit your site are missing from the list you can add them to your +application/config/user_agents.php file.

    + +

    $this->agent->is_referral()

    +

    Returns TRUE/FALSE (boolean) if the user agent was referred from another site.

    + + +

    $this->agent->browser()

    +

    Returns a string containing the name of the web browser viewing your site.

    + +

    $this->agent->version()

    +

    Returns a string containing the version number of the web browser viewing your site.

    + +

    $this->agent->mobile()

    +

    Returns a string containing the name of the mobile device viewing your site.

    + +

    $this->agent->robot()

    +

    Returns a string containing the name of the robot viewing your site.

    + +

    $this->agent->platform()

    +

    Returns a string containing the platform viewing your site (Linux, Windows, OS X, etc.).

    + +

    $this->agent->referrer()

    +

    The referrer, if the user agent was referred from another site. Typically you'll test for this as follows:

    + + if ($this->agent->is_referral())
    +{
    +    echo $this->agent->referrer();
    +}
    + + +

    $this->agent->agent_string()

    +

    Returns a string containing the full user agent string. Typically it will be something like this:

    + +Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.4) Gecko/20060613 Camino/1.0.2 + + +

    $this->agent->accept_lang()

    +

    Lets you determine if the user agent accepts a particular language. Example:

    + +if ($this->agent->accept_lang('en'))
    +{
    +    echo 'You accept English!';
    +}
    + +

    Note: This function is not typically very reliable +since some browsers do not provide language info, and even among those that do, it is not always accurate.

    + + + +

    $this->agent->accept_charset()

    +

    Lets you determine if the user agent accepts a particular character set. Example:

    + +if ($this->agent->accept_charset('utf-8'))
    +{
    +    echo 'You browser supports UTF-8!';
    +}
    + +

    Note: This function is not typically very reliable +since some browsers do not provide character-set info, and even among those that do, it is not always accurate.

    + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/xmlrpc.html b/api/user_guide/libraries/xmlrpc.html new file mode 100644 index 0000000..139ba68 --- /dev/null +++ b/api/user_guide/libraries/xmlrpc.html @@ -0,0 +1,519 @@ + + + + + +XML-RPC and XML-RPC Server Classes : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    XML-RPC and XML-RPC Server Classes

    + + +

    CodeIgniter's XML-RPC classes permit you to send requests to another server, or set up +your own XML-RPC server to receive requests.

    + + +

    What is XML-RPC?

    + +

    Quite simply it is a way for two computers to communicate over the internet using XML. +One computer, which we will call the client, sends an XML-RPC request to +another computer, which we will call the server. Once the server receives and processes the request it +will send back a response to the client.

    + +

    For example, using the MetaWeblog API, an XML-RPC Client (usually a desktop publishing tool) will +send a request to an XML-RPC Server running on your site. This request might be a new weblog entry +being sent for publication, or it could be a request for an existing entry for editing. + +When the XML-RPC Server receives this request it will examine it to determine which class/method should be called to process the request. +Once processed, the server will then send back a response message.

    + +

    For detailed specifications, you can visit the XML-RPC site.

    + +

    Initializing the Class

    + +

    Like most other classes in CodeIgniter, the XML-RPC and XML-RPCS classes are initialized in your controller using the $this->load->library function:

    + +

    To load the XML-RPC class you will use:

    +$this->load->library('xmlrpc'); +

    Once loaded, the xml-rpc library object will be available using: $this->xmlrpc

    + +

    To load the XML-RPC Server class you will use:

    + +$this->load->library('xmlrpc');
    +$this->load->library('xmlrpcs'); +
    +

    Once loaded, the xml-rpcs library object will be available using: $this->xmlrpcs

    + +

    Note:  When using the XML-RPC Server class you must load BOTH the XML-RPC class and the XML-RPC Server class.

    + + + +

    Sending XML-RPC Requests

    + +

    To send a request to an XML-RPC server you must specify the following information:

    + +
      +
    • The URL of the server
    • +
    • The method on the server you wish to call
    • +
    • The request data (explained below).
    • +
    + +

    Here is a basic example that sends a simple Weblogs.com ping to the Ping-o-Matic

    + + +$this->load->library('xmlrpc');
    +
    +$this->xmlrpc->server('http://rpc.pingomatic.com/', 80);
    +$this->xmlrpc->method('weblogUpdates.ping');
    + +
    +$request = array('My Photoblog', 'http://www.my-site.com/photoblog/');
    +$this->xmlrpc->request($request);
    +
    +if ( ! $this->xmlrpc->send_request())
    +{
    +    echo $this->xmlrpc->display_error();
    +}
    + +

    Explanation

    + +

    The above code initializes the XML-RPC class, sets the server URL and method to be called (weblogUpdates.ping). The +request (in this case, the title and URL of your site) is placed into an array for transportation, and +compiled using the request() function. +Lastly, the full request is sent. If the send_request() method returns false we will display the error message +sent back from the XML-RPC Server.

    + +

    Anatomy of a Request

    + +

    An XML-RPC request is simply the data you are sending to the XML-RPC server. Each piece of data in a request +is referred to as a request parameter. The above example has two parameters: +The URL and title of your site. When the XML-RPC server receives your request, it will look for parameters it requires.

    + +

    Request parameters must be placed into an array for transportation, and each parameter can be one +of seven data types (strings, numbers, dates, etc.). If your parameters are something other than strings +you will have to include the data type in the request array.

    + +

    Here is an example of a simple array with three parameters:

    + +$request = array('John', 'Doe', 'www.some-site.com');
    +$this->xmlrpc->request($request);
    + +

    If you use data types other than strings, or if you have several different data types, you will place +each parameter into its own array, with the data type in the second position:

    + + +$request = array (
    +                   array('John', 'string'),
    +                   array('Doe', 'string'),
    +                   array(FALSE, 'boolean'),
    +                   array(12345, 'int')
    +                 ); +
    +$this->xmlrpc->request($request);
    + +The Data Types section below has a full list of data types. + + + +

    Creating an XML-RPC Server

    + +

    An XML-RPC Server acts as a traffic cop of sorts, waiting for incoming requests and redirecting them to the +appropriate functions for processing.

    + +

    To create your own XML-RPC server involves initializing the XML-RPC Server class in your controller where you expect the incoming +request to appear, then setting up an array with mapping instructions so that incoming requests can be sent to the appropriate +class and method for processing.

    + +

    Here is an example to illustrate:

    + + +$this->load->library('xmlrpc');
    +$this->load->library('xmlrpcs');
    +
    +$config['functions']['new_post'] = array('function' => 'My_blog.new_entry'),
    +$config['functions']['update_post'] = array('function' => 'My_blog.update_entry');
    +$config['object'] = $this;
    +
    +$this->xmlrpcs->initialize($config);
    +$this->xmlrpcs->serve();
    + +

    The above example contains an array specifying two method requests that the Server allows. +The allowed methods are on the left side of the array. When either of those are received, they will be mapped to the class and method on the right.

    + +

    The 'object' key is a special key that you pass an instantiated class object with, which is necessary when the method you are mapping to is not + part of the CodeIgniter super object.

    + +

    In other words, if an XML-RPC Client sends a request for the new_post method, your +server will load the My_blog class and call the new_entry function. +If the request is for the update_post method, your +server will load the My_blog class and call the update_entry function.

    + +

    The function names in the above example are arbitrary. You'll decide what they should be called on your server, +or if you are using standardized APIs, like the Blogger or MetaWeblog API, you'll use their function names.

    + +

    There are two additional configuration keys you may make use of when initializing the server class: debug can be set to TRUE in order to enable debugging, and xss_clean may be set to FALSE to prevent sending data through the Security library's xss_clean function. + +

    Processing Server Requests

    + +

    When the XML-RPC Server receives a request and loads the class/method for processing, it will pass +an object to that method containing the data sent by the client.

    + +

    Using the above example, if the new_post method is requested, the server will expect a class +to exist with this prototype:

    + +class My_blog extends CI_Controller {
    +
    +    function new_post($request)
    +    {
    +
    +    }
    +} +
    + +

    The $request variable is an object compiled by the Server, which contains the data sent by the XML-RPC Client. +Using this object you will have access to the request parameters enabling you to process the request. When +you are done you will send a Response back to the Client.

    + +

    Below is a real-world example, using the Blogger API. One of the methods in the Blogger API is getUserInfo(). +Using this method, an XML-RPC Client can send the Server a username and password, in return the Server sends +back information about that particular user (nickname, user ID, email address, etc.). Here is how the processing +function might look:

    + + +class My_blog extends CI_Controller {
    +
    +    function getUserInfo($request)
    +    {
    + +        $username = 'smitty';
    +        $password = 'secretsmittypass';

    + +        $this->load->library('xmlrpc');
    +    
    +        $parameters = $request->output_parameters();
    +    
    +        if ($parameters['1'] != $username AND $parameters['2'] != $password)
    +        {
    +            return $this->xmlrpc->send_error_message('100', 'Invalid Access');
    +        }
    +    
    +        $response = array(array('nickname'  => array('Smitty','string'),
    +                                'userid'    => array('99','string'),
    +                                'url'       => array('http://yoursite.com','string'),
    +                                'email'     => array('jsmith@yoursite.com','string'),
    +                                'lastname'  => array('Smith','string'),
    +                                'firstname' => array('John','string')
    +                                ),
    +                         'struct');
    +
    +        return $this->xmlrpc->send_response($response);
    +    }
    +} +
    + +

    Notes:

    +

    The output_parameters() function retrieves an indexed array corresponding to the request parameters sent by the client. +In the above example, the output parameters will be the username and password.

    + +

    If the username and password sent by the client were not valid, and error message is returned using send_error_message().

    + +

    If the operation was successful, the client will be sent back a response array containing the user's info.

    + + +

    Formatting a Response

    + +

    Similar to Requests, Responses must be formatted as an array. However, unlike requests, a response is an array +that contains a single item. This item can be an array with several additional arrays, but there +can be only one primary array index. In other words, the basic prototype is this:

    + +$response = array('Response data', 'array'); + +

    Responses, however, usually contain multiple pieces of information. In order to accomplish this we must put the response into its own +array so that the primary array continues to contain a single piece of data. Here's an example showing how this might be accomplished:

    + + +$response = array (
    +                   array(
    +                         'first_name' => array('John', 'string'),
    +                         'last_name' => array('Doe', 'string'),
    +                         'member_id' => array(123435, 'int'),
    +                         'todo_list' => array(array('clean house', 'call mom', 'water plants'), 'array'),
    +                        ),
    +                 'struct'
    +                 ); +
    + +

    Notice that the above array is formatted as a struct. This is the most common data type for responses.

    + +

    As with Requests, a response can be one of the seven data types listed in the Data Types section.

    + + +

    Sending an Error Response

    + +

    If you need to send the client an error response you will use the following:

    + +return $this->xmlrpc->send_error_message('123', 'Requested data not available'); + +

    The first parameter is the error number while the second parameter is the error message.

    + + + + + + +

    Creating Your Own Client and Server

    + +

    To help you understand everything we've covered thus far, let's create a couple controllers that act as +XML-RPC Client and Server. You'll use the Client to send a request to the Server and receive a response.

    + +

    The Client

    + +

    Using a text editor, create a controller called xmlrpc_client.php. +In it, place this code and save it to your applications/controllers/ folder:

    + + + +

    Note: In the above code we are using a "url helper". You can find more information in the Helpers Functions page.

    + +

    The Server

    + +

    Using a text editor, create a controller called xmlrpc_server.php. +In it, place this code and save it to your applications/controllers/ folder:

    + + + +

    Try it!

    + +

    Now visit the your site using a URL similar to this:

    +example.com/index.php/xmlrpc_client/ + +

    You should now see the message you sent to the server, and its response back to you.

    + +

    The client you created sends a message ("How's is going?") to the server, along with a request for the "Greetings" method. +The Server receives the request and maps it to the "process" function, where a response is sent back.

    + +

    Using Associative Arrays In a Request Parameter

    + +

    If you wish to use an associative array in your method parameters you will need to use a struct datatype:

    + +$request = array(
    +                  array(
    +                        // Param 0
    +                        array(
    +                              'name'=>'John'
    +                              ),
    +                              'struct'
    +                        ),
    +                        array(
    +                              // Param 1
    +                              array(
    +                                    'size'=>'large',
    +                                    'shape'=>'round'
    +                                    ),
    +                              'struct'
    +                        )
    +                  );
    + $this->xmlrpc->request($request);
    + +

    You can retrieve the associative array when processing the request in the Server.

    + +$parameters = $request->output_parameters();
    + $name = $parameters['0']['name'];
    + $size = $parameters['1']['size'];
    + $size = $parameters['1']['shape'];
    + +

    XML-RPC Function Reference

    + +

    $this->xmlrpc->server()

    +

    Sets the URL and port number of the server to which a request is to be sent:

    +$this->xmlrpc->server('http://www.sometimes.com/pings.php', 80); + +

    $this->xmlrpc->timeout()

    +

    Set a time out period (in seconds) after which the request will be canceled:

    +$this->xmlrpc->timeout(6); + +

    $this->xmlrpc->method()

    +

    Sets the method that will be requested from the XML-RPC server:

    +$this->xmlrpc->method('method'); + +

    Where method is the name of the method.

    + +

    $this->xmlrpc->request()

    +

    Takes an array of data and builds request to be sent to XML-RPC server:

    +$request = array(array('My Photoblog', 'string'), 'http://www.yoursite.com/photoblog/');
    +$this->xmlrpc->request($request);
    + +

    $this->xmlrpc->send_request()

    +

    The request sending function. Returns boolean TRUE or FALSE based on success for failure, enabling it to be used conditionally.

    + +

    $this->xmlrpc->set_debug(TRUE);

    +

    Enables debugging, which will display a variety of information and error data helpful during development.

    + + +

    $this->xmlrpc->display_error()

    +

    Returns an error message as a string if your request failed for some reason.

    +echo $this->xmlrpc->display_error(); + +

    $this->xmlrpc->display_response()

    +

    Returns the response from the remote server once request is received. The response will typically be an associative array.

    +$this->xmlrpc->display_response(); + +

    $this->xmlrpc->send_error_message()

    +

    This function lets you send an error message from your server to the client. First parameter is the error number while the second parameter +is the error message.

    +return $this->xmlrpc->send_error_message('123', 'Requested data not available'); + +

    $this->xmlrpc->send_response()

    +

    Lets you send the response from your server to the client. An array of valid data values must be sent with this method.

    +$response = array(
    +                 array(
    +                        'flerror' => array(FALSE, 'boolean'),
    +                        'message' => "Thanks for the ping!"
    +                     )
    +                 'struct');
    +return $this->xmlrpc->send_response($response);
    + + + +

    Data Types

    + +

    According to the XML-RPC spec there are seven types +of values that you can send via XML-RPC:

    + +
      +
    • int or i4
    • +
    • boolean
    • +
    • string
    • +
    • double
    • +
    • dateTime.iso8601
    • +
    • base64
    • +
    • struct (contains array of values)
    • +
    • array (contains array of values)
    • +
    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/libraries/zip.html b/api/user_guide/libraries/zip.html new file mode 100644 index 0000000..0a03653 --- /dev/null +++ b/api/user_guide/libraries/zip.html @@ -0,0 +1,288 @@ + + + + + +Zip Encoding Class : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Zip Encoding Class

    +

    CodeIgniter's Zip Encoding Class classes permit you to create Zip archives. Archives can be downloaded to your +desktop or saved to a directory.

    + + +

    Initializing the Class

    +

    Like most other classes in CodeIgniter, the Zip class is initialized in your controller using the $this->load->library function:

    + +$this->load->library('zip'); +

    Once loaded, the Zip library object will be available using: $this->zip

    + + +

    Usage Example

    + +

    This example demonstrates how to compress a file, save it to a folder on your server, and download it to your desktop.

    + + +$name = 'mydata1.txt';
    +$data = 'A Data String!';
    +
    +$this->zip->add_data($name, $data);
    +
    +// Write the zip file to a folder on your server. Name it "my_backup.zip"
    +$this->zip->archive('/path/to/directory/my_backup.zip'); +

    + // Download the file to your desktop. Name it "my_backup.zip"
    +$this->zip->download('my_backup.zip'); +
    + +

    Function Reference

    + +

    $this->zip->add_data()

    + +

    Permits you to add data to the Zip archive. The first parameter must contain the name you would like +given to the file, the second parameter must contain the file data as a string:

    + + +$name = 'my_bio.txt';
    +$data = 'I was born in an elevator...';
    +
    +$this->zip->add_data($name, $data); +
    + +

    You are allowed multiple calls to this function in order to +add several files to your archive. Example:

    + + +$name = 'mydata1.txt';
    +$data = 'A Data String!';
    +$this->zip->add_data($name, $data);
    +
    +$name = 'mydata2.txt';
    +$data = 'Another Data String!';
    +$this->zip->add_data($name, $data);
    +
    + +

    Or you can pass multiple files using an array:

    + + +$data = array(
    +                'mydata1.txt' => 'A Data String!',
    +                'mydata2.txt' => 'Another Data String!'
    +            );
    +
    +$this->zip->add_data($data);
    +
    +$this->zip->download('my_backup.zip'); +
    + +

    If you would like your compressed data organized into sub-folders, include the path as part of the filename:

    + + +$name = 'personal/my_bio.txt';
    +$data = 'I was born in an elevator...';
    +
    +$this->zip->add_data($name, $data); +
    + +

    The above example will place my_bio.txt inside a folder called personal.

    + + +

    $this->zip->add_dir()

    + +

    Permits you to add a directory. Usually this function is unnecessary since you can place your data into folders when +using $this->zip->add_data(), but if you would like to create an empty folder you can do so. Example:

    + +$this->zip->add_dir('myfolder'); // Creates a folder called "myfolder" + + + +

    $this->zip->read_file()

    + +

    Permits you to compress a file that already exists somewhere on your server. Supply a file path and the zip class will +read it and add it to the archive:

    + + +$path = '/path/to/photo.jpg';

    +$this->zip->read_file($path); +

    + // Download the file to your desktop. Name it "my_backup.zip"
    +$this->zip->download('my_backup.zip'); +
    + +

    If you would like the Zip archive to maintain the directory structure of the file in it, pass TRUE (boolean) in the +second parameter. Example:

    + + + +$path = '/path/to/photo.jpg';

    +$this->zip->read_file($path, TRUE); +

    + // Download the file to your desktop. Name it "my_backup.zip"
    +$this->zip->download('my_backup.zip'); +
    + +

    In the above example, photo.jpg will be placed inside two folders: path/to/

    + + + +

    $this->zip->read_dir()

    + +

    Permits you to compress a folder (and its contents) that already exists somewhere on your server. Supply a file path to the +directory and the zip class will recursively read it and recreate it as a Zip archive. All files contained within the +supplied path will be encoded, as will any sub-folders contained within it. Example:

    + + +$path = '/path/to/your/directory/';

    +$this->zip->read_dir($path); +

    + // Download the file to your desktop. Name it "my_backup.zip"
    +$this->zip->download('my_backup.zip'); +
    + +

    By default the Zip archive will place all directories listed in the first parameter inside the zip. If you want the tree preceding the target folder to be ignored +you can pass FALSE (boolean) in the second parameter. Example:

    + + +$path = '/path/to/your/directory/';

    +$this->zip->read_dir($path, FALSE); +
    + +

    This will create a ZIP with the folder "directory" inside, then all sub-folders stored correctly inside that, but will not include the folders /path/to/your.

    + + + + +

    $this->zip->archive()

    + +

    Writes the Zip-encoded file to a directory on your server. Submit a valid server path ending in the file name. Make sure the +directory is writable (666 or 777 is usually OK). Example:

    + +$this->zip->archive('/path/to/folder/myarchive.zip'); // Creates a file named myarchive.zip + + +

    $this->zip->download()

    + +

    Causes the Zip file to be downloaded from your server. The function must be passed the name you would like the zip file called. +Example:

    + +$this->zip->download('latest_stuff.zip'); // File will be named "latest_stuff.zip" + +

    Note:  Do not display any data in the controller in which you call this function since it sends various server headers +that cause the download to happen and the file to be treated as binary.

    + + +

    $this->zip->get_zip()

    + +

    Returns the Zip-compressed file data. Generally you will not need this function unless you want to do something unique with the data. +Example:

    + + +$name = 'my_bio.txt';
    +$data = 'I was born in an elevator...';
    +
    +$this->zip->add_data($name, $data);

    + +$zip_file = $this->zip->get_zip(); +
    + + +

    $this->zip->clear_data()

    + +

    The Zip class caches your zip data so that it doesn't need to recompile the Zip archive for each function you use above. +If, however, you need to create multiple Zips, each with different data, you can clear the cache between calls. Example:

    + + +$name = 'my_bio.txt';
    +$data = 'I was born in an elevator...';
    +
    +$this->zip->add_data($name, $data);
    +$zip_file = $this->zip->get_zip();
    +
    +$this->zip->clear_data(); +

    + +$name = 'photo.jpg';
    +$this->zip->read_file("/path/to/photo.jpg"); // Read the file's contents
    +

    +$this->zip->download('myphotos.zip'); +
    + + + + + + + + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/license.html b/api/user_guide/license.html new file mode 100644 index 0000000..c990aa2 --- /dev/null +++ b/api/user_guide/license.html @@ -0,0 +1,107 @@ + + + + + +CodeIgniter License Agreement : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + + +
    + + + + +
    + + + +
    + +

    CodeIgniter License Agreement

    + +

    Copyright (c) 2008 - 2011, EllisLab, Inc.
    +All rights reserved.

    + +

    This license is a legal agreement between you and EllisLab Inc. for the use of CodeIgniter Software (the "Software"). By obtaining the Software you agree to comply with the terms and conditions of this license.

    + +

    Permitted Use

    +

    You are permitted to use, copy, modify, and distribute the Software and its documentation, with or without modification, for any purpose, provided that the following conditions are met:

    + +
      +
    1. A copy of this license agreement must be included with the distribution.
    2. +
    3. Redistributions of source code must retain the above copyright notice in all source code files.
    4. +
    5. Redistributions in binary form must reproduce the above copyright notice in the documentation and/or other materials provided with the distribution.
    6. +
    7. Any files that have been modified must carry notices stating the nature of the change and the names of those who changed them.
    8. +
    9. Products derived from the Software must include an acknowledgment that they are derived from CodeIgniter in their documentation and/or other materials provided with the distribution.
    10. +
    11. Products derived from the Software may not be called "CodeIgniter", nor may "CodeIgniter" appear in their name, without prior written permission from EllisLab, Inc.
    12. +
    + +

    Indemnity

    +

    You agree to indemnify and hold harmless the authors of the Software and any contributors for any direct, indirect, incidental, or consequential third-party claims, actions or suits, as well as any related expenses, liabilities, damages, settlements or fees arising from your use or misuse of the Software, or a violation of any terms of this license.

    + +

    Disclaimer of Warranty

    +

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF QUALITY, PERFORMANCE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

    + +

    Limitations of Liability

    +

    YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USE OF THE SOFTWARE. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE LIABLE FOR CLAIMS, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USE AND ASSUME ALL RISKS ASSOCIATED WITH ITS USE, INCLUDING BUT NOT LIMITED TO THE RISKS OF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF DATA OR SOFTWARE PROGRAMS, OR UNAVAILABILITY OR INTERRUPTION OF OPERATIONS.

    + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/nav/hacks.txt b/api/user_guide/nav/hacks.txt new file mode 100644 index 0000000..8c17f00 --- /dev/null +++ b/api/user_guide/nav/hacks.txt @@ -0,0 +1,10 @@ +I did the following hack in moo.fx.js: + +At line 79 in the toggle: function() function, I added: + +document.getElementById('nav').style.display = 'block'; + +-- Rick Ellis + + +Also removed fx.Opacity and fx.Height from moo.fx.js -- Pascal \ No newline at end of file diff --git a/api/user_guide/nav/moo.fx.js b/api/user_guide/nav/moo.fx.js new file mode 100644 index 0000000..256371d --- /dev/null +++ b/api/user_guide/nav/moo.fx.js @@ -0,0 +1,83 @@ +/* +moo.fx, simple effects library built with prototype.js (http://prototype.conio.net). +by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE. +for more info (http://moofx.mad4milk.net). +10/24/2005 +v(1.0.2) +*/ + +//base +var fx = new Object(); +fx.Base = function(){}; +fx.Base.prototype = { + setOptions: function(options) { + this.options = { + duration: 500, + onComplete: '' + } + Object.extend(this.options, options || {}); + }, + + go: function() { + this.duration = this.options.duration; + this.startTime = (new Date).getTime(); + this.timer = setInterval (this.step.bind(this), 13); + }, + + step: function() { + var time = (new Date).getTime(); + var Tpos = (time - this.startTime) / (this.duration); + if (time >= this.duration+this.startTime) { + this.now = this.to; + clearInterval (this.timer); + this.timer = null; + if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10); + } + else { + this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from; + //this time-position, sinoidal transition thing is from script.aculo.us + } + this.increase(); + }, + + custom: function(from, to) { + if (this.timer != null) return; + this.from = from; + this.to = to; + this.go(); + }, + + hide: function() { + this.now = 0; + this.increase(); + }, + + clearTimer: function() { + clearInterval(this.timer); + this.timer = null; + } +} + +//stretchers +fx.Layout = Class.create(); +fx.Layout.prototype = Object.extend(new fx.Base(), { + initialize: function(el, options) { + this.el = $(el); + this.el.style.overflow = "hidden"; + this.el.iniWidth = this.el.offsetWidth; + this.el.iniHeight = this.el.offsetHeight; + this.setOptions(options); + } +}); + +fx.Height = Class.create(); +Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), { + increase: function() { + this.el.style.height = this.now + "px"; + }, + + toggle: function() { + if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0); + else this.custom(0, this.el.scrollHeight); + } +}); diff --git a/api/user_guide/nav/nav.js b/api/user_guide/nav/nav.js new file mode 100644 index 0000000..b9b6e09 --- /dev/null +++ b/api/user_guide/nav/nav.js @@ -0,0 +1,156 @@ +function create_menu(basepath) +{ + var base = (basepath == 'null') ? '' : basepath; + + document.write( + '' + + '
    ' + + + '' + + + '

    Basic Info

    ' + + '' + + + '

    Installation

    ' + + '' + + + '

    Introduction

    ' + + '' + + + '

    Tutorial

    ' + + '' + + + '
    ' + + + '

    General Topics

    ' + + '' + + + '

    Additional Resources

    ' + + '' + + + '
    ' + + + '

    Class Reference

    ' + + '' + + + '
    ' + + + '

    Driver Reference

    ' + + '' + + + '

    Helper Reference

    ' + + '' + + + '
    '); +} \ No newline at end of file diff --git a/api/user_guide/nav/prototype.lite.js b/api/user_guide/nav/prototype.lite.js new file mode 100644 index 0000000..e6c3622 --- /dev/null +++ b/api/user_guide/nav/prototype.lite.js @@ -0,0 +1,127 @@ +/* Prototype JavaScript framework + * (c) 2005 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * + * For details, see the Prototype web site: http://prototype.conio.net/ + * +/*--------------------------------------------------------------------------*/ + + +//note: this is a stripped down version of prototype, to be used with moo.fx by mad4milk (http://moofx.mad4milk.net). + +var Class = { + create: function() { + return function() { + this.initialize.apply(this, arguments); + } + } +} + +Object.extend = function(destination, source) { + for (property in source) { + destination[property] = source[property]; + } + return destination; +} + +Function.prototype.bind = function(object) { + var __method = this; + return function() { + return __method.apply(object, arguments); + } +} + +function $() { + var elements = new Array(); + + for (var i = 0; i < arguments.length; i++) { + var element = arguments[i]; + if (typeof element == 'string') + element = document.getElementById(element); + + if (arguments.length == 1) + return element; + + elements.push(element); + } + + return elements; +} + +//------------------------- + +document.getElementsByClassName = function(className) { + var children = document.getElementsByTagName('*') || document.all; + var elements = new Array(); + + for (var i = 0; i < children.length; i++) { + var child = children[i]; + var classNames = child.className.split(' '); + for (var j = 0; j < classNames.length; j++) { + if (classNames[j] == className) { + elements.push(child); + break; + } + } + } + + return elements; +} + +//------------------------- + +if (!window.Element) { + var Element = new Object(); +} + +Object.extend(Element, { + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + }, + + hasClassName: function(element, className) { + element = $(element); + if (!element) + return; + var a = element.className.split(' '); + for (var i = 0; i < a.length; i++) { + if (a[i] == className) + return true; + } + return false; + }, + + addClassName: function(element, className) { + element = $(element); + Element.removeClassName(element, className); + element.className += ' ' + className; + }, + + removeClassName: function(element, className) { + element = $(element); + if (!element) + return; + var newClassName = ''; + var a = element.className.split(' '); + for (var i = 0; i < a.length; i++) { + if (a[i] != className) { + if (i > 0) + newClassName += ' '; + newClassName += a[i]; + } + } + element.className = newClassName; + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + for (var i = 0; i < element.childNodes.length; i++) { + var node = element.childNodes[i]; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + Element.remove(node); + } + } +}); \ No newline at end of file diff --git a/api/user_guide/nav/user_guide_menu.js b/api/user_guide/nav/user_guide_menu.js new file mode 100644 index 0000000..ce5d077 --- /dev/null +++ b/api/user_guide/nav/user_guide_menu.js @@ -0,0 +1,4 @@ +window.onload = function() { + myHeight = new fx.Height('nav', {duration: 400}); + myHeight.hide(); +} \ No newline at end of file diff --git a/api/user_guide/overview/appflow.html b/api/user_guide/overview/appflow.html new file mode 100644 index 0000000..c2004c7 --- /dev/null +++ b/api/user_guide/overview/appflow.html @@ -0,0 +1,95 @@ + + + + + +Application Flow Chart : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Application Flow Chart

    + +

    The following graphic illustrates how data flows throughout the system:

    + +
    CodeIgniter application flow
    + + +
      +
    1. The index.php serves as the front controller, initializing the base resources needed to run CodeIgniter.
    2. +
    3. The Router examines the HTTP request to determine what should be done with it.
    4. +
    5. If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
    6. +
    7. Security. Before the application controller is loaded, the HTTP request and any user submitted data is filtered for security.
    8. +
    9. The Controller loads the model, core libraries, helpers, and any other resources needed to process the specific request.
    10. +
    11. The finalized View is rendered then sent to the web browser to be seen. If caching is enabled, the view is cached first so +that on subsequent requests it can be served.
    12. +
    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/at_a_glance.html b/api/user_guide/overview/at_a_glance.html new file mode 100644 index 0000000..d51d42c --- /dev/null +++ b/api/user_guide/overview/at_a_glance.html @@ -0,0 +1,162 @@ + + + + + +CodeIgniter at a Glance : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    CodeIgniter at a Glance

    + + +

    CodeIgniter is an Application Framework

    + +

    CodeIgniter is a toolkit for people who build web applications using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code +from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and +logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by +minimizing the amount of code needed for a given task.

    + +

    CodeIgniter is Free

    +

    CodeIgniter is licensed under an Apache/BSD-style open source license so you can use it however you please. +For more information please read the license agreement.

    + +

    CodeIgniter is Light Weight

    +

    Truly light weight. The core system requires only a few very small libraries. This is in stark contrast to many frameworks that require significantly more resources. +Additional libraries are loaded dynamically upon request, based on your needs for a given process, so the base system +is very lean and quite fast. +

    + +

    CodeIgniter is Fast

    +

    Really fast. We challenge you to find a framework that has better performance than CodeIgniter.

    + + +

    CodeIgniter Uses M-V-C

    +

    CodeIgniter uses the Model-View-Controller approach, which allows great separation between logic and presentation. +This is particularly good for projects in which designers are working with your template files, as the code these file contain will be minimized. We describe MVC in more detail on its own page.

    + +

    CodeIgniter Generates Clean URLs

    +

    The URLs generated by CodeIgniter are clean and search-engine friendly. Rather than using the standard "query string" +approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based approach:

    + +example.com/news/article/345 + +

    Note: By default the index.php file is included in the URL but it can be removed using a simple .htaccess file.

    + +

    CodeIgniter Packs a Punch

    +

    CodeIgniter comes with full-range of libraries that enable the most commonly needed web development tasks, +like accessing a database, sending email, validating form data, maintaining sessions, manipulating images, working with XML-RPC data and +much more.

    + +

    CodeIgniter is Extensible

    +

    The system can be easily extended through the use of your own libraries, helpers, or through class extensions or system hooks.

    + + +

    CodeIgniter Does Not Require a Template Engine

    +

    Although CodeIgniter does come with a simple template parser that can be optionally used, it does not force you to use one. + +Template engines simply can not match the performance of native PHP, and the syntax that must be learned to use a template +engine is usually only marginally easier than learning the basics of PHP. Consider this block of PHP code:

    + +<ul>
    +
    +<?php foreach ($addressbook as $name):?>
    +
    +<li><?=$name?></li>
    +
    +<?php endforeach; ?>
    +
    +</ul>
    + +

    Contrast this with the pseudo-code used by a template engine:

    + +<ul>
    +
    +{foreach from=$addressbook item="name"}
    +
    +<li>{$name}</li>
    +
    +{/foreach}
    +
    +</ul>
    + +

    Yes, the template engine example is a bit cleaner, but it comes at the price of performance, as the pseudo-code must be converted +back into PHP to run. Since one of our goals is maximum performance, we opted to not require the use of a template engine.

    + + +

    CodeIgniter is Thoroughly Documented

    +

    Programmers love to code and hate to write documentation. We're no different, of course, but +since documentation is as important as the code itself, +we are committed to doing it. Our source code is extremely clean and well commented as well.

    + + +

    CodeIgniter has a Friendly Community of Users

    + +

    Our growing community of users can be seen actively participating in our Community Forums.

    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/cheatsheets.html b/api/user_guide/overview/cheatsheets.html new file mode 100644 index 0000000..7284cd7 --- /dev/null +++ b/api/user_guide/overview/cheatsheets.html @@ -0,0 +1,83 @@ + + + + + +CodeIgniter Cheatsheets : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    CodeIgniter Cheatsheets

    + +

    Library Reference

    + +
    CodeIgniter Library Reference
    + +

    Helpers Reference

    +
    CodeIgniter Library Reference
    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/features.html b/api/user_guide/overview/features.html new file mode 100644 index 0000000..aebafe6 --- /dev/null +++ b/api/user_guide/overview/features.html @@ -0,0 +1,118 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    CodeIgniter Features

    + +

    Features in and of themselves are a very poor way to judge an application since they tell you nothing +about the user experience, or how intuitively or intelligently it is designed. Features +don't reveal anything about the quality of the code, or the performance, or the attention to detail, or security practices. +The only way to really judge an app is to try it and get to know the code. Installing +CodeIgniter is child's play so we encourage you to do just that. In the mean time here's a list of CodeIgniter's main features.

    + +
      +
    • Model-View-Controller Based System
    • +
    • Extremely Light Weight
    • +
    • Full Featured database classes with support for several platforms.
    • +
    • Active Record Database Support
    • +
    • Form and Data Validation
    • +
    • Security and XSS Filtering
    • +
    • Session Management
    • +
    • Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more.
    • +
    • Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM
    • +
    • File Uploading Class
    • +
    • FTP Class
    • +
    • Localization
    • +
    • Pagination
    • +
    • Data Encryption
    • +
    • Benchmarking
    • +
    • Full Page Caching
    • +
    • Error Logging
    • +
    • Application Profiling
    • +
    • Calendaring Class
    • +
    • User Agent Class
    • +
    • Zip Encoding Class
    • +
    • Template Engine Class
    • +
    • Trackback Class
    • +
    • XML-RPC Library
    • +
    • Unit Testing Class
    • +
    • Search-engine Friendly URLs
    • +
    • Flexible URI Routing
    • +
    • Support for Hooks and Class Extensions
    • +
    • Large library of "helper" functions
    • +
    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/getting_started.html b/api/user_guide/overview/getting_started.html new file mode 100644 index 0000000..049d29c --- /dev/null +++ b/api/user_guide/overview/getting_started.html @@ -0,0 +1,92 @@ + + + + + +Getting Started With CodeIgniter : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    Getting Started With CodeIgniter

    + +

    Any software application requires some effort to learn. We've done our best to minimize the learning +curve while making the process as enjoyable as possible. +

    + +

    The first step is to install CodeIgniter, then read +all the topics in the Introduction section of the Table of Contents.

    + +

    Next, read each of the General Topics pages in order. +Each topic builds on the previous one, and includes code examples that you are encouraged to try.

    + +

    Once you understand the basics you'll be ready to explore the Class Reference and +Helper Reference pages to learn to utilize the native libraries and helper files.

    + +

    Feel free to take advantage of our Community Forums +if you have questions or problems, and +our Wiki to see code examples posted by other users.

    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/goals.html b/api/user_guide/overview/goals.html new file mode 100644 index 0000000..ec5a418 --- /dev/null +++ b/api/user_guide/overview/goals.html @@ -0,0 +1,98 @@ + + + + + +Design and Architectural Goals : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + + +

    Design and Architectural Goals

    + +

    Our goal for CodeIgniter is maximum performance, capability, and flexibility in the smallest, lightest possible package.

    + +

    To meet this goal we are committed to benchmarking, re-factoring, and simplifying at every step of the development process, +rejecting anything that doesn't further the stated objective.

    + +

    From a technical and architectural standpoint, CodeIgniter was created with the following objectives:

    + +
      +
    • Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested, rather than globally. No assumptions are made by the system regarding what may be needed beyond the minimal core resources, so the system is very light-weight by default. The events, as triggered by the HTTP request, and the controllers and views you design will determine what is invoked.
    • +
    • Loose Coupling. Coupling is the degree to which components of a system rely on each other. The less components depend on each other the more reusable and flexible the system becomes. Our goal was a very loosely coupled system.
    • +
    • Component Singularity. Singularity is the degree to which components have a narrowly focused purpose. In CodeIgniter, each class and its functions are highly autonomous in order to allow maximum usefulness.
    • +
    + +

    CodeIgniter is a dynamically instantiated, loosely coupled system with high component singularity. It strives for simplicity, flexibility, and high performance in a small footprint package.

    + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/index.html b/api/user_guide/overview/index.html new file mode 100644 index 0000000..1f38839 --- /dev/null +++ b/api/user_guide/overview/index.html @@ -0,0 +1,84 @@ + + + + + +CodeIgniter Overview : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + +

    CodeIgniter Overview

    + +

    The following pages describe the broad concepts behind CodeIgniter:

    + + + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/overview/mvc.html b/api/user_guide/overview/mvc.html new file mode 100644 index 0000000..1d98c2e --- /dev/null +++ b/api/user_guide/overview/mvc.html @@ -0,0 +1,100 @@ + + + + + +Model-View-Controller : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Model-View-Controller

    + +

    CodeIgniter is based on the Model-View-Controller development pattern. + +MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

    + +
      +
    • The Model represents your data structures. Typically your model classes will contain functions that help you +retrieve, insert, and update information in your database.
    • +
    • The View is the information that is being presented to a user. A View will normally be a web page, but +in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of "page".
    • +
    • The Controller serves as an intermediary between the Model, the View, +and any other resources needed to process the HTTP request and generate a web page.
    • + +
    + +

    CodeIgniter has a fairly loose approach to MVC since Models are not required. +If you don't need the added separation, or find that maintaining models requires more complexity than you +want, you can ignore them and build your application minimally using Controllers and Views. CodeIgniter also +enables you to incorporate your own existing scripts, or even develop core libraries for the system, + enabling you to work in a way that makes the most sense to you.

    + + + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/toc.html b/api/user_guide/toc.html new file mode 100644 index 0000000..9c28da3 --- /dev/null +++ b/api/user_guide/toc.html @@ -0,0 +1,229 @@ + + + + + +Table of Contents : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + + +
    + + +
    + + +
    + + +

    Table of Contents

    + + + + + + + + +
    + +

    Basic Info

    + + +

    Installation

    + + +

    Introduction

    + + +

    Tutorial

    + + +
    + +

    General Topics

    + + +

    Additional Resources

    + + + +
    + +

    Class Reference

    + + + +
    + +

    Driver Reference

    + + +

    Helper Reference

    + + + + + +
    + +
    + + + + + + + + \ No newline at end of file diff --git a/api/user_guide/tutorial/conclusion.html b/api/user_guide/tutorial/conclusion.html new file mode 100644 index 0000000..a1c9c24 --- /dev/null +++ b/api/user_guide/tutorial/conclusion.html @@ -0,0 +1,91 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Tutorial - Conclusion

    + +

    This tutorial did not cover all of the things you might expect of a full-fledged content management system, but it introduced you to the more important topics of routing, writing controllers, and models. We hope this tutorial gave you an insight into some of CodeIgniter's basic design patterns, which you can expand upon.

    + +

    Now that you've completed this tutorial, we recommend you check out the rest of the documentation. CodeIgniter is often praised because of its comprehensive documentation. Use this to your advantage and read the "Introduction" and "General Topics" sections thoroughly. You should read the class and helper references when needed.

    + +

    Every intermediate PHP programmer should be able to get the hang of CodeIgniter within a few days.

    + +

    If you still have questions about the framework or your own CodeIgniter code, you can:

    + + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/tutorial/create_news_items.html b/api/user_guide/tutorial/create_news_items.html new file mode 100644 index 0000000..4db7fb8 --- /dev/null +++ b/api/user_guide/tutorial/create_news_items.html @@ -0,0 +1,179 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Tutorial - Create news items

    + +

    You now know how you can read data from a database using CodeIgnite, but you haven't written any information to the database yet. In this section you'll expand your news controller and model created earlier to include this functionality.

    + +

    Create a form

    + +

    To input data into the database you need to create a form where you can input the information to be stored. This means you'll be needing a form with two fields, one for the title and one for the text. You'll derive the slug from our title in the model. Create the new view at application/views/news/create.php.

    + + + +

    There are only two things here that probably look unfamiliar to you: the form_open() function and the validation_errors() function.

    + +

    The first function is provided by the form helper and renders the form element and adds extra functionality, like adding a hidden CSFR prevention field. The latter is used to report errors related to form validation.

    + +

    Go back to your news controller. You're going to do two things here, check whether the form was submitted and whether the submitted data passed the validation rules. You'll use the form validation library to do this.

    + +
    +public function create()
    +{
    +	$this->load->helper('form');
    +	$this->load->library('form_validation');
    +
    +	$data['title'] = 'Create a news item';
    +
    +	$this->form_validation->set_rules('title', 'Title', 'required');
    +	$this->form_validation->set_rules('text', 'text', 'required');
    +
    +	if ($this->form_validation->run() === FALSE)
    +	{
    +		$this->load->view('templates/header', $data);
    +		$this->load->view('news/create');
    +		$this->load->view('templates/footer');
    +
    +	}
    +	else
    +	{
    +		$this->news_model->set_news();
    +		$this->load->view('news/success');
    +	}
    +}
    +
    + +

    The code above adds a lot of functionality. The first few lines load the form helper and the form validation library. After that, rules for the form validation are set. The set_rules() method takes three arguments; the name of the input field, the name to be used in error messages, and the rule. In this case the title and text fields are required.

    + +

    CodeIgniter has a powerful form validation library as demonstrated above. You can read more about this library here.

    + +

    Continuing down, you can see a condition that checks whether the form validation ran successfully. If it did not, the form is displayed, if it was submitted and passed all the rules, the model is called. After this, a view is loaded to display a success message. Create a view at application/view/news/success.php and write a success message.

    + +

    Model

    + +

    The only thing that remains is writing a method that writes the data to the database. You'll use the Active Record class to insert the information and use the input library to get the posted data. Open up the model created earlier and add the following:

    + +
    +public function set_news()
    +{
    +	$this->load->helper('url');
    +
    +	$slug = url_title($this->input->post('title'), 'dash', TRUE);
    +
    +	$data = array(
    +		'title' => $this->input->post('title'),
    +		'slug' => $slug,
    +		'text' => $this->input->post('text')
    +	);
    +
    +	return $this->db->insert('news', $data);
    +}
    +
    + +

    This new method takes care of inserting the news item into the database. The third line contains a new function, url_title(). This function - provided by the URL helper - strips down the string you pass it, replacing all spaces by dashes (-) and makes sure everything is in lowercase characters. This leaves you with a nice slug, perfect for creating URIs.

    + +

    Let's continue with preparing the record that is going to be inserted later, inside the $data array. Each element corresponds with a column in the database table created earlier. You might notice a new method here, namely the post() method from the input library. This method makes sure the data is sanitized, protecting you from nasty attacks from others. The input library is loaded by default. At last, you insert our $data array into our database.

    + +

    Routing

    + +

    Before you can start adding news items into your CodeIgniter application you have to add an extra rule to config/routes.php file. Make sure your file contains the following. This makes sure CodeIgniter sees 'create' as a method instead of a news item's slug.

    + +
    +$route['news/create'] = 'news/create';
    +$route['news/(:any)'] = 'news/view/$1';
    +$route['news'] = 'news';
    +$route['(:any)'] = 'pages/view/$1';
    +$route['default_controller'] = 'pages/view';
    +
    + +

    Now point your browser to your local development environment where you installed CodeIgniter and add index.php/news/create to the URL. Congratulations, you just created your first CodeIgniter application! Add some news and check out the different pages you made.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/tutorial/hard_coded_pages.html b/api/user_guide/tutorial/hard_coded_pages.html new file mode 100644 index 0000000..2b5951f --- /dev/null +++ b/api/user_guide/tutorial/hard_coded_pages.html @@ -0,0 +1,158 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Tutorial - Hard coded pages

    + +

    The first thing we're going to do is setting up a controller to handle our hard coded pages. A controller is a class with a collection of methods that represent the different actions you can perform on a certain object. In our case, we want to be able to view a page.

    + +

    Note: This tutorial assumes you've downloaded CodeIgniter and installed the framework in your development environment.

    + +

    Create a file at application/controllers/pages.php with the following code.

    + + + +

    If you're familiar with PHP classes you see that we create a Pages class with a view method that accepts one parameter, $page. Another interesting observation is that the Pages class is extending the CI_Controller class. This means that the new Pages class can access the methods and variables defined in the CI_Controller class. When you look at this class in system/core/controller.php you can see this class is doing something really important; assigning an instance from the CodeIgniter super object to the $this object. In most of your code, $this is the object you will use to interact with the framework.

    + +

    Now we've created our first method, it is time to do some basic templating. For this tutorial, we will be creating two views to acts as our footer and header. Let's create our header at application/views/templates/header.php and ad the following code.

    + + + +

    Our header doesn't do anything exciting. It contains the basic HTML code that we will want to display before loading the main view. You can also see that we echo the $title variable, which we didn't define. We will set this variable in the Pages controller a bit later. Let's go ahead and create a footer at application/views/templates/footer.php that includes the following code.

    + + + +

    Adding logic to the controller

    + +

    Now we've set up the basics so we can finally do some real programming. Earlier we set up our controller with a view method. Because we don't want to write a separate method for every page, we made the view method accept one parameter, the name of the page. These hard coded pages will be located in application/views/pages/. Create two files in this directory named home.php and about.php and put in some HTML content.

    + +

    In order to load these pages we'll have to check whether these page actually exists. When the page does exist, we load the view for that pages, including the header and footer and display it to the user. If it doesn't, we show a "404 Page not found" error.

    + + + +

    The first thing we do is checking whether the page we're looking for does actually exist. We use PHP's native file_exists() to do this check and pass the path where the file is supposed to be. Next is the function show_404(), a CodeIgniter function that renders the default error page and sets the appropriate HTTP headers.

    + +

    In the header template you saw we were using the $title variable to customize our page title. This is where we define the title, but instead of assigning the value to a variable, we assign it to the title element in the $data array. The last thing we need to do is loading the views in the order we want them to be displayed. We also pass the $data array to the header view to make its elements available in the header view file.

    + +

    Routing

    + +

    Actually, our controller is already functioning. Point your browser to index.php/pages/view to see your homepage. When you visit index.php/pages/view/about you will see the about page, again including your header and footer. Now we're going to get rid of the pages/view part in our URI. As you may have seen, CodeIgniter does its routing by the class, method and parameter, separated by slashes.

    + +

    Open the routing file located at application/config/routes.php and add the following two lines. Remove all other code that sets any element in the $route array.

    + + + +

    CodeIgniter reads its routing rules from top to bottom and routes the request to the first matching rule. These routes are stored in the $route array where the keys represent the incoming request and the value the path to the method, as described above.

    + +

    The first rule in our $routes array matches every request - using the wildcard operator (:any) - and passes the value to the view method of the pages class we created earlier. The default controller route makes sure every request to the root goes to the view method as well, which has the first parameter set to 'home' by default.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/tutorial/index.html b/api/user_guide/tutorial/index.html new file mode 100644 index 0000000..d1da602 --- /dev/null +++ b/api/user_guide/tutorial/index.html @@ -0,0 +1,101 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Tutorial − Introduction

    + +

    This tutorial is intended to introduce you to the CodeIgniter framework and the basic principles of MVC architecture. It will show you how a basic CodeIgniter application is constructed in step-by-step fashion.

    + +

    In this tutorial, you will be creating a basic news application. You will begin by writing the code that can load static pages. Next, you will create a news section that reads news items from a database. Finally, you'll add a form to create news items in the database.

    + +

    This tutorial will primarily focus on:

    +
      +
    • Model-View-Controller basics
    • +
    • Routing basics
    • +
    • Form validation
    • +
    • Performing basic database queries using "Active Record"
    • +
    + +

    The entire tutorial is split up over several pages, each explaining a small part of the functionality of the CodeIgniter framework. You'll go through the following pages:

    +
      +
    • Introduction, this page, which gives you an overview of what to expect.
    • +
    • Static pages, which will teach you the basics of controllers, views and routing.
    • +
    • News section, where you'll start using models and will be doing some basic database operations.
    • +
    • Create news items, which will introduce more advanced database operations and form validation.
    • +
    • Conclusion, which will give you some pointers on further reading and other resources.
    • +
    + +

    Enjoy your exploration of the CodeIgniter framework.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/tutorial/news_section.html b/api/user_guide/tutorial/news_section.html new file mode 100644 index 0000000..f8e64fc --- /dev/null +++ b/api/user_guide/tutorial/news_section.html @@ -0,0 +1,230 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Tutorial − News section

    + +

    In the last section, we went over some basic concepts of the framework by writing a class that includes static pages. We cleaned up the URI by adding custom routing rules. Now it's time to introduce dynamic content and start using a database.

    + +

    Setting up your model

    + +

    Instead of writing database operations right in the controller, queries should be placed in a model, so they can easily be reused later. Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.

    + +

    Open up the application/models directory and create a new file called news_model.php and add the following code. Make sure you've configured your database properly as described here.

    + +
    +<?php
    +class News_model extends CI_Model {
    +
    +	public function __construct()
    +	{
    +		$this->load->database();
    +	}
    +}
    +
    + +

    This code looks similar to the controller code that was used earlier. It creates a new model by extending CI_Model and loads the database library. This will make the database class available through the $this->db object.

    + +

    Before querying the database, a database schema has to be created. Connect to your database and run the SQL command below. Also add some seed records.

    + +
    +CREATE TABLE news (
    +	id int(11) NOT NULL AUTO_INCREMENT,
    +	title varchar(128) NOT NULL,
    +	slug varchar(128) NOT NULL,
    +	text text NOT NULL,
    +	PRIMARY KEY (id),
    +	KEY slug (slug)
    +);
    +
    + +

    Now that the database and a model have been set up, you'll need a method to get all of our posts from our database. To do this, the database abstraction layer that is included with CodeIgniter — Active Record — is used. This makes it possible to write your 'queries' once and make them work on all supported database systems. Add the following code to your model.

    + +
    +public function get_news($slug = FALSE)
    +{
    +	if ($slug === FALSE)
    +	{
    +		$query = $this->db->get('news');
    +		return $query->result_array();
    +	}
    +
    +	$query = $this->db->get_where('news', array('slug' => $slug));
    +	return $query->row_array();
    +}
    +
    + +

    With this code you can perform two different queries. You can get all news records, or get a news item by its slug. You might have noticed that the $slug variable wasn't sanitized before running the query; Active Record does this for you.

    + +

    Display the news

    + +

    Now that the queries are written, the model should be tied to the views that are going to display the news items to the user. This could be done in our pages controller created earlier, but for the sake of clarity, a new "news" controller is defined. Create the new controller at application/controllers/news.php.

    + +
    +<?php
    +class News extends CI_Controller {
    +
    +	public function __construct()
    +	{
    +		parent::__construct();
    +		$this->load->model('news_model');
    +	}
    +
    +	public function index()
    +	{
    +		$data['news'] = $this->news_model->get_news();
    +	}
    +
    +	public function view($slug)
    +	{
    +		$data['news'] = $this->news_model->get_news($slug);
    +	}
    +}
    +
    + +

    Looking at the code, you may see some similarity with the files we created earlier. First, the "__construct" method: it calls the constructor of its parent class (CI_Controller) and loads the model, so it can be used in all other methods in this controller.

    + +

    Next, there are two methods to view all news items and one for a specific news item. You can see that the $slug variable is passed to the model's method in the second method. The model is using this slug to identify the news item to be returned.

    + +

    Now the data is retrieved by the controller through our model, but nothing is displayed yet. The next thing to do is passing this data to the views.

    + +
    +public function index()
    +{
    +	$data['news'] = $this->news_model->get_news();
    +	$data['title'] = 'News archive';
    +
    +	$this->load->view('templates/header', $data);
    +	$this->load->view('news/index', $data);
    +	$this->load->view('templates/footer');
    +}
    +
    + +

    The code above gets all news records from the model and assigns it to a variable. The value for the title is also assigned to the $data['title'] element and all data is passed to the views. You now need to create a view to render the news items. Create application/views/news/index.php and add the next piece of code.

    + +
    +<?php foreach ($news as $news_item): ?>
    +
    +    <h2><?php echo $news_item['title'] ?></h2>
    +    <div id="main">
    +        <?php echo $news_item['text'] ?>
    +    </div>
    +    <p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>
    +
    +<?php endforeach ?>
    +
    + +

    Here, each news item is looped and displayed to the user. You can see we wrote our template in PHP mixed with HTML. If you prefer to use a template language, you can use CodeIgniter's Template Parser class or a third party parser.

    + +

    The news overview page is now done, but a page to display individual news items is still absent. The model created earlier is made in such way that it can easily be used for this functionality. You only need to add some code to the controller and create a new view. Go back to the news controller and add the following lines to the file.

    + +
    +public function view($slug)
    +{
    +	$data['news_item'] = $this->news_model->get_news($slug);
    +
    +	if (empty($data['news_item']))
    +	{
    +		show_404();
    +	}
    +
    +	$data['title'] = $data['news_item']['title'];
    +
    +	$this->load->view('templates/header', $data);
    +	$this->load->view('news/view', $data);
    +	$this->load->view('templates/footer');
    +}
    +
    + +

    Instead of calling the get_news() method without a parameter, the $slug variable is passed, so it will return the specific news item. The only things left to do is create the corresponding view at application/views/news/view.php. Put the following code in this file.

    + +
    +<?php
    +echo '<h2>'.$news_item['title'].'</h2>';
    +echo $news_item['text'];
    +
    + +

    Routing

    +

    Because of the wildcard routing rule created earlier, you need need an extra route to view the controller that you just made. Modify your routing file (application/config/routes.php) so it looks as follows. This makes sure the requests reaches the news controller instead of going directly to the pages controller. The first line routes URI's with a slug to the view method in the news controller.

    + +
    +$route['news/(:any)'] = 'news/view/$1';
    +$route['news'] = 'news';
    +$route['(:any)'] = 'pages/view/$1';
    +$route['default_controller'] = 'pages/view';
    +
    + +

    Point your browser to your document root, followed by index.php/news and watch your news page.

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/tutorial/static_pages.html b/api/user_guide/tutorial/static_pages.html new file mode 100644 index 0000000..4b138d7 --- /dev/null +++ b/api/user_guide/tutorial/static_pages.html @@ -0,0 +1,206 @@ + + + + + +CodeIgniter Features : CodeIgniter User Guide + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +

    CodeIgniter User Guide Version 2.1.4

    +
    + + + + + + + + + +
    + + +
    + + + +
    + + +

    Tutorial − Static pages

    + +

    Note: This tutorial assumes you've downloaded CodeIgniter and installed the framework in your development environment.

    + +

    The first thing you're going to do is set up a controller to handle static pages. +A controller is simply a class that helps delegate work. It is the glue of your +web application.

    + +

    For example, when a call is made to: http://example.com/news/latest/10 We might imagine +that there is a controller named "news". The method being called on news +would be "latest". The news method's job could be to grab 10 +news items, and render them on the page. Very often in MVC, you'll see URL +patterns that match: http://example.com/[controller-class]/[controller-method]/[arguments] +As URL schemes become more complex, this may change. But for now, this is all we will need to know.

    + +

    Create a file at application/controllers/pages.php with the following code.

    + + + +

    You have created a class named "pages", with a view method that accepts one argument named $page. +The pages class is extending the CI_Controller class. +This means that the new pages class can access the methods and variables defined in the CI_Controller class +(system/core/Controller.php).

    + +

    The controller is what will become the center of every request to your web application. +In very technical CodeIgniter discussions, it may be referred to as the super object. +Like any php class, you refer to it within your controllers as $this. +Referring to $this is how you will load libraries, views, and generally +command the framework.

    + +

    Now you've created your first method, it's time to make some basic page templates. +We will be creating two "views" (page templates) that act as our page footer and header.

    + +

    Create the header at application/views/templates/header.php and add the following code.

    + + + +

    The header contains the basic HTML code that you'll want to display before loading the main view, together with a heading. +It will also output the $title variable, which we'll define later in the controller. +Now create a footer at application/views/templates/footer.php that includes the following code:

    + + + +

    Adding logic to the controller

    + +

    Earlier you set up a controller with a view() method. The method accepts one parameter, which is the name of the page to be loaded. +The static page templates will be located in the application/views/pages/ directory.

    + +

    In that directory, create two files named home.php and about.php. +Within those files, type some text − anything you'd like − and save them. +If you like to be particularly un-original, try "Hello World!".

    + +

    In order to load those pages, you'll have to check whether the requested page actually exists:

    + +
    +public function view($page = 'home')
    +{
    +
    +	if ( ! file_exists('application/views/pages/'.$page.'.php'))
    +	{
    +		// Whoops, we don't have a page for that!
    +		show_404();
    +	}
    +
    +	$data['title'] = ucfirst($page); // Capitalize the first letter
    +
    +	$this->load->view('templates/header', $data);
    +	$this->load->view('pages/'.$page, $data);
    +	$this->load->view('templates/footer', $data);
    +
    +}
    +
    + +

    Now, when the page does exist, it is loaded, including the header and footer, and displayed to the user. If the page doesn't exist, a "404 Page not found" error is shown.

    + +

    The first line in this method checks whether the page actually exists. PHP's native file_exists() function is used to check whether the file is where it's expected to be. show_404() is a built-in CodeIgniter function that renders the default error page.

    + +

    In the header template, the $title variable was used to customize the page title. The value of title is defined in this method, but instead of assigning the value to a variable, it is assigned to the title element in the $data array.

    + +

    The last thing that has to be done is loading the views in the order they should be displayed. +The second parameter in the view() method is used to pass values to the view. Each value in the $data array is assigned to a variable with the name of its key. So the value of $data['title'] in the controller is equivalent to $title in the view.

    + +

    Routing

    + +

    The controller is now functioning! Point your browser to [your-site-url]index.php/pages/view to see your page. When you visit index.php/pages/view/about you'll see the about page, again including the header and footer.

    + +

    Using custom routing rules, you have the power to map any URI to any controller and method, and break free from the normal convention: +http://example.com/[controller-class]/[controller-method]/[arguments]

    + +

    Let's do that. Open the routing file located at application/config/routes.php and add the following two lines. Remove all other code that sets any element in the $route array.

    + +
    +$route['default_controller'] = 'pages/view';
    +$route['(:any)'] = 'pages/view/$1';
    +
    + +

    CodeIgniter reads its routing rules from top to bottom and routes the request to the first matching rule. Each rule is a regular expression +(left-side) mapped to a controller and method name separated by slashes (right-side). +When a request comes in, CodeIgniter looks for the first match, and calls the appropriate controller and method, possibly with arguments.

    + +

    More information about routing can be found in the URI Routing documentation.

    + +

    Here, the second rule in the $routes array matches any request using the wildcard string (:any). +and passes the parameter to the view() method of the pages class.

    + +

    Now visit index.php/about. Did it get routed correctly to the view() method +in the pages controller? Awesome!

    + +
    + + + + + + + \ No newline at end of file diff --git a/api/user_guide/userguide.css b/api/user_guide/userguide.css new file mode 100644 index 0000000..f93ff0d --- /dev/null +++ b/api/user_guide/userguide.css @@ -0,0 +1,415 @@ +body { + margin: 0; + padding: 0; + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + font-size: 14px; + color: #333; + background-color: #fff; +} + +a { + color: #0134c5; + background-color: transparent; + text-decoration: none; + font-weight: normal; + outline-style: none; +} +a:visited { + color: #0134c5; + background-color: transparent; + text-decoration: none; + outline-style: none; +} +a:hover { + color: #000; + text-decoration: none; + background-color: transparent; + outline-style: none; +} + +#breadcrumb { + float: left; + background-color: transparent; + margin: 10px 0 0 42px; + padding: 0; + font-size: 10px; + color: #666; +} +#breadcrumb_right { + float: right; + width: 175px; + background-color: transparent; + padding: 8px 8px 3px 0; + text-align: right; + font-size: 10px; + color: #666; +} +#nav { + background-color: #494949; + margin: 0; + padding: 0; +} +#nav2 { + background: #fff url(images/nav_bg_darker.jpg) repeat-x left top; + padding: 0 310px 0 0; + margin: 0; + text-align: right; +} +#nav_inner { + background-color: transparent; + padding: 8px 12px 0 20px; + margin: 0; + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + font-size: 11px; +} + +#nav_inner h3 { + font-size: 12px; + color: #fff; + margin: 0; + padding: 0; +} + +#nav_inner .td_sep { + background: transparent url(images/nav_separator_darker.jpg) repeat-y left top; + width: 25%; + padding: 0 0 0 20px; +} +#nav_inner .td { + width: 25%; +} +#nav_inner p { + color: #eee; + background-color: transparent; + padding:0; + margin: 0 0 10px 0; +} +#nav_inner ul { + list-style-image: url(images/arrow.gif); + padding: 0 0 0 18px; + margin: 8px 0 12px 0; +} +#nav_inner li { + padding: 0; + margin: 0 0 4px 0; +} + +#nav_inner a { + color: #eee; + background-color: transparent; + text-decoration: none; + font-weight: normal; + outline-style: none; +} + +#nav_inner a:visited { + color: #eee; + background-color: transparent; + text-decoration: none; + outline-style: none; +} + +#nav_inner a:hover { + color: #ccc; + text-decoration: none; + background-color: transparent; + outline-style: none; +} + +#masthead { + margin: 0 40px 0 35px; + padding: 0 0 0 6px; + border-bottom: 1px solid #999; +} + +#masthead h1 { +background-color: transparent; +color: #e13300; +font-size: 18px; +font-weight: normal; +margin: 0; +padding: 0 0 6px 0; +} + +#searchbox { + background-color: transparent; + padding: 6px 40px 0 0; + text-align: right; + font-size: 10px; + color: #666; +} + +#img_welcome { + border-bottom: 1px solid #D0D0D0; + margin: 0 40px 0 40px; + padding: 0; + text-align: center; +} + +#content { + margin: 20px 40px 0 40px; + padding: 0; +} + +#content p { + margin: 12px 20px 12px 0; +} + +#content h1 { +color: #e13300; +border-bottom: 1px solid #666; +background-color: transparent; +font-weight: normal; +font-size: 24px; +margin: 0 0 20px 0; +padding: 3px 0 7px 3px; +} + +#content h2 { + background-color: transparent; + border-bottom: 1px solid #999; + color: #000; + font-size: 18px; + font-weight: bold; + margin: 28px 0 16px 0; + padding: 5px 0 6px 0; +} + +#content h3 { + background-color: transparent; + color: #333; + font-size: 16px; + font-weight: bold; + margin: 16px 0 15px 0; + padding: 0 0 0 0; +} + +#content h4 { + background-color: transparent; + color: #444; + font-size: 14px; + font-weight: bold; + margin: 22px 0 0 0; + padding: 0 0 0 0; +} + +#content img { + margin: auto; + padding: 0; +} + +#content code { + font-family: Monaco, Verdana, Sans-serif; + font-size: 12px; + background-color: #f9f9f9; + border: 1px solid #D0D0D0; + color: #002166; + display: block; + margin: 14px 0 14px 0; + padding: 12px 10px 12px 10px; +} + +#content pre { + font-family: Monaco, Verdana, Sans-serif; + font-size: 12px; + background-color: #f9f9f9; + border: 1px solid #D0D0D0; + color: #002166; + display: block; + margin: 14px 0 14px 0; + padding: 12px 10px 12px 10px; +} + +#content .path { + background-color: #EBF3EC; + border: 1px solid #99BC99; + color: #005702; + text-align: center; + margin: 0 0 14px 0; + padding: 5px 10px 5px 8px; +} + +#content dfn { + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + color: #00620C; + font-weight: bold; + font-style: normal; +} +#content var { + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + color: #8F5B00; + font-weight: bold; + font-style: normal; +} +#content samp { + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + color: #480091; + font-weight: bold; + font-style: normal; +} +#content kbd { + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + color: #A70000; + font-weight: bold; + font-style: normal; +} + +#content ul { + list-style-image: url(images/arrow.gif); + margin: 10px 0 12px 0; +} + +li.reactor { + list-style-image: url(images/reactor-bullet.png); +} +#content li { + margin-bottom: 9px; +} + +#content li p { + margin-left: 0; + margin-right: 0; +} + +#content .tableborder { + border: 1px solid #999; +} +#content th { + font-weight: bold; + text-align: left; + font-size: 12px; + background-color: #666; + color: #fff; + padding: 4px; +} + +#content .td { + font-weight: normal; + font-size: 12px; + padding: 6px; + background-color: #f3f3f3; +} + +#content .tdpackage { + font-weight: normal; + font-size: 12px; +} + +#content .important { + background: #FBE6F2; + border: 1px solid #D893A1; + color: #333; + margin: 10px 0 5px 0; + padding: 10px; +} + +#content .important p { + margin: 6px 0 8px 0; + padding: 0; +} + +#content .important .leftpad { + margin: 6px 0 8px 0; + padding-left: 20px; +} + +#content .critical { + background: #FBE6F2; + border: 1px solid #E68F8F; + color: #333; + margin: 10px 0 5px 0; + padding: 10px; +} + +#content .critical p { + margin: 5px 0 6px 0; + padding: 0; +} + + +#footer { +background-color: transparent; +font-size: 10px; +padding: 16px 0 15px 0; +margin: 20px 0 0 0; +text-align: center; +} + +#footer p { + font-size: 10px; + color: #999; + text-align: center; +} +#footer address { + font-style: normal; +} + +.center { + text-align: center; +} + +img { + padding:0; + border: 0; + margin: 0; +} + +.nopad { + padding:0; + border: 0; + margin: 0; +} + + +form { + margin: 0; + padding: 0; +} + +.input { + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + font-size: 11px; + color: #333; + border: 1px solid #B3B4BD; + width: 100%; + font-size: 11px; + height: 1.5em; + padding: 0; + margin: 0; +} + +.textarea { + font-family: Lucida Grande, Verdana, Geneva, Sans-serif; + font-size: 14px; + color: #143270; + background-color: #f9f9f9; + border: 1px solid #B3B4BD; + width: 100%; + padding: 6px; + margin: 0; +} + +.select { + background-color: #fff; + font-size: 11px; + font-weight: normal; + color: #333; + padding: 0; + margin: 0 0 3px 0; +} + +.checkbox { + background-color: transparent; + padding: 0; + border: 0; +} + +.submit { + background-color: #000; + color: #fff; + font-weight: normal; + font-size: 10px; + border: 1px solid #fff; + margin: 0; + padding: 1px 5px 2px 5px; +} \ No newline at end of file diff --git a/frontend/.browserslistrc b/frontend/.browserslistrc new file mode 100644 index 0000000..d6471a3 --- /dev/null +++ b/frontend/.browserslistrc @@ -0,0 +1,2 @@ +> 1% +last 2 versions diff --git a/frontend/.env b/frontend/.env new file mode 100644 index 0000000..000311e --- /dev/null +++ b/frontend/.env @@ -0,0 +1 @@ +VUE_APP_API_URL=http://localhost:8000/api/index.php/training diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.js new file mode 100644 index 0000000..1c6179f --- /dev/null +++ b/frontend/.eslintrc.js @@ -0,0 +1,17 @@ +module.exports = { + root: true, + env: { + node: true + }, + 'extends': [ + 'plugin:vue/essential', + 'eslint:recommended' + ], + rules: { + 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', + 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off' + }, + parserOptions: { + parser: 'babel-eslint' + } +} diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..a0dddc6 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,21 @@ +.DS_Store +node_modules +/dist + +# local env files +.env.local +.env.*.local + +# Log files +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..474dfc1 --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,24 @@ +# The bluefire frontend + +## Project setup +``` +yarn install +``` + +### Compiles and hot-reloads for development +``` +yarn serve +``` + +### Compiles and minifies for production +``` +yarn build +``` + +### Lints and fixes files +``` +yarn lint +``` + +### Customize configuration +See [Configuration Reference](https://cli.vuejs.org/config/). diff --git a/frontend/babel.config.js b/frontend/babel.config.js new file mode 100644 index 0000000..e955840 --- /dev/null +++ b/frontend/babel.config.js @@ -0,0 +1,5 @@ +module.exports = { + presets: [ + '@vue/cli-plugin-babel/preset' + ] +} diff --git a/frontend/jsconfig.json b/frontend/jsconfig.json new file mode 100644 index 0000000..09e7655 --- /dev/null +++ b/frontend/jsconfig.json @@ -0,0 +1,5 @@ +{ + "include": [ + "./src/**/**" + ] +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..12b007c --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,30 @@ +{ + "name": "bluefire-frontend", + "version": "0.1.0", + "private": true, + "scripts": { + "serve": "vue-cli-service serve", + "build": "vue-cli-service build", + "lint": "vue-cli-service lint" + }, + "dependencies": { + "axios": "^0.19.2", + "core-js": "^3.4.4", + "material-icons": "^0.3.1", + "normalize.css": "^8.0.1", + "vue": "^2.6.10", + "vue-router": "^3.1.3", + "vuex": "^3.1.2" + }, + "devDependencies": { + "@vue/cli-plugin-babel": "^4.1.0", + "@vue/cli-plugin-eslint": "^4.1.0", + "@vue/cli-plugin-router": "^4.1.0", + "@vue/cli-plugin-vuex": "^4.1.2", + "@vue/cli-service": "^4.1.0", + "babel-eslint": "^10.0.3", + "eslint": "^5.16.0", + "eslint-plugin-vue": "^5.0.0", + "vue-template-compiler": "^2.6.10" + } +} diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico new file mode 100644 index 0000000..df36fcf Binary files /dev/null and b/frontend/public/favicon.ico differ diff --git a/frontend/public/index.html b/frontend/public/index.html new file mode 100644 index 0000000..b9b3c92 --- /dev/null +++ b/frontend/public/index.html @@ -0,0 +1,17 @@ + + + + + + + + bluefire-frontend + + + +
    + + + diff --git a/frontend/src/App.vue b/frontend/src/App.vue new file mode 100644 index 0000000..3eace3b --- /dev/null +++ b/frontend/src/App.vue @@ -0,0 +1,25 @@ + + + diff --git a/frontend/src/assets/css/bluefire.css b/frontend/src/assets/css/bluefire.css new file mode 100644 index 0000000..c2e2e70 --- /dev/null +++ b/frontend/src/assets/css/bluefire.css @@ -0,0 +1,564 @@ + +body { + font-family: 'Product Sans'; + margin: 0; +} +p ,h1, h2, h3, h4, h5, h6{ + margin-bottom: 0; + margin-top: 0; +} +a { + color: black; + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +.line-separator { + border: 0.2rem solid rgba(60, 53, 113, 1); +} +/* Forms */ +.form-space { + height: 3rem; +} +.form-input { + margin-bottom: 2rem; +} +.form-input.horizontal { + display: flex; + flex-direction: row; +} +.form-input * { + display: block; +} +.form-input.horizontal > label { + width: 80%; +} +.form-input.horiziontal > div,input{ + width: 20%; +} +.form-input label { + font-size: 1.5rem; + font-weight: bold; +} +.form-input label.required::after { + content: '*'; + color: red; +} +.form-input input[type=text],input[type=password],textarea { + appearance: none; + border: none; + border-bottom: 1px solid black; + width: 100%; + font-family: "Product Sans"; + padding: 0.25rem 0.25rem; + background-color: inherit; +} +.form-input input[type=file] { + appearance: none; + width: 100%; +} +.form-input input[type=radio] { + appearance: none; + width: 1rem; + border-radius: 50%; + padding: 0 0.5rem; + margin: 0 0.4rem; + border: 1px solid black; +} +.form-input input[type=radio]:checked { + appearance: none; + width: 1rem; + border-radius: 50%; + padding: 0 0.5rem; + margin: 0 0.4rem; + border: 1px solid black; + background: radial-gradient(black 0,black 35%, transparent 36%) +} +.form-input div { + padding: 0.25rem 0.25rem; +} +.form-notice { + margin-bottom: 2rem; +} +.button { + appearance: none; + background-color: rgba(60, 53, 113, 1); + color: white; + border: none; + border-radius: 5px; + font-family: "Product Sans"; + margin: 0.5rem 0; + cursor: pointer; +} +.button.plain { + color: rgba(60, 53, 113, 1); + background-color: transparent; +} +.button.large { + padding: 1rem 0.5rem; + font-size: 1.5rem; +} +.button.medium { + padding: 1rem 0.5rem; + font-size: 1.25rem; +} + +header { + font-family: 'Product Sans'; + font-size: 1.125rem; + background-color: rgba(242, 242, 242, 1); + height: 4rem; + box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.3); + display: flex; + flex-direction: row; + align-items: center; + padding: 0rem 3rem; +} +header .logo img{ + object-fit: contain; + height: 4rem; +} +header .sublogo { + margin-left: 0.25rem; + margin-top: auto; + margin-bottom: 1rem; + margin-right: 1rem; + font-size: 1rem; +} +header .nav { + display: flex; + flex-direction: row; +} +header .nav-item { + margin: 0 1rem; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + height: 100%; +} +header .nav-item .nav-link { + text-decoration: none; + color: black; +} +header .selectors { + margin-left: auto; + display: flex; + flex-direction: row; + +} +.bluefire-selector { + appearance: none; + border: none; + font-family: 'Product Sans'; + font-size: 1.125rem; + margin-top: 0.5rem; + margin-bottom: 0.5rem; + padding-right: 2rem; + + /* Custom arrow */ + background-image: + linear-gradient(45deg, transparent 50%, #666666 50%), + linear-gradient(135deg, #666666 50%, transparent 50%); + background-position: + calc(100% - 1rem) 0.4rem, + calc(100% - 0.5rem) 0.4rem; + background-size: + 0.5rem 0.5rem, + 0.5rem 0.5rem; + background-repeat: no-repeat; +} +.bluefire-selector:focus { + color: black; + border: none; +} + +header .search { + position: relative; + border-bottom: 0.125rem solid black; + margin-right: 1rem; +} +header .search .header-search { + appearance: none; + background-color: transparent; + border: none; + padding: 0.25rem; + font-size: 0.875rem; + font-family: "Product Sans"; +} +header .search .button-search img{ + position: absolute; + right: 0; + height: 1.5rem; +} + +header .account .nav-link { + font-weight: bold; +} + +.container { + padding: 2rem 4%; +} + +.index-banner { + padding: 0em 8% 0 8%; +} +.index-banner h1{ + font-family: "Montserrat"; + font-weight: bold; + font-size: 3.5rem; + text-align: center; + color: #333333; + margin-top: 3rem; + margin-bottom: 2rem; +} +.index-banner .index-image { + width: 100%; + border-radius: 20px; + opacity: 0.78; + +} +.index-banner .subheading { + font-weight: bold; + font-size: 2rem; + text-align: center; + color: #333333; + margin: 3rem auto; +} + +.page-banner { + height: 20rem; + background: url('../images/1.jpg'); + background-size: cover; +} +.page-banner-inner { + background-color: rgba(255,255,255,0.25); + width: 100%; + height: calc(100% - 4rem); + padding: 2rem 8%; + position: relative; +} +.page-banner-title { + position: absolute; + left: 6%; + bottom: 0.5rem; +} +.page-banner-title h1 { + font-size: 3.25rem; +} +.main-content { + padding: 0 3%; +} +.section-heading { + display: flex; + flex-direction: row; + border-bottom: 0.5rem solid #322b6b; +} +.section-heading h1 { + font-size: 3rem; + font-family: "Product Sans"; + margin-bottom: 0px; + margin-left: 0.5rem; +} +.section-heading .right { + margin-left: auto; +} +.section-content { + padding: 0 1%; + margin-bottom: 4rem; +} +footer { + padding: 0 3rem; + background-color: rgba(215, 215, 215, 1); + margin-bottom: 0.5rem; +} +.main-footer { + display: flex; + flex-direction: row; + align-items: center; + height: 8rem; +} + +.main-footer .logo img{ + object-fit: contain; + height: 4rem; +} +.main-footer .sublogo { + margin-left: 0.25rem; + margin-top: auto; + margin-bottom: 3rem; + margin-right: 1rem; + font-size: 1rem; +} +.main-footer .contact { + display: flex; + flex-direction: column; + margin-left: auto; + margin-right: 3rem; + align-items: right; +} +.main-footer .contact p { + text-align: right; + margin: 0.5rem 0; + font-size: 1.125rem; +} +footer .copyright { + font-size: 1.125rem; + text-align: center; + padding: 0.5rem 0; +} + +/* Login page */ +.login-container{ + background: url("../images/2.jpg"); + background-size: cover; + position: relative; +} +.login-container .inner { + background: rgba(255,255,255,0.63); + padding: 4rem 4% 8rem 4%; + padding-top: 8rem; + padding-bottom: 6rem; +} +.login-banner { + position: absolute; + top: 10rem; + right: 4%; + float: right; + text-align: right; +} +.login-banner p { + margin: 0; + font-size: 3rem; + font-weight: bold; + line-height: 1; +} +.login-banner .large { + font-size: 5rem; + color: #333; +} +.box-container { + background-color: rgba(242, 242, 242, 1); + padding-top: 2rem; + padding-left: 2.5rem; + padding-right: 2.5rem; + padding-bottom: 0.5rem; + border-radius: 20px; + box-shadow: 5px 5px 18px rgba(167, 109, 109, 0.3); + width: 25rem; +} +.login-box .admin-login { + display: block; + text-align: right; + +} +.login-form { + padding: 0 2.5rem; +} + +.register-link a{ + color: rgba(60, 53, 113, 1); + font-size: 1.25rem; + font-weight: bold; +} + +/* Admin page */ +.admin-container { + padding: 0 1.5%; +} +.admin-heading { + margin-bottom: 4rem; +} +.admin-heading h1 { + font-size: 1.75rem; +} + +/* Position page */ +.position-container { + margin-top: 1rem; + padding: 0 8%; +} +.position { + display: flex; + flex-direction: row; +} +.position-overview { + width: 30%; +} +.title-bar { + width: 4rem; + border-top: 0.75rem solid rgba(60, 53, 113, 1); + height: 0.5rem; +} +.position-title { + margin-bottom: 0.5rem; +} +.position-location div { + margin-bottom: 0.5rem +} +.position-location .region { + font-family: "Montserrat"; + font-weight: bold; + font-size: 0.75rem; +} +.position-location .address { + font-size: 0.875rem; +} +.detail-item h2 { + margin-bottom: 0.25rem; + font-size: 1.25rem; +} +.detail-item p { + font-size: 1.25rem; + margin-bottom: 1rem; +} +.position-description { + padding-left: 6%; + padding-top: 1.5rem; + width: 75%; + font-size: 1.125rem; +} +.position-description .description { + margin-bottom: 2rem; +} +.position-status { + margin-left: auto; + padding: 2rem 2rem 2rem 2rem; +} +.position-status h2 { + font-size: 1.5rem; +} +.position-status .applicant-amount { + color: rgba(60, 53, 113, 1); + font-size: 3.5rem; + text-align: center; + font-weight: bold; +} +/* List pages */ +.list-container { + margin-top: 2rem; +} + +/* Job apply container */ +.narrow-container { + margin-top: 4rem; + padding: 0 8%; +} +.normal-heading { + font-size: 1.5rem; + font-family: "Montserrat"; +} +.normal-box { + background-color: rgba(242, 242, 242, 1); + padding: 2rem 2rem 2rem 1.5rem; +} +.normal-form { + background-color: rgba(242, 242, 242, 1); + padding: 2rem 8rem 2rem 1.5rem; +} +.apply-title { + margin: 0 2rem; + margin-bottom: 2rem; +} +.required-notice { + color: red; + font-weight: bold; +} +/* Applicant page */ + +.normal-box.applicant { + box-shadow: 4px 4px 17px rgba(0, 0, 0, 0.349019607843137); + border-radius: 20px; + margin-bottom: 2rem; +} + +.applicant .applicant-no { + font-weight: bold; + font-size: 1.5rem; + color: #322b6b; + margin-right: 1rem; +} +.applicant .applicant-detail { + flex-grow: 1; +} +.applicant-name { + font-size: 0.75rem; + margin-bottom: 1rem; +} + +.applicant-data { + padding: 0.5rem; +} + +.applicant-fate { + display: flex; + flex-direction: row; + justify-content: flex-end; +} +/* About page */ +.about-background { + background: url('../images/about.jpg'); +} +.about-container { + background: rgba(255,255,255,0.9); + padding: 2.5rem 12rem 2.5rem 12rem; + font-family: "Montserrat"; +} +.about-container h1 { + font-size: 4rem; + padding-bottom: 2.5rem; + text-align: center; +} +.about-container p { + text-align: center; + font-size: 1.5rem; +} +.about-container .about-bottom-space { + padding-bottom: 2.5rem; +} + +/* Utility classes */ + +.w-25 { + width: 25%; +} +.w-33 { + width: 33.333333%; +} +.w-50 { + width: 50%; +} +.w-67 { + width: 66.6666666%; +} +.w-100 { + width: 100%; +} +.text-center { + text-align: center; +} +.uppercase { + text-transform: uppercase; +} +.row { + display: flex; + flex-direction: row; +} + +.flex-center { + display: flex; + flex-direction: column; + align-items: center; +} +.rounded { + border-radius: 20px; +} +textarea.noresize { + resize: none; +} + +.font-heading { + font-family: "Montserrat"; +} diff --git a/frontend/src/assets/css/fonts.css b/frontend/src/assets/css/fonts.css new file mode 100644 index 0000000..98cadde --- /dev/null +++ b/frontend/src/assets/css/fonts.css @@ -0,0 +1,13 @@ +@font-face { + font-family: 'Montserrat'; + src: url('../fonts/Montserrat-Regular.woff2') format('woff2') font-weight-normal, + url('../fonts/Montserrat-Bold.woff2') format('woff2') font-weight-bold; +} + +@font-face { + font-family: 'Product Sans'; + src: url('../fonts/Product Sans Regular.woff2') format('woff2') font-weight-normal, + url('../fonts/Product Sans Bold.woff2') format('woff2') font-weight-bold, + url('../fonts/Product Sans Italic.woff2') format('woff2') font-italic font-weight-normal, + url('../fonts/Product Sans Bold Italic.woff2') format('woff2') font-italic font-weight-bold; +} diff --git a/frontend/src/assets/fonts/Montserrat-Bold.woff2 b/frontend/src/assets/fonts/Montserrat-Bold.woff2 new file mode 100644 index 0000000..24fd8fc Binary files /dev/null and b/frontend/src/assets/fonts/Montserrat-Bold.woff2 differ diff --git a/frontend/src/assets/fonts/Montserrat-Regular.woff2 b/frontend/src/assets/fonts/Montserrat-Regular.woff2 new file mode 100644 index 0000000..95cb51d Binary files /dev/null and b/frontend/src/assets/fonts/Montserrat-Regular.woff2 differ diff --git a/frontend/src/assets/fonts/Product Sans Bold Italic.woff2 b/frontend/src/assets/fonts/Product Sans Bold Italic.woff2 new file mode 100644 index 0000000..80f6e97 Binary files /dev/null and b/frontend/src/assets/fonts/Product Sans Bold Italic.woff2 differ diff --git a/frontend/src/assets/fonts/Product Sans Bold.woff2 b/frontend/src/assets/fonts/Product Sans Bold.woff2 new file mode 100644 index 0000000..6ac7bfb Binary files /dev/null and b/frontend/src/assets/fonts/Product Sans Bold.woff2 differ diff --git a/frontend/src/assets/fonts/Product Sans Italic.woff2 b/frontend/src/assets/fonts/Product Sans Italic.woff2 new file mode 100644 index 0000000..ac18842 Binary files /dev/null and b/frontend/src/assets/fonts/Product Sans Italic.woff2 differ diff --git a/frontend/src/assets/fonts/Product Sans Regular.woff2 b/frontend/src/assets/fonts/Product Sans Regular.woff2 new file mode 100644 index 0000000..07e2427 Binary files /dev/null and b/frontend/src/assets/fonts/Product Sans Regular.woff2 differ diff --git a/frontend/src/assets/images/1.jpg b/frontend/src/assets/images/1.jpg new file mode 100644 index 0000000..35ba750 Binary files /dev/null and b/frontend/src/assets/images/1.jpg differ diff --git a/frontend/src/assets/images/2.jpg b/frontend/src/assets/images/2.jpg new file mode 100644 index 0000000..e6c08ed Binary files /dev/null and b/frontend/src/assets/images/2.jpg differ diff --git a/frontend/src/assets/images/HeaderLogo.png b/frontend/src/assets/images/HeaderLogo.png new file mode 100644 index 0000000..2417472 Binary files /dev/null and b/frontend/src/assets/images/HeaderLogo.png differ diff --git a/frontend/src/assets/images/Logo.psd b/frontend/src/assets/images/Logo.psd new file mode 100644 index 0000000..a11df5a Binary files /dev/null and b/frontend/src/assets/images/Logo.psd differ diff --git a/frontend/src/assets/images/LogoHorizontal.png b/frontend/src/assets/images/LogoHorizontal.png new file mode 100644 index 0000000..cf17bab Binary files /dev/null and b/frontend/src/assets/images/LogoHorizontal.png differ diff --git a/frontend/src/assets/images/LogoVertical.png b/frontend/src/assets/images/LogoVertical.png new file mode 100644 index 0000000..8c3542f Binary files /dev/null and b/frontend/src/assets/images/LogoVertical.png differ diff --git a/frontend/src/assets/images/about.jpg b/frontend/src/assets/images/about.jpg new file mode 100644 index 0000000..f94c99f Binary files /dev/null and b/frontend/src/assets/images/about.jpg differ diff --git a/frontend/src/assets/images/bookmark.svg b/frontend/src/assets/images/bookmark.svg new file mode 100644 index 0000000..06098d1 --- /dev/null +++ b/frontend/src/assets/images/bookmark.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/frontend/src/assets/images/search-icon.png b/frontend/src/assets/images/search-icon.png new file mode 100644 index 0000000..0657ffc Binary files /dev/null and b/frontend/src/assets/images/search-icon.png differ diff --git a/frontend/src/components/ApplicantListing.vue b/frontend/src/components/ApplicantListing.vue new file mode 100644 index 0000000..3dce934 --- /dev/null +++ b/frontend/src/components/ApplicantListing.vue @@ -0,0 +1,180 @@ + + + + \ No newline at end of file diff --git a/frontend/src/components/JobListing.vue b/frontend/src/components/JobListing.vue new file mode 100644 index 0000000..b28ee29 --- /dev/null +++ b/frontend/src/components/JobListing.vue @@ -0,0 +1,250 @@ + + + + \ No newline at end of file diff --git a/frontend/src/layouts/BackOffice.vue b/frontend/src/layouts/BackOffice.vue new file mode 100644 index 0000000..5946b09 --- /dev/null +++ b/frontend/src/layouts/BackOffice.vue @@ -0,0 +1,61 @@ + + + + diff --git a/frontend/src/layouts/FrontOffice.vue b/frontend/src/layouts/FrontOffice.vue new file mode 100644 index 0000000..3918fbd --- /dev/null +++ b/frontend/src/layouts/FrontOffice.vue @@ -0,0 +1,83 @@ + + + diff --git a/frontend/src/lib/API.js b/frontend/src/lib/API.js new file mode 100644 index 0000000..f7abe52 --- /dev/null +++ b/frontend/src/lib/API.js @@ -0,0 +1,5 @@ +import axios from 'axios'; +var client = axios.create({ + baseURL: process.env.VUE_APP_API_URL +}); +export default client; diff --git a/frontend/src/main.js b/frontend/src/main.js new file mode 100644 index 0000000..f253456 --- /dev/null +++ b/frontend/src/main.js @@ -0,0 +1,12 @@ +import Vue from 'vue' +import App from './App.vue' +import router from './router' +import store from './store' + +Vue.config.productionTip = false + +new Vue({ + router, + store, + render: h => h(App) +}).$mount('#app') diff --git a/frontend/src/router/index.js b/frontend/src/router/index.js new file mode 100644 index 0000000..f5413fe --- /dev/null +++ b/frontend/src/router/index.js @@ -0,0 +1,108 @@ +import Vue from 'vue' +import VueRouter from 'vue-router' +import FrontOffice from '../layouts/FrontOffice.vue' +import BackOffice from '../layouts/BackOffice.vue' + +import Index from '../views/Index.vue' +import Login from '../views/Login.vue' +import AdminLogin from '../views/AdminLogin.vue' +import Register from '../views/Register.vue' +import AboutUs from '../views/AboutUs.vue' +import JobDetail from '../views/JobDetail.vue' +import JobList from '../views/JobList.vue' +import BookmarkList from '../views/BookmarkList.vue' +import JobApply from '../views/JobApply.vue' + +import AdminIndex from '../views/admin/AdminIndex.vue' +import AdminAddJob from '../views/admin/AdminAddJob.vue' +import AdminEditJob from '../views/admin/AdminEditJob.vue' +import AdminApplicantDetail from '../views/admin/AdminApplicantDetail' +Vue.use(VueRouter) + +const routes = [ + { + path: "/", + component: FrontOffice, + children: [ + { + name: 'index', + path: '', + component: Index, + }, + { + name: 'login', + path: '/login', + component: Login, + }, + { + name: 'admin-login', + path: '/admin/login', + component: AdminLogin, + }, + { + name: 'register', + path: '/register', + component: Register, + }, + { + name: 'about-us', + path: 'about', + component: AboutUs, + }, + { + name: 'job-detail', + path: '/job/:id', + component: JobDetail, + }, + { + name: 'job-apply', + path: '/job/apply/:id', + component: JobApply, + }, + { + name: 'job-list', + path: '/jobs', + component: JobList, + }, + { + name: 'bookmark-list', + path: '/bookmarks', + component: BookmarkList, + }, + ], + }, + { + path: '/admin', + component: BackOffice, + children: [ + { + name: 'admin-index', + path: '', + component: AdminIndex, + }, + { + name: 'admin-job-new', + path: 'job/new', + component: AdminAddJob, + }, + { + name: 'admin-job-edit', + path: 'job/edit/:id', + component: AdminEditJob, + }, + { + name: 'admin-job-applicants', + path: 'applicants/:id', + component: AdminApplicantDetail + } + ] + } +] + +const router = new VueRouter({ + mode: 'history', + base: process.env.BASE_URL, + routes +}) + +export default router diff --git a/frontend/src/store/index.js b/frontend/src/store/index.js new file mode 100644 index 0000000..626d540 --- /dev/null +++ b/frontend/src/store/index.js @@ -0,0 +1,51 @@ +import Vue from 'vue' +import Vuex from 'vuex' + +Vue.use(Vuex) + +export default new Vuex.Store({ + state: { + apiKey: 0, + user: {}, + adminApiKey: 0, + admin: {}, + countryId: 0, + cityId: 0, + countries: [], + cities: [], + }, + mutations: { + login(state, data) { + state.apiKey = data.UserID; + state.user = data; + }, + logout(state) { + state.apiKey = 0; + state.user = {}; + }, + adminLogin(state, data) { + state.adminApiKey = data.AdminID; + state.admin = data + }, + adminLogout(state) { + state.adminApiKey = 0; + state.admin = {}; + }, + setCountryId(state, id) { + state.countryId = id; + }, + setCityId(state, id) { + state.cityId = id; + }, + setCountries(state, countries) { + state.countries = countries; + }, + setCities(state, cities) { + state.cities = cities; + } + }, + actions: { + }, + modules: { + } +}) diff --git a/frontend/src/views/AboutUs.vue b/frontend/src/views/AboutUs.vue new file mode 100644 index 0000000..c7291fe --- /dev/null +++ b/frontend/src/views/AboutUs.vue @@ -0,0 +1,19 @@ + + + diff --git a/frontend/src/views/AdminLogin.vue b/frontend/src/views/AdminLogin.vue new file mode 100644 index 0000000..1b81fcd --- /dev/null +++ b/frontend/src/views/AdminLogin.vue @@ -0,0 +1,56 @@ + + + \ No newline at end of file diff --git a/frontend/src/views/BookmarkList.vue b/frontend/src/views/BookmarkList.vue new file mode 100644 index 0000000..290e8b4 --- /dev/null +++ b/frontend/src/views/BookmarkList.vue @@ -0,0 +1,37 @@ + + + + + \ No newline at end of file diff --git a/frontend/src/views/Index.vue b/frontend/src/views/Index.vue new file mode 100644 index 0000000..5fefd7f --- /dev/null +++ b/frontend/src/views/Index.vue @@ -0,0 +1,28 @@ + + + diff --git a/frontend/src/views/JobApply.vue b/frontend/src/views/JobApply.vue new file mode 100644 index 0000000..1706379 --- /dev/null +++ b/frontend/src/views/JobApply.vue @@ -0,0 +1,152 @@ + + + + \ No newline at end of file diff --git a/frontend/src/views/JobDetail.vue b/frontend/src/views/JobDetail.vue new file mode 100644 index 0000000..8b76fde --- /dev/null +++ b/frontend/src/views/JobDetail.vue @@ -0,0 +1,108 @@ + + + + \ No newline at end of file diff --git a/frontend/src/views/JobList.vue b/frontend/src/views/JobList.vue new file mode 100644 index 0000000..bc833f8 --- /dev/null +++ b/frontend/src/views/JobList.vue @@ -0,0 +1,31 @@ + + + + + \ No newline at end of file diff --git a/frontend/src/views/Login.vue b/frontend/src/views/Login.vue new file mode 100644 index 0000000..0fa47b2 --- /dev/null +++ b/frontend/src/views/Login.vue @@ -0,0 +1,68 @@ + + + \ No newline at end of file diff --git a/frontend/src/views/Register.vue b/frontend/src/views/Register.vue new file mode 100644 index 0000000..4f28c8c --- /dev/null +++ b/frontend/src/views/Register.vue @@ -0,0 +1,110 @@ +