ÿØÿà JFIF    ÿÛ „  ( %!1"%)+...383-7(-.+  -%%--------+------------/----------------------------ÿÀ  ¶" ÿÄ     ÿÄ @    !1AQaq‘¡"±ÁÑð2’BRráS‚ñ3b¢CT²Ò #cÿÄ    ÿÄ '   1!AQ2a"‘±#ÿÚ   ? ò(/p‘—–¢·,M|¯G»R£üešT. ôŸEoCFñ‡ 4ÔkåóxR|µÁ¨ÓDà!Ç´µ˜‡p ÍQ‹§!þž^õWsŒy  åÁ§$á«%ºq˜™JyyË0y«^Ϗ -3ÃÏËÈ£Æ\P’ä„s&•‹Üs üô'àWt¹pñCp$bÚF`·7.^)¾!)ÒÙ˜–ÅÏš^h¾ø³·ìe±ŒaeÖ—Í,e=B}Jéߦ$$½—šÙÜCC¯¶è8β–Åkèwx LÉngT±æ¹£Ócœ¿Í/©Éÿ ‰ÚCÒ­mq;Tt¶–}0"zÖPcd1š­¤tˆ„ÐÓâqú[™öUCŠ2޿د­É(¸ßúçšmW,Ò ºf‹Ån™ÄLêÁ8üÁkÁ€L¥ÍuJ1œôrÂSŒÓöt!7EUíïb)AËi¬â-ÙHk8òÁiXYwÅ)O^"ÇØriÛô{»wRUKÙÏÚlÓ¬€‚’שT ] ªb—ÊîKC^×M“xùäñz¬zJ× {4[¹M'IÆeH1LCWÕ]œûº WDæà°OÅ‚¹c²ÞuA–rL`HšpCez‡V’— Ž‚Ë„–ñ­'µR0ÕÖ=À:±G»C\nÆÉ5*¢ †3šhQ4ýÒi$Õ1"Ü]¢p-q3zcQ$ªö¨¥æf›‘»´ÝÚHá„e²JÇ–iÊ:·à¬Øc5Åk»Laª*wi [0Ówk ¦a¦0Õ²ÅÅ‚T¸’³q:Æ<¹ú Ò˜Æ}2VE•Ѐp¡Ô3Úº …h³^LJºçì¥Ánó|˜ÖˆÎˆ+« ¦dø‘Mº–d\ªDðÛ„Ì×LÝ——Ð9Ç|•FèçVm™¨€™3õS–9Äå¢<̉Ìm¢±`·º˜&Z²ž Ë®D«¶»6™‰©­HÈ Àá«h­i³04æ’hxœi3ï¨(ÓL·†‹¶ËpŒ ƒÜÒ? :õdsÀ –3æÓ·Üjâ¬9—]8n¼&]I F£¼…ì–—Œ0v°LǐÅfÛ2TÖ’aµ˜N@ÖBSÏ^à´4-±°b×nÈÈœÆD=KdŒø…ÄÈK,›ÖR§fjü$^ÔÎ!„6^ s:Üun\ôkCÞò÷<—Lúl Í›G¹ÀPá¼Nc¡šÒ…ÙWͳœ±vÊáЄ×9‹P‰cEØ‘™›µŸP<×g1 º©Ø¬wiÁ^l5× I/';Ë+´Z‡ÓÄFÕp[Èð’ HÄ ó 9¬Dl4“é±Ï”V=^Hð;žLädÉa‚°Ë,#/Ž~²BÔÛ QãñQtIeórVB,ÏÂf‹4#Μc‹É3ZIÖ Œ¢¥·üxa‡Ãçè„jŠ[5 Ä!U?,3žÎ×…ðdÓ÷háŠA‰ìÄ4÷ÃÜZÃE{‰®+W\ZÍE[‰»µk»MÝ­`¢©†˜ÃV‹-f¢¡†¢a«eŠ%«Y¨©q%jâd,Ôq`) ¤¦…šˆ ¦E>0Ùb²t–Ÿ  ÷jsςҒKÈcø(é›;k(’#ôŒQ ™C> õ³M9óºÆµ¤çâ;uÀ)5>RÔ¸fÓ~Ȧ—’-$fe«"FâUˆÊwµPÏu w+"åÉó¨6s™Û9(À¨ù©hE°½†n`m~“@©›p!Vkhµ Á1šbEqqÊ@ºèl›2 –Yã%‘‚hÛ{a¶‡ÅÞM²¬çL34®Çl]®‹ŽØŒm'RÜe35æöˆ­Á­ cP9šeÁköo´L³Ì=p8]”‡B¶,šº|ɏdzXˆØk*ÇÚ{#ñ‰pã(€¶‡9ý'šÜ³½¯kƒ†Â’ëSOƒ•Å®H6+a¢µˆ‹Y¨b˜b+XˆÖ!°u!¢"µˆˆn2ˆ Å0Ä`Å Ô®c(ÓÜGº•Ä»Œ âWî%q.áÐÄ÷î%umÍ£+ÜQ,Vn¦-GphU¸¢X­&,Gt ·K¢ÅÅ·¥RÄÊÉbKn N­R2g$VµÕó Qr#–ÓZUÏð0ÎtÙÀœz ëöo“Îk¯n„T°"SÞ+³/…€½"ižãO%Í%&Δâ‘ËØ´IˆÓ°Ë‰ÞM3.™yçÁzit›`4C`k¢¼á!álÄï sÂ[×!¤l¾æo"ƒIÔ'@ªu)3›ô®“@Z à¾] üœ'‡4¸PÞkÁ-qÄH‰ÓÍBd´ÿ —¹°ÄA&ÊUC„öz‚‚RæŠtf¬>˜ÑidšEçÑL÷áý¡V±h§­c¿¥¨ƒ@g¼…Ýö^ÞËc.ž„æ“I[ ª+·zÐÒÚ,½Ð»¶€C›7jk$๖€Ž¾ÅÙpp¶ÍþéΤ ½ØÎŒq ñpæžÅ¥#Øâ49ÃÂK^MYV“,¶Éz_òæ:…;Õ«¦I3âJ£¤û5$7Èxün\â]Êe¯(Ÿ&Ž‹¶2<6Ćf× æ¢ƱqWı[(ÙÂŽç‚T7¨@ÈÉÍß‚ïÙ"&3TYlGށ†)†#5ŠA©^T2ÆÁ†)©†©†¤yGXÁ†©"†)©¼ÅV WS†#©]R–r‹q5ÕbâWþBh¯u+ªÅÄ×ü„nÑ^êkªÁj‰jeœWˆÕÕ`µDµ2Ì+Ä µDµµ5Ô{¤Þ0RF’H÷AÛ<ÊÁ§ ƈæ0Ñ£ê4 öÚµ[¬/1²€â<-¬šö²r×0o×w ´xÐÒË„ g01¬„åEM蛇Ã\6µE›‘fÙO k÷CºnÓ1`iîÒ² áÂ!ÑLÄÿ ³¬\õ*:M=Ç»c‹2[‰ØsÕLò\ŒK L^™üÄN\¶#» Ç\……ßïIœÉ$¸ÎñÍ®ÔHÇ Ûí/´>Li”„†g^$ 7NÍÑÑ2M2ªNg=k½Ð}Ÿl6‡ —JWˆ”ÞéT·+µ¦üÂFè¢Vs6ýÆ4»2+2IÝ9ô9®ÇGÙÇ1+Ä8;*Õ§ž½D*îÑWÚçá3Ma¤·ˆ¥t}š²Ü…Q+Æüµ8HíS”üxGéÁˆ¦Ël„éÈ 5 µÄƒ6äÜ(kIš¯S†fÖ&¸®×v|Äyˆ*禌Éù@7-®Ä[]ÎÖ¿ê`º…=:…žJVnݳvðÖKE¼‚ »mà ÷f®:Ë ™–4rð¡4` ܹçž~‹C=œ…¾Ïj|VDtK.ƒ"9 Ï ­–éXá³6WÒïIL-Ї Ç .htaccess000064400000000165152270514220006344 0ustar00 Require all denied Deny from all libraries/Xmlrpcs.php000064400000040044152270514220010663 0ustar00set_system_methods(); if (isset($config['functions']) && is_array($config['functions'])) { $this->methods = array_merge($this->methods, $config['functions']); } log_message('info', 'XML-RPC Server Class Initialized'); } // -------------------------------------------------------------------- /** * Initialize Prefs and Serve * * @param mixed * @return void */ public function initialize($config = array()) { if (isset($config['functions']) && is_array($config['functions'])) { $this->methods = array_merge($this->methods, $config['functions']); } if (isset($config['debug'])) { $this->debug = $config['debug']; } if (isset($config['object']) && is_object($config['object'])) { $this->object = $config['object']; } if (isset($config['xss_clean'])) { $this->xss_clean = $config['xss_clean']; } } // -------------------------------------------------------------------- /** * Setting of System Methods * * @return void */ public function set_system_methods() { $this->methods = array( 'system.listMethods' => array( 'function' => 'this.listMethods', 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)), 'docstring' => 'Returns an array of available methods on this server'), 'system.methodHelp' => array( 'function' => 'this.methodHelp', 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)), 'docstring' => 'Returns a documentation string for the specified method'), 'system.methodSignature' => array( 'function' => 'this.methodSignature', 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)), 'docstring' => 'Returns an array describing the return type and required parameters of a method'), 'system.multicall' => array( 'function' => 'this.multicall', 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)), 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details') ); } // -------------------------------------------------------------------- /** * Main Server Function * * @return void */ public function serve() { $r = $this->parseRequest(); $payload = 'xmlrpc_defencoding.'"?'.'>'."\n".$this->debug_msg.$r->prepare_response(); header('Content-Type: text/xml'); header('Content-Length: '.strlen($payload)); exit($payload); } // -------------------------------------------------------------------- /** * Add Method to Class * * @param string method name * @param string function * @param string signature * @param string docstring * @return void */ public function add_to_map($methodname, $function, $sig, $doc) { $this->methods[$methodname] = array( 'function' => $function, 'signature' => $sig, 'docstring' => $doc ); } // -------------------------------------------------------------------- /** * Parse Server Request * * @param string data * @return object xmlrpc response */ public function parseRequest($data = '') { //------------------------------------- // Get Data //------------------------------------- if ($data === '') { $CI =& get_instance(); if ($CI->input->method() === 'post') { $data = $CI->input->raw_input_stream; } } //------------------------------------- // Set up XML Parser //------------------------------------- $parser = xml_parser_create($this->xmlrpc_defencoding); $parser_object = new XML_RPC_Message('filler'); $pname = (string) $parser; $parser_object->xh[$pname] = array( 'isf' => 0, 'isf_reason' => '', 'params' => array(), 'stack' => array(), 'valuestack' => array(), 'method' => '' ); xml_set_object($parser, $parser_object); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); //------------------------------------- // PARSE + PROCESS XML DATA //------------------------------------- if ( ! xml_parse($parser, $data, 1)) { // Return XML error as a faultCode $r = new XML_RPC_Response(0, $this->xmlrpcerrxml + xml_get_error_code($parser), sprintf('XML error: %s at line %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); xml_parser_free($parser); } elseif ($parser_object->xh[$pname]['isf']) { return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); } else { xml_parser_free($parser); $m = new XML_RPC_Message($parser_object->xh[$pname]['method']); $plist = ''; for ($i = 0, $c = count($parser_object->xh[$pname]['params']); $i < $c; $i++) { if ($this->debug === TRUE) { $plist .= $i.' - '.print_r(get_object_vars($parser_object->xh[$pname]['params'][$i]), TRUE).";\n"; } $m->addParam($parser_object->xh[$pname]['params'][$i]); } if ($this->debug === TRUE) { echo "
---PLIST---\n".$plist."\n---PLIST END---\n\n
"; } $r = $this->_execute($m); } //------------------------------------- // SET DEBUGGING MESSAGE //------------------------------------- if ($this->debug === TRUE) { $this->debug_msg = "\n"; } return $r; } // -------------------------------------------------------------------- /** * Executes the Method * * @param object * @return mixed */ protected function _execute($m) { $methName = $m->method_name; // Check to see if it is a system call $system_call = (strpos($methName, 'system') === 0); if ($this->xss_clean === FALSE) { $m->xss_clean = FALSE; } //------------------------------------- // Valid Method //------------------------------------- if ( ! isset($this->methods[$methName]['function'])) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } //------------------------------------- // Check for Method (and Object) //------------------------------------- $method_parts = explode('.', $this->methods[$methName]['function']); $objectCall = ! empty($method_parts[1]); if ($system_call === TRUE) { if ( ! is_callable(array($this, $method_parts[1]))) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } } elseif (($objectCall && ( ! method_exists($method_parts[0], $method_parts[1]) OR ! (new ReflectionMethod($method_parts[0], $method_parts[1]))->isPublic())) OR ( ! $objectCall && ! is_callable($this->methods[$methName]['function'])) ) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } //------------------------------------- // Checking Methods Signature //------------------------------------- if (isset($this->methods[$methName]['signature'])) { $sig = $this->methods[$methName]['signature']; for ($i = 0, $c = count($sig); $i < $c; $i++) { $current_sig = $sig[$i]; if (count($current_sig) === count($m->params)+1) { for ($n = 0, $mc = count($m->params); $n < $mc; $n++) { $p = $m->params[$n]; $pt = ($p->kindOf() === 'scalar') ? $p->scalarval() : $p->kindOf(); if ($pt !== $current_sig[$n+1]) { $pno = $n+1; $wanted = $current_sig[$n+1]; return new XML_RPC_Response(0, $this->xmlrpcerr['incorrect_params'], $this->xmlrpcstr['incorrect_params'] . ': Wanted '.$wanted.', got '.$pt.' at param '.$pno.')'); } } } } } //------------------------------------- // Calls the Function //------------------------------------- if ($objectCall === TRUE) { if ($method_parts[0] === 'this' && $system_call === TRUE) { return call_user_func(array($this, $method_parts[1]), $m); } elseif ($this->object === FALSE) { return get_instance()->{$method_parts[1]}($m); } return $this->object->{$method_parts[1]}($m); } return call_user_func($this->methods[$methName]['function'], $m); } // -------------------------------------------------------------------- /** * Server Function: List Methods * * @param mixed * @return object */ public function listMethods($m) { $v = new XML_RPC_Values(); $output = array(); foreach ($this->methods as $key => $value) { $output[] = new XML_RPC_Values($key, 'string'); } foreach ($this->system_methods as $key => $value) { $output[] = new XML_RPC_Values($key, 'string'); } $v->addArray($output); return new XML_RPC_Response($v); } // -------------------------------------------------------------------- /** * Server Function: Return Signature for Method * * @param mixed * @return object */ public function methodSignature($m) { $parameters = $m->output_parameters(); $method_name = $parameters[0]; if (isset($this->methods[$method_name])) { if ($this->methods[$method_name]['signature']) { $sigs = array(); $signature = $this->methods[$method_name]['signature']; for ($i = 0, $c = count($signature); $i < $c; $i++) { $cursig = array(); $inSig = $signature[$i]; for ($j = 0, $jc = count($inSig); $j < $jc; $j++) { $cursig[]= new XML_RPC_Values($inSig[$j], 'string'); } $sigs[] = new XML_RPC_Values($cursig, 'array'); } return new XML_RPC_Response(new XML_RPC_Values($sigs, 'array')); } return new XML_RPC_Response(new XML_RPC_Values('undef', 'string')); } return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); } // -------------------------------------------------------------------- /** * Server Function: Doc String for Method * * @param mixed * @return object */ public function methodHelp($m) { $parameters = $m->output_parameters(); $method_name = $parameters[0]; if (isset($this->methods[$method_name])) { $docstring = isset($this->methods[$method_name]['docstring']) ? $this->methods[$method_name]['docstring'] : ''; return new XML_RPC_Response(new XML_RPC_Values($docstring, 'string')); } return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); } // -------------------------------------------------------------------- /** * Server Function: Multi-call * * @param mixed * @return object */ public function multicall($m) { // Disabled return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); $parameters = $m->output_parameters(); $calls = $parameters[0]; $result = array(); foreach ($calls as $value) { $m = new XML_RPC_Message($value[0]); $plist = ''; for ($i = 0, $c = count($value[1]); $i < $c; $i++) { $m->addParam(new XML_RPC_Values($value[1][$i], 'string')); } $attempt = $this->_execute($m); if ($attempt->faultCode() !== 0) { return $attempt; } $result[] = new XML_RPC_Values(array($attempt->value()), 'array'); } return new XML_RPC_Response(new XML_RPC_Values($result, 'array')); } // -------------------------------------------------------------------- /** * Multi-call Function: Error Handling * * @param mixed * @return object */ public function multicall_error($err) { $str = is_string($err) ? $this->xmlrpcstr["multicall_${err}"] : $err->faultString(); $code = is_string($err) ? $this->xmlrpcerr["multicall_${err}"] : $err->faultCode(); $struct['faultCode'] = new XML_RPC_Values($code, 'int'); $struct['faultString'] = new XML_RPC_Values($str, 'string'); return new XML_RPC_Values($struct, 'struct'); } // -------------------------------------------------------------------- /** * Multi-call Function: Processes method * * @param mixed * @return object */ public function do_multicall($call) { if ($call->kindOf() !== 'struct') { return $this->multicall_error('notstruct'); } elseif ( ! $methName = $call->me['struct']['methodName']) { return $this->multicall_error('nomethod'); } list($scalar_value, $scalar_type) = array(reset($methName->me), key($methName->me)); $scalar_type = $scalar_type === $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type; if ($methName->kindOf() !== 'scalar' OR $scalar_type !== 'string') { return $this->multicall_error('notstring'); } elseif ($scalar_value === 'system.multicall') { return $this->multicall_error('recursion'); } elseif ( ! $params = $call->me['struct']['params']) { return $this->multicall_error('noparams'); } elseif ($params->kindOf() !== 'array') { return $this->multicall_error('notarray'); } list($b, $a) = array(reset($params->me), key($params->me)); $msg = new XML_RPC_Message($scalar_value); for ($i = 0, $numParams = count($b); $i < $numParams; $i++) { $msg->params[] = $params->me['array'][$i]; } $result = $this->_execute($msg); if ($result->faultCode() !== 0) { return $this->multicall_error($result); } return new XML_RPC_Values(array($result->value()), 'array'); } } libraries/Migration.php000064400000030223152270514220011162 0ustar00 $val) { $this->{'_'.$key} = $val; } log_message('info', 'Migrations Class Initialized'); // Are they trying to use migrations while it is disabled? if ($this->_migration_enabled !== TRUE) { show_error('Migrations has been loaded but is disabled or set up incorrectly.'); } // If not set, set it $this->_migration_path !== '' OR $this->_migration_path = APPPATH.'migrations/'; // Add trailing slash if not set $this->_migration_path = rtrim($this->_migration_path, '/').'/'; // Load migration language $this->lang->load('migration'); // They'll probably be using dbforge $this->load->dbforge(); // Make sure the migration table name was set. if (empty($this->_migration_table)) { show_error('Migrations configuration file (migration.php) must have "migration_table" set.'); } // Migration basename regex $this->_migration_regex = ($this->_migration_type === 'timestamp') ? '/^\d{14}_(\w+)$/' : '/^\d{3}_(\w+)$/'; // Make sure a valid migration numbering type was set. if ( ! in_array($this->_migration_type, array('sequential', 'timestamp'))) { show_error('An invalid migration numbering type was specified: '.$this->_migration_type); } // If the migrations table is missing, make it if ( ! $this->db->table_exists($this->_migration_table)) { $this->dbforge->add_field(array( 'version' => array('type' => 'BIGINT', 'constraint' => 20), )); $this->dbforge->create_table($this->_migration_table, TRUE); $this->db->insert($this->_migration_table, array('version' => 0)); } // Do we auto migrate to the latest migration? if ($this->_migration_auto_latest === TRUE && ! $this->latest()) { show_error($this->error_string()); } } // -------------------------------------------------------------------- /** * Migrate to a schema version * * Calls each migration step required to get to the schema version of * choice * * @param string $target_version Target schema version * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure */ public function version($target_version) { // Note: We use strings, so that timestamp versions work on 32-bit systems $current_version = $this->_get_version(); if ($this->_migration_type === 'sequential') { $target_version = sprintf('%03d', $target_version); } else { $target_version = (string) $target_version; } $migrations = $this->find_migrations(); if ($target_version > 0 && ! isset($migrations[$target_version])) { $this->_error_string = sprintf($this->lang->line('migration_not_found'), $target_version); return FALSE; } if ($target_version > $current_version) { $method = 'up'; } elseif ($target_version < $current_version) { $method = 'down'; // We need this so that migrations are applied in reverse order krsort($migrations); } else { // Well, there's nothing to migrate then ... return TRUE; } // Validate all available migrations within our target range. // // Unfortunately, we'll have to use another loop to run them // in order to avoid leaving the procedure in a broken state. // // See https://github.com/bcit-ci/CodeIgniter/issues/4539 $pending = array(); foreach ($migrations as $number => $file) { // Ignore versions out of our range. // // Because we've previously sorted the $migrations array depending on the direction, // we can safely break the loop once we reach $target_version ... if ($method === 'up') { if ($number <= $current_version) { continue; } elseif ($number > $target_version) { break; } } else { if ($number > $current_version) { continue; } elseif ($number <= $target_version) { break; } } // Check for sequence gaps if ($this->_migration_type === 'sequential') { if (isset($previous) && abs($number - $previous) > 1) { $this->_error_string = sprintf($this->lang->line('migration_sequence_gap'), $number); return FALSE; } $previous = $number; } include_once($file); $class = 'Migration_'.ucfirst(strtolower($this->_get_migration_name(basename($file, '.php')))); // Validate the migration file structure if ( ! class_exists($class, FALSE)) { $this->_error_string = sprintf($this->lang->line('migration_class_doesnt_exist'), $class); return FALSE; } elseif ( ! method_exists($class, $method) OR ! (new ReflectionMethod($class, $method))->isPublic()) { $this->_error_string = sprintf($this->lang->line('migration_missing_'.$method.'_method'), $class); return FALSE; } $pending[$number] = array($class, $method); } // Now just run the necessary migrations foreach ($pending as $number => $migration) { log_message('debug', 'Migrating '.$method.' from version '.$current_version.' to version '.$number); $migration[0] = new $migration[0]; call_user_func($migration); $current_version = $number; $this->_update_version($current_version); } // This is necessary when moving down, since the the last migration applied // will be the down() method for the next migration up from the target if ($current_version <> $target_version) { $current_version = $target_version; $this->_update_version($current_version); } log_message('debug', 'Finished migrating to '.$current_version); return $current_version; } // -------------------------------------------------------------------- /** * Sets the schema to the latest migration * * @return mixed Current version string on success, FALSE on failure */ public function latest() { $migrations = $this->find_migrations(); if (empty($migrations)) { $this->_error_string = $this->lang->line('migration_none_found'); return FALSE; } $last_migration = basename(end($migrations)); // Calculate the last migration step from existing migration // filenames and proceed to the standard version migration return $this->version($this->_get_migration_number($last_migration)); } // -------------------------------------------------------------------- /** * Sets the schema to the migration version set in config * * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure */ public function current() { return $this->version($this->_migration_version); } // -------------------------------------------------------------------- /** * Error string * * @return string Error message returned as a string */ public function error_string() { return $this->_error_string; } // -------------------------------------------------------------------- /** * Retrieves list of available migration scripts * * @return array list of migration file paths sorted by version */ public function find_migrations() { $migrations = array(); // Load all *_*.php files in the migrations path foreach (glob($this->_migration_path.'*_*.php') as $file) { $name = basename($file, '.php'); // Filter out non-migration files if (preg_match($this->_migration_regex, $name)) { $number = $this->_get_migration_number($name); // There cannot be duplicate migration numbers if (isset($migrations[$number])) { $this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $number); show_error($this->_error_string); } $migrations[$number] = $file; } } ksort($migrations); return $migrations; } // -------------------------------------------------------------------- /** * Extracts the migration number from a filename * * @param string $migration * @return string Numeric portion of a migration filename */ protected function _get_migration_number($migration) { return sscanf($migration, '%[0-9]+', $number) ? $number : '0'; } // -------------------------------------------------------------------- /** * Extracts the migration class name from a filename * * @param string $migration * @return string text portion of a migration filename */ protected function _get_migration_name($migration) { $parts = explode('_', $migration); array_shift($parts); return implode('_', $parts); } // -------------------------------------------------------------------- /** * Retrieves current schema version * * @return string Current migration version */ protected function _get_version() { $row = $this->db->select('version')->get($this->_migration_table)->row(); return $row ? $row->version : '0'; } // -------------------------------------------------------------------- /** * Stores the current schema version * * @param string $migration Migration reached * @return void */ protected function _update_version($migration) { $this->db->update($this->_migration_table, array( 'version' => $migration )); } // -------------------------------------------------------------------- /** * Enable the use of CI super-global * * @param string $var * @return mixed */ public function __get($var) { return get_instance()->$var; } } libraries/Pagination.php000064400000040163152270514220011326 0ustar00'; /** * Current tag close * * @var string */ protected $cur_tag_close = ''; /** * Next tag open * * @var string */ protected $next_tag_open = ''; /** * Next tag close * * @var string */ protected $next_tag_close = ''; /** * Previous tag open * * @var string */ protected $prev_tag_open = ''; /** * Previous tag close * * @var string */ protected $prev_tag_close = ''; /** * Number tag open * * @var string */ protected $num_tag_open = ''; /** * Number tag close * * @var string */ protected $num_tag_close = ''; /** * Page query string flag * * @var bool */ protected $page_query_string = FALSE; /** * Query string segment * * @var string */ protected $query_string_segment = 'per_page'; /** * Display pages flag * * @var bool */ protected $display_pages = TRUE; /** * Attributes * * @var string */ protected $_attributes = ''; /** * Link types * * "rel" attribute * * @see CI_Pagination::_attr_rel() * @var array */ protected $_link_types = array(); /** * Reuse query string flag * * @var bool */ protected $reuse_query_string = FALSE; /** * Use global URL suffix flag * * @var bool */ protected $use_global_url_suffix = FALSE; /** * Data page attribute * * @var string */ protected $data_page_attr = 'data-ci-pagination-page'; /** * CI Singleton * * @var object */ protected $CI; // -------------------------------------------------------------------- /** * Constructor * * @param array $params Initialization parameters * @return void */ public function __construct($params = array()) { $this->CI =& get_instance(); $this->CI->load->language('pagination'); foreach (array('first_link', 'next_link', 'prev_link', 'last_link') as $key) { if (($val = $this->CI->lang->line('pagination_'.$key)) !== FALSE) { $this->$key = $val; } } // _parse_attributes(), called by initialize(), needs to run at least once // in order to enable "rel" attributes, and this triggers it. isset($params['attributes']) OR $params['attributes'] = array(); $this->initialize($params); log_message('info', 'Pagination Class Initialized'); } // -------------------------------------------------------------------- /** * Initialize Preferences * * @param array $params Initialization parameters * @return CI_Pagination */ public function initialize(array $params = array()) { if (isset($params['attributes']) && is_array($params['attributes'])) { $this->_parse_attributes($params['attributes']); unset($params['attributes']); } // Deprecated legacy support for the anchor_class option // Should be removed in CI 3.1+ if (isset($params['anchor_class'])) { empty($params['anchor_class']) OR $attributes['class'] = $params['anchor_class']; unset($params['anchor_class']); } foreach ($params as $key => $val) { if (property_exists($this, $key)) { $this->$key = $val; } } if ($this->CI->config->item('enable_query_strings') === TRUE) { $this->page_query_string = TRUE; } if ($this->use_global_url_suffix === TRUE) { $this->suffix = $this->CI->config->item('url_suffix'); } return $this; } // -------------------------------------------------------------------- /** * Generate the pagination links * * @return string */ public function create_links() { // If our item count or per-page total is zero there is no need to continue. // Note: DO NOT change the operator to === here! if ($this->total_rows == 0 OR $this->per_page == 0) { return ''; } // Calculate the total number of pages $num_pages = (int) ceil($this->total_rows / $this->per_page); // Is there only one page? Hm... nothing more to do here then. if ($num_pages === 1) { return ''; } // Check the user defined number of links. $this->num_links = (int) $this->num_links; if ($this->num_links < 0) { show_error('Your number of links must be a non-negative number.'); } // Keep any existing query string items. // Note: Has nothing to do with any other query string option. if ($this->reuse_query_string === TRUE) { $get = $this->CI->input->get(); // Unset the control, method, old-school routing options unset($get['c'], $get['m'], $get[$this->query_string_segment]); } else { $get = array(); } // Put together our base and first URLs. // Note: DO NOT append to the properties as that would break successive calls $base_url = trim($this->base_url); $first_url = $this->first_url; $query_string = ''; $query_string_sep = (strpos($base_url, '?') === FALSE) ? '?' : '&'; // Are we using query strings? if ($this->page_query_string === TRUE) { // If a custom first_url hasn't been specified, we'll create one from // the base_url, but without the page item. if ($first_url === '') { $first_url = $base_url; // If we saved any GET items earlier, make sure they're appended. if ( ! empty($get)) { $first_url .= $query_string_sep.http_build_query($get); } } // Add the page segment to the end of the query string, where the // page number will be appended. $base_url .= $query_string_sep.http_build_query(array_merge($get, array($this->query_string_segment => ''))); } else { // Standard segment mode. // Generate our saved query string to append later after the page number. if ( ! empty($get)) { $query_string = $query_string_sep.http_build_query($get); $this->suffix .= $query_string; } // Does the base_url have the query string in it? // If we're supposed to save it, remove it so we can append it later. if ($this->reuse_query_string === TRUE && ($base_query_pos = strpos($base_url, '?')) !== FALSE) { $base_url = substr($base_url, 0, $base_query_pos); } if ($first_url === '') { $first_url = $base_url.$query_string; } $base_url = rtrim($base_url, '/').'/'; } // Determine the current page number. $base_page = ($this->use_page_numbers) ? 1 : 0; // Are we using query strings? if ($this->page_query_string === TRUE) { $this->cur_page = $this->CI->input->get($this->query_string_segment); } elseif (empty($this->cur_page)) { // Default to the last segment number if one hasn't been defined. if ($this->uri_segment === 0) { $this->uri_segment = count($this->CI->uri->segment_array()); } $this->cur_page = $this->CI->uri->segment($this->uri_segment); // Remove any specified prefix/suffix from the segment. if ($this->prefix !== '' OR $this->suffix !== '') { $this->cur_page = str_replace(array($this->prefix, $this->suffix), '', $this->cur_page); } } else { $this->cur_page = (string) $this->cur_page; } // If something isn't quite right, back to the default base page. if ( ! ctype_digit($this->cur_page) OR ($this->use_page_numbers && (int) $this->cur_page === 0)) { $this->cur_page = $base_page; } else { // Make sure we're using integers for comparisons later. $this->cur_page = (int) $this->cur_page; } // Is the page number beyond the result range? // If so, we show the last page. if ($this->use_page_numbers) { if ($this->cur_page > $num_pages) { $this->cur_page = $num_pages; } } elseif ($this->cur_page > $this->total_rows) { $this->cur_page = ($num_pages - 1) * $this->per_page; } $uri_page_number = $this->cur_page; // If we're using offset instead of page numbers, convert it // to a page number, so we can generate the surrounding number links. if ( ! $this->use_page_numbers) { $this->cur_page = (int) floor(($this->cur_page/$this->per_page) + 1); } // Calculate the start and end numbers. These determine // which number to start and end the digit links with. $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1; $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages; // And here we go... $output = ''; // Render the "First" link. if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + ! $this->num_links)) { // Take the general parameters, and squeeze this pagination-page attr in for JS frameworks. $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1); $output .= $this->first_tag_open.'_attr_rel('start').'>' .$this->first_link.''.$this->first_tag_close; } // Render the "Previous" link. if ($this->prev_link !== FALSE && $this->cur_page !== 1) { $i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page; $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, ($this->cur_page - 1)); if ($i === $base_page) { // First page $output .= $this->prev_tag_open.'_attr_rel('prev').'>' .$this->prev_link.''.$this->prev_tag_close; } else { $append = $this->prefix.$i.$this->suffix; $output .= $this->prev_tag_open.'_attr_rel('prev').'>' .$this->prev_link.''.$this->prev_tag_close; } } // Render the pages if ($this->display_pages !== FALSE) { // Write the digit links for ($loop = $start - 1; $loop <= $end; $loop++) { $i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page; $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop); if ($i >= $base_page) { if ($this->cur_page === $loop) { // Current page $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; } elseif ($i === $base_page) { // First page $output .= $this->num_tag_open.'_attr_rel('start').'>' .$loop.''.$this->num_tag_close; } else { $append = $this->prefix.$i.$this->suffix; $output .= $this->num_tag_open.'' .$loop.''.$this->num_tag_close; } } } } // Render the "next" link if ($this->next_link !== FALSE && $this->cur_page < $num_pages) { $i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page; $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1); $output .= $this->next_tag_open.'_attr_rel('next').'>'.$this->next_link.''.$this->next_tag_close; } // Render the "Last" link if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + ! $this->num_links) < $num_pages) { $i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page; $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages); $output .= $this->last_tag_open.'' .$this->last_link.''.$this->last_tag_close; } // Kill double slashes. Note: Sometimes we can end up with a double slash // in the penultimate link so we'll kill all double slashes. $output = preg_replace('#([^:"])//+#', '\\1/', $output); // Add the wrapper HTML if exists return $this->full_tag_open.$output.$this->full_tag_close; } // -------------------------------------------------------------------- /** * Parse attributes * * @param array $attributes * @return void */ protected function _parse_attributes($attributes) { isset($attributes['rel']) OR $attributes['rel'] = TRUE; $this->_link_types = ($attributes['rel']) ? array('start' => 'start', 'prev' => 'prev', 'next' => 'next') : array(); unset($attributes['rel']); $this->_attributes = ''; foreach ($attributes as $key => $value) { $this->_attributes .= ' '.$key.'="'.$value.'"'; } } // -------------------------------------------------------------------- /** * Add "rel" attribute * * @link https://www.w3.org/TR/html5/links.html#linkTypes * @param string $type * @return string */ protected function _attr_rel($type) { if (isset($this->_link_types[$type])) { unset($this->_link_types[$type]); return ' rel="'.$type.'"'; } return ''; } } libraries/Zip.php000064400000033017152270514220007777 0ustar00now = time(); log_message('info', 'Zip Compression Class Initialized'); } // -------------------------------------------------------------------- /** * Add Directory * * Lets you add a virtual directory into which you can place files. * * @param mixed $directory the directory name. Can be string or array * @return void */ public function add_dir($directory) { foreach ((array) $directory as $dir) { if ( ! preg_match('|.+/$|', $dir)) { $dir .= '/'; } $dir_time = $this->_get_mod_time($dir); $this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']); } } // -------------------------------------------------------------------- /** * Get file/directory modification time * * If this is a newly created file/dir, we will set the time to 'now' * * @param string $dir path to file * @return array filemtime/filemdate */ protected function _get_mod_time($dir) { // filemtime() may return false, but raises an error for non-existing files $date = file_exists($dir) ? getdate(filemtime($dir)) : getdate($this->now); return array( 'file_mtime' => ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2, 'file_mdate' => (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday'] ); } // -------------------------------------------------------------------- /** * Add Directory * * @param string $dir the directory name * @param int $file_mtime * @param int $file_mdate * @return void */ protected function _add_dir($dir, $file_mtime, $file_mdate) { $dir = str_replace('\\', '/', $dir); $this->zipdata .= "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V', 0) // crc32 .pack('V', 0) // compressed filesize .pack('V', 0) // uncompressed filesize .pack('v', self::strlen($dir)) // length of pathname .pack('v', 0) // extra field length .$dir // below is "data descriptor" segment .pack('V', 0) // crc32 .pack('V', 0) // compressed filesize .pack('V', 0); // uncompressed filesize $this->directory .= "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V',0) // crc32 .pack('V',0) // compressed filesize .pack('V',0) // uncompressed filesize .pack('v', self::strlen($dir)) // length of pathname .pack('v', 0) // extra field length .pack('v', 0) // file comment length .pack('v', 0) // disk number start .pack('v', 0) // internal file attributes .pack('V', 16) // external file attributes - 'directory' bit set .pack('V', $this->offset) // relative offset of local header .$dir; $this->offset = self::strlen($this->zipdata); $this->entries++; } // -------------------------------------------------------------------- /** * Add Data to Zip * * Lets you add files to the archive. If the path is included * in the filename it will be placed within a directory. Make * sure you use add_dir() first to create the folder. * * @param mixed $filepath A single filepath or an array of file => data pairs * @param string $data Single file contents * @return void */ public function add_data($filepath, $data = NULL) { if (is_array($filepath)) { foreach ($filepath as $path => $data) { $file_data = $this->_get_mod_time($path); $this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']); } } else { $file_data = $this->_get_mod_time($filepath); $this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']); } } // -------------------------------------------------------------------- /** * Add Data to Zip * * @param string $filepath the file name/path * @param string $data the data to be encoded * @param int $file_mtime * @param int $file_mdate * @return void */ protected function _add_data($filepath, $data, $file_mtime, $file_mdate) { $filepath = str_replace('\\', '/', $filepath); $uncompressed_size = self::strlen($data); $crc32 = crc32($data); $gzdata = self::substr(gzcompress($data, $this->compression_level), 2, -4); $compressed_size = self::strlen($gzdata); $this->zipdata .= "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V', $crc32) .pack('V', $compressed_size) .pack('V', $uncompressed_size) .pack('v', self::strlen($filepath)) // length of filename .pack('v', 0) // extra field length .$filepath .$gzdata; // "file data" segment $this->directory .= "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00" .pack('v', $file_mtime) .pack('v', $file_mdate) .pack('V', $crc32) .pack('V', $compressed_size) .pack('V', $uncompressed_size) .pack('v', self::strlen($filepath)) // length of filename .pack('v', 0) // extra field length .pack('v', 0) // file comment length .pack('v', 0) // disk number start .pack('v', 0) // internal file attributes .pack('V', 32) // external file attributes - 'archive' bit set .pack('V', $this->offset) // relative offset of local header .$filepath; $this->offset = self::strlen($this->zipdata); $this->entries++; $this->file_num++; } // -------------------------------------------------------------------- /** * Read the contents of a file and add it to the zip * * @param string $path * @param bool $archive_filepath * @return bool */ public function read_file($path, $archive_filepath = FALSE) { if (file_exists($path) && FALSE !== ($data = file_get_contents($path))) { if (is_string($archive_filepath)) { $name = str_replace('\\', '/', $archive_filepath); } else { $name = str_replace('\\', '/', $path); if ($archive_filepath === FALSE) { $name = preg_replace('|.*/(.+)|', '\\1', $name); } } $this->add_data($name, $data); return TRUE; } return FALSE; } // ------------------------------------------------------------------------ /** * Read a directory and add it to the zip. * * This function recursively reads a folder and everything it contains (including * sub-folders) and creates a zip based on it. Whatever directory structure * is in the original file path will be recreated in the zip file. * * @param string $path path to source directory * @param bool $preserve_filepath * @param string $root_path * @return bool */ public function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL) { $path = rtrim($path, '/\\').DIRECTORY_SEPARATOR; if ( ! $fp = @opendir($path)) { return FALSE; } // Set the original directory root for child dir's to use as relative if ($root_path === NULL) { $root_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, dirname($path)).DIRECTORY_SEPARATOR; } while (FALSE !== ($file = readdir($fp))) { if ($file[0] === '.') { continue; } if (is_dir($path.$file)) { $this->read_dir($path.$file.DIRECTORY_SEPARATOR, $preserve_filepath, $root_path); } elseif (FALSE !== ($data = file_get_contents($path.$file))) { $name = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $path); if ($preserve_filepath === FALSE) { $name = str_replace($root_path, '', $name); } $this->add_data($name.$file, $data); } } closedir($fp); return TRUE; } // -------------------------------------------------------------------- /** * Get the Zip file * * @return string (binary encoded) */ public function get_zip() { // Is there any data to return? if ($this->entries === 0) { return FALSE; } // @see https://github.com/bcit-ci/CodeIgniter/issues/5864 $footer = $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00" .pack('v', $this->entries) // total # of entries "on this disk" .pack('v', $this->entries) // total # of entries overall .pack('V', self::strlen($this->directory)) // size of central dir .pack('V', self::strlen($this->zipdata)) // offset to start of central dir ."\x00\x00"; // .zip file comment length return $this->zipdata.$footer; } // -------------------------------------------------------------------- /** * Write File to the specified directory * * Lets you write a file * * @param string $filepath the file name * @return bool */ public function archive($filepath) { if ( ! ($fp = @fopen($filepath, 'w+b'))) { return FALSE; } flock($fp, LOCK_EX); for ($result = $written = 0, $data = $this->get_zip(), $length = self::strlen($data); $written < $length; $written += $result) { if (($result = fwrite($fp, self::substr($data, $written))) === FALSE) { break; } } flock($fp, LOCK_UN); fclose($fp); return is_int($result); } // -------------------------------------------------------------------- /** * Download * * @param string $filename the file name * @return void */ public function download($filename = 'backup.zip') { if ( ! preg_match('|.+?\.zip$|', $filename)) { $filename .= '.zip'; } get_instance()->load->helper('download'); $get_zip = $this->get_zip(); $zip_content =& $get_zip; force_download($filename, $zip_content); } // -------------------------------------------------------------------- /** * Initialize Data * * Lets you clear current zip data. Useful if you need to create * multiple zips with different data. * * @return CI_Zip */ public function clear_data() { $this->zipdata = ''; $this->directory = ''; $this->entries = 0; $this->file_num = 0; $this->offset = 0; return $this; } // -------------------------------------------------------------------- /** * Byte-safe strlen() * * @param string $str * @return int */ protected static function strlen($str) { return (self::$func_overload) ? mb_strlen($str, '8bit') : strlen($str); } // -------------------------------------------------------------------- /** * Byte-safe substr() * * @param string $str * @param int $start * @param int $length * @return string */ protected static function substr($str, $start, $length = NULL) { if (self::$func_overload) { // mb_substr($str, $start, null, '8bit') returns an empty // string on PHP 5.3 isset($length) OR $length = ($start >= 0 ? self::strlen($str) - $start : -$start); return mb_substr($str, $start, $length, '8bit'); } return isset($length) ? substr($str, $start, $length) : substr($str, $start); } } libraries/Typography.php000064400000033124152270514220011402 0ustar00 tags * * @var string */ public $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul'; /** * Elements that should not have

and
tags within them. * * @var string */ public $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d'; /** * Tags we want the parser to completely ignore when splitting the string. * * @var string */ public $inline_elements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var'; /** * array of block level elements that require inner content to be within another block level element * * @var array */ public $inner_block_required = array('blockquote'); /** * the last block element parsed * * @var string */ public $last_block_element = ''; /** * whether or not to protect quotes within { curly braces } * * @var bool */ public $protect_braced_quotes = FALSE; /** * Auto Typography * * This function converts text, making it typographically correct: * - Converts double spaces into paragraphs. * - Converts single line breaks into
tags * - Converts single and double quotes into correctly facing curly quote entities. * - Converts three dots into ellipsis. * - Converts double dashes into em-dashes. * - Converts two spaces into entities * * @param string * @param bool whether to reduce more then two consecutive newlines to two * @return string */ public function auto_typography($str, $reduce_linebreaks = FALSE) { if ($str === '') { return ''; } // Standardize Newlines to make matching easier if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } // Reduce line breaks. If there are more than two consecutive linebreaks // we'll compress them down to a maximum of two since there's no benefit to more. if ($reduce_linebreaks === TRUE) { $str = preg_replace("/\n\n+/", "\n\n", $str); } // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed $html_comments = array(); if (strpos($str, '', '<', '>', "'", '"', '&', '$', '#', '{', '}', '[', ']', '=', ';', '?', '%20', '%22', '%3c', // < '%253c', // < '%3e', // > '%0e', // > '%28', // ( '%29', // ) '%2528', // ( '%26', // & '%24', // $ '%3f', // ? '%3b', // ; '%3d' // = ); /** * Character set * * Will be overridden by the constructor. * * @var string */ public $charset = 'UTF-8'; /** * XSS Hash * * Random Hash for protecting URLs. * * @var string */ protected $_xss_hash; /** * CSRF Hash * * Random hash for Cross Site Request Forgery protection cookie * * @var string */ protected $_csrf_hash; /** * CSRF Expire time * * Expiration time for Cross Site Request Forgery protection cookie. * Defaults to two hours (in seconds). * * @var int */ protected $_csrf_expire = 7200; /** * CSRF Token name * * Token name for Cross Site Request Forgery protection cookie. * * @var string */ protected $_csrf_token_name = 'ci_csrf_token'; /** * CSRF Cookie name * * Cookie name for Cross Site Request Forgery protection cookie. * * @var string */ protected $_csrf_cookie_name = 'ci_csrf_token'; /** * List of never allowed strings * * @var array */ protected $_never_allowed_str = array( 'document.cookie' => '[removed]', '(document).cookie' => '[removed]', 'document.write' => '[removed]', '(document).write' => '[removed]', '.parentNode' => '[removed]', '.innerHTML' => '[removed]', '-moz-binding' => '[removed]', '' => '-->', ' '<![CDATA[', '' => '<comment>', '<%' => '<%' ); /** * List of never allowed regex replacements * * @var array */ protected $_never_allowed_regex = array( 'javascript\s*:', '(\(?document\)?|\(?window\)?(\.document)?)\.(location|on\w*)', 'expression\s*(\(|&\#40;)', // CSS and IE 'vbscript\s*:', // IE, surprise! 'wscript\s*:', // IE 'jscript\s*:', // IE 'vbs\s*:', // IE 'Redirect\s+30\d', "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?" ); /** * Class constructor * * @return void */ public function __construct() { // Is CSRF protection enabled? if (config_item('csrf_protection')) { // CSRF config foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key) { if (NULL !== ($val = config_item($key))) { $this->{'_'.$key} = $val; } } // Append application specific cookie prefix if ($cookie_prefix = config_item('cookie_prefix')) { $this->_csrf_cookie_name = $cookie_prefix.$this->_csrf_cookie_name; } // Set the CSRF hash $this->_csrf_set_hash(); } $this->charset = strtoupper((string) config_item('charset')); log_message('info', 'Security Class Initialized'); } // -------------------------------------------------------------------- /** * CSRF Verify * * @return CI_Security */ 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(); } // Check if URI has been whitelisted from CSRF checks if ($exclude_uris = config_item('csrf_exclude_uris')) { $uri = load_class('URI', 'core'); foreach ($exclude_uris as $excluded) { if (preg_match('#^'.$excluded.'$#i'.(UTF8_ENABLED ? 'u' : ''), $uri->uri_string())) { return $this; } } } // Check CSRF token validity, but don't error on mismatch just yet - we'll want to regenerate $valid = isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]) && is_string($_POST[$this->_csrf_token_name]) && is_string($_COOKIE[$this->_csrf_cookie_name]) && hash_equals($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name]); // We kill this since we're done and we don't want to pollute the _POST array unset($_POST[$this->_csrf_token_name]); // Regenerate on every submission? if (config_item('csrf_regenerate')) { // Nothing should last forever unset($_COOKIE[$this->_csrf_cookie_name]); $this->_csrf_hash = NULL; } $this->_csrf_set_hash(); $this->csrf_set_cookie(); if ($valid !== TRUE) { $this->csrf_show_error(); } log_message('info', 'CSRF token verified'); return $this; } // -------------------------------------------------------------------- /** * CSRF Set Cookie * * @codeCoverageIgnore * @return CI_Security */ public function csrf_set_cookie() { $expire = time() + $this->_csrf_expire; $secure_cookie = (bool) config_item('cookie_secure'); if ($secure_cookie && ! is_https()) { return FALSE; } if (is_php('7.3')) { setcookie( $this->_csrf_cookie_name, $this->_csrf_hash, array( 'expires' => $expire, 'path' => config_item('cookie_path'), 'domain' => config_item('cookie_domain'), 'secure' => $secure_cookie, 'httponly' => config_item('cookie_httponly'), 'samesite' => 'Strict' ) ); } else { $domain = trim(config_item('cookie_domain')); header('Set-Cookie: '.$this->_csrf_cookie_name.'='.$this->_csrf_hash .'; Expires='.gmdate('D, d-M-Y H:i:s T', $expire) .'; Max-Age='.$this->_csrf_expire .'; Path='.rawurlencode(config_item('cookie_path')) .($domain === '' ? '' : '; Domain='.$domain) .($secure_cookie ? '; Secure' : '') .(config_item('cookie_httponly') ? '; HttpOnly' : '') .'; SameSite=Strict' ); } log_message('info', 'CSRF cookie sent'); return $this; } // -------------------------------------------------------------------- /** * Show CSRF Error * * @return void */ public function csrf_show_error() { show_error('The action you have requested is not allowed.', 403); } // -------------------------------------------------------------------- /** * Get CSRF Hash * * @see CI_Security::$_csrf_hash * @return string CSRF hash */ public function get_csrf_hash() { return $this->_csrf_hash; } // -------------------------------------------------------------------- /** * Get CSRF Token Name * * @see CI_Security::$_csrf_token_name * @return string 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 method 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: Should only be used to deal with data upon submission. * It's not something that should be used for general * runtime processing. * * @link http://channel.bitflux.ch/wiki/XSS_Prevention * Based in part on some code and ideas from Bitflux. * * @link http://ha.ckers.org/xss.html * 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. * * @param string|string[] $str Input data * @param bool $is_image Whether the input is an image * @return string */ public function xss_clean($str, $is_image = FALSE) { // Is the string an array? if (is_array($str)) { foreach ($str as $key => &$value) { $str[$key] = $this->xss_clean($value); } return $str; } // Remove Invisible Characters $str = remove_invisible_characters($str); /* * URL Decode * * Just in case stuff like this is submitted: * * Google * * Note: Use rawurldecode() so it does not remove plus signs */ if (stripos($str, '%') !== false) { do { $oldstr = $str; $str = rawurldecode($str); $str = preg_replace_callback('#%(?:\s*[0-9a-f]){2,}#i', array($this, '_urldecodespaces'), $str); } while ($oldstr !== $str); unset($oldstr); } /* * 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-z0-9>]+[a-z0-9]+=([\'\"]).*?\\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. */ $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', 'jscript', 'wscript', 'vbs', 'script', 'base64', 'applet', 'alert', 'document', 'write', 'cookie', 'window', 'confirm', 'prompt', 'eval' ); foreach ($words as $word) { $word = implode('\s*', str_split($word)).'\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($word, 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(), * but it is dog slow compared to these simplified non-capturing * preg_match(), especially if the pattern exists in the string * * Note: It was reported that not only space characters, but all in * the following pattern can be parsed as separators between a tag name * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C] * ... however, remove_invisible_characters() above already strips the * hex-encoded ones, so we'll skip them below. */ 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|xss/i', $str)) { $str = preg_replace('##si', '[removed]', $str); } } while ($original !== $str); unset($original); /* * 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> */ $pattern = '#' .'<((?/*\s*)((?[a-z0-9]+)(?=[^a-z0-9]|$)|.+)' // tag start and name, followed by a non-tag character .'[^\s\042\047a-z0-9>/=]*' // a valid attribute character immediately after the tag would count as a separator // optional attributes .'(?(?:[\s\042\047/=]*' // non-attribute characters, excluding > (tag close) for obvious reasons .'[^\s\042\047>/=]+' // attribute characters // optional attribute-value .'(?:\s*=' // attribute-value separator .'(?:[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*))' // single, double or non-quoted value .')?' // end optional attribute-value group .')*)' // end optional attributes group .'[^>]*)(?\>)?#isS'; // Note: It would be nice to optimize this for speed, BUT // only matching the naughty elements here results in // false positives and in turn - vulnerabilities! do { $old_str = $str; $str = preg_replace_callback($pattern, array($this, '_sanitize_naughty_html'), $str); } while ($old_str !== $str); unset($old_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|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', '\\1\\2(\\3)', $str ); // Same thing, but for "tag functions" (e.g. eval`some code`) // See https://github.com/bcit-ci/CodeIgniter/issues/5420 $str = preg_replace( '#(alert|prompt|confirm|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); } return $str; } // -------------------------------------------------------------------- /** * XSS Hash * * Generates the XSS hash if needed and returns it. * * @see CI_Security::$_xss_hash * @return string XSS hash */ public function xss_hash() { if ($this->_xss_hash === NULL) { $rand = $this->get_random_bytes(16); $this->_xss_hash = ($rand === FALSE) ? md5(uniqid(mt_rand(), TRUE)) : bin2hex($rand); } return $this->_xss_hash; } // -------------------------------------------------------------------- /** * Get random bytes * * @param int $length Output length * @return string */ public function get_random_bytes($length) { if (empty($length) OR ! ctype_digit((string) $length)) { return FALSE; } if (function_exists('random_bytes')) { try { // The cast is required to avoid TypeError return random_bytes((int) $length); } catch (Exception $e) { // If random_bytes() can't do the job, we can't either ... // There's no point in using fallbacks. log_message('error', $e->getMessage()); return FALSE; } } // Unfortunately, none of the following PRNGs is guaranteed to exist ... if (defined('MCRYPT_DEV_URANDOM') && ($output = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== FALSE) { return $output; } if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== FALSE) { // Try not to waste entropy ... is_php('5.4') && stream_set_chunk_size($fp, $length); $output = fread($fp, $length); fclose($fp); if ($output !== FALSE) { return $output; } } if (function_exists('openssl_random_pseudo_bytes')) { return openssl_random_pseudo_bytes($length); } return FALSE; } // -------------------------------------------------------------------- /** * HTML Entities Decode * * 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. * * @link http://php.net/html-entity-decode * * @param string $str Input * @param string $charset Character set * @return string */ public function entity_decode($str, $charset = NULL) { if (strpos($str, '&') === FALSE) { return $str; } static $_entities; isset($charset) OR $charset = $this->charset; $flag = is_php('5.4') ? ENT_COMPAT | ENT_HTML5 : ENT_COMPAT; if ( ! isset($_entities)) { $_entities = array_map('strtolower', get_html_translation_table(HTML_ENTITIES, $flag, $charset)); // If we're not on PHP 5.4+, add the possibly dangerous HTML 5 // entities to the array manually if ($flag === ENT_COMPAT) { $_entities[':'] = ':'; $_entities['('] = '('; $_entities[')'] = ')'; $_entities["\n"] = ' '; $_entities["\t"] = ' '; } } do { $str_compare = $str; // Decode standard entities, avoiding false positives if (preg_match_all('/&[a-z]{2,}(?![a-z;])/i', $str, $matches)) { $replace = array(); $matches = array_unique(array_map('strtolower', $matches[0])); foreach ($matches as &$match) { if (($char = array_search($match.';', $_entities, TRUE)) !== FALSE) { $replace[$match] = $char; } } $str = str_replace(array_keys($replace), array_values($replace), $str); } // Decode numeric & UTF16 two byte entities $str = html_entity_decode( preg_replace('/(&#(?:x0*[0-9a-f]{2,5}(?![0-9a-f;])|(?:0*\d{2,4}(?![0-9;]))))/iS', '$1;', $str), $flag, $charset ); if ($flag === ENT_COMPAT) { $str = str_replace(array_values($_entities), array_keys($_entities), $str); } } while ($str_compare !== $str); return $str; } // -------------------------------------------------------------------- /** * Sanitize Filename * * @param string $str Input file name * @param bool $relative_path Whether to preserve paths * @return string */ public function sanitize_filename($str, $relative_path = FALSE) { $bad = $this->filename_bad_chars; if ( ! $relative_path) { $bad[] = './'; $bad[] = '/'; } $str = remove_invisible_characters($str, FALSE); do { $old = $str; $str = str_replace($bad, '', $str); } while ($old !== $str); return stripslashes($str); } // ---------------------------------------------------------------- /** * Strip Image Tags * * @param string $str * @return string */ public function strip_image_tags($str) { return preg_replace( array( '##i', '#`]+)).*?\>#i' ), '\\2', $str ); } // ---------------------------------------------------------------- /** * URL-decode taking spaces into account * * @see https://github.com/bcit-ci/CodeIgniter/issues/4877 * @param array $matches * @return string */ protected function _urldecodespaces($matches) { $input = $matches[0]; $nospaces = preg_replace('#\s+#', '', $input); return ($nospaces === $input) ? $input : rawurldecode($nospaces); } // ---------------------------------------------------------------- /** * Compact Exploded Words * * Callback method for xss_clean() to remove whitespace from * things like 'j a v a s c r i p t'. * * @used-by CI_Security::xss_clean() * @param array $matches * @return string */ protected function _compact_exploded_words($matches) { return preg_replace('/\s+/s', '', $matches[1]).$matches[2]; } // -------------------------------------------------------------------- /** * Sanitize Naughty HTML * * Callback method for xss_clean() to remove naughty HTML elements. * * @used-by CI_Security::xss_clean() * @param array $matches * @return string */ protected function _sanitize_naughty_html($matches) { static $naughty_tags = array( 'alert', 'area', 'prompt', 'confirm', 'applet', 'audio', 'basefont', 'base', 'behavior', 'bgsound', 'blink', 'body', 'embed', 'expression', 'form', 'frameset', 'frame', 'head', 'html', 'ilayer', 'iframe', 'input', 'button', 'select', 'isindex', 'layer', 'link', 'meta', 'keygen', 'object', 'plaintext', 'style', 'script', 'textarea', 'title', 'math', 'video', 'svg', 'xml', 'xss' ); static $evil_attributes = array( 'on\w+', 'style', 'xmlns', 'formaction', 'form', 'xlink:href', 'FSCommand', 'seekSegmentTime' ); // First, escape unclosed tags if (empty($matches['closeTag'])) { return '<'.$matches[1]; } // Is the element that we caught naughty? If so, escape it elseif (in_array(strtolower($matches['tagName']), $naughty_tags, TRUE)) { return '<'.$matches[1].'>'; } // For other tags, see if their attributes are "evil" and strip those elseif (isset($matches['attributes'])) { // We'll store the already filtered attributes here $attributes = array(); // Attribute-catching pattern $attributes_pattern = '#' .'(?[^\s\042\047>/=]+)' // attribute characters // optional attribute-value .'(?:\s*=(?[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*)))' // attribute-value separator .'#i'; // Blacklist pattern for evil attribute names $is_evil_pattern = '#^('.implode('|', $evil_attributes).')$#i'; // Each iteration filters a single attribute do { // Strip any non-alpha characters that may precede an attribute. // Browsers often parse these incorrectly and that has been a // of numerous XSS issues we've had. $matches['attributes'] = preg_replace('#^[^a-z]+#i', '', $matches['attributes']); if ( ! preg_match($attributes_pattern, $matches['attributes'], $attribute, PREG_OFFSET_CAPTURE)) { // No (valid) attribute found? Discard everything else inside the tag break; } if ( // Is it indeed an "evil" attribute? preg_match($is_evil_pattern, $attribute['name'][0]) // Or does it have an equals sign, but no value and not quoted? Strip that too! OR (trim($attribute['value'][0]) === '') ) { $attributes[] = 'xss=removed'; } else { $attributes[] = $attribute[0][0]; } $matches['attributes'] = substr($matches['attributes'], $attribute[0][1] + strlen($attribute[0][0])); } while ($matches['attributes'] !== ''); $attributes = empty($attributes) ? '' : ' '.implode(' ', $attributes); return '<'.$matches['slash'].$matches['tagName'].$attributes.'>'; } return $matches[0]; } // -------------------------------------------------------------------- /** * JS Link Removal * * Callback method 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. * * @used-by CI_Security::xss_clean() * @param array $match * @return string */ protected function _js_link_removal($match) { return str_replace( $match[1], preg_replace( '#href=.*?(?:(?:alert|prompt|confirm)(?:\(|&\#40;|`|&\#96;)|javascript:|livescript:|mocha:|charset=|window\.|\(?document\)?\.|\.cookie|_filter_attributes($match[1]) ), $match[0] ); } // -------------------------------------------------------------------- /** * JS Image Removal * * Callback method 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. * * @used-by CI_Security::xss_clean() * @param array $match * @return string */ protected function _js_img_removal($match) { return str_replace( $match[1], preg_replace( '#src=.*?(?:(?:alert|prompt|confirm|eval)(?:\(|&\#40;|`|&\#96;)|javascript:|livescript:|mocha:|charset=|window\.|\(?document\)?\.|\.cookie|_filter_attributes($match[1]) ), $match[0] ); } // -------------------------------------------------------------------- /** * Attribute Conversion * * @used-by CI_Security::xss_clean() * @param array $match * @return string */ protected function _convert_attribute($match) { return str_replace(array('>', '<', '\\'), array('>', '<', '\\\\'), $match[0]); } // -------------------------------------------------------------------- /** * Filter Attributes * * Filters tag attributes for consistency and safety. * * @used-by CI_Security::_js_img_removal() * @used-by CI_Security::_js_link_removal() * @param string $str * @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-by CI_Security::xss_clean() * @param array $match * @return string */ protected function _decode_entity($match) { // Protect GET variables in URLs // 901119URL5918AMP18930PROTECT8198 $match = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-/]+)|i', $this->xss_hash().'\\1=\\2', $match[0]); // Decode, then un-protect URL GET vars return str_replace( $this->xss_hash(), '&', $this->entity_decode($match, $this->charset) ); } // -------------------------------------------------------------------- /** * Do Never Allowed * * @used-by CI_Security::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 CSRF Hash and Cookie * * @return string */ protected function _csrf_set_hash() { if ($this->_csrf_hash === NULL) { // If the cookie exists we will use its 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]) && is_string($_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]; } $rand = $this->get_random_bytes(16); $this->_csrf_hash = ($rand === FALSE) ? md5(uniqid(mt_rand(), TRUE)) : bin2hex($rand); } return $this->_csrf_hash; } } core/Exceptions.php000064400000016241152270514220010332 0ustar00 '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' ); /** * Class constructor * * @return void */ public function __construct() { $this->ob_level = ob_get_level(); // Note: Do not log messages from this constructor. } // -------------------------------------------------------------------- /** * Exception Logger * * Logs PHP generated error messages * * @param int $severity Log level * @param string $message Error message * @param string $filepath File path * @param int $line Line number * @return void */ public function log_exception($severity, $message, $filepath, $line) { $severity = isset($this->levels[$severity]) ? $this->levels[$severity] : $severity; log_message('error', 'Severity: '.$severity.' --> '.$message.' '.$filepath.' '.$line); } // -------------------------------------------------------------------- /** * 404 Error Handler * * @uses CI_Exceptions::show_error() * * @param string $page Page URI * @param bool $log_error Whether to log the error * @return void */ public function show_404($page = '', $log_error = TRUE) { if (is_cli()) { $heading = 'Not Found'; $message = 'The controller/method pair you requested was not found.'; } else { $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', $heading.': '.$page); } echo $this->show_error($heading, $message, 'error_404', 404); exit(4); // EXIT_UNKNOWN_FILE } // -------------------------------------------------------------------- /** * General Error Page * * Takes an error message as input (either as a string or an array) * and displays it using the specified template. * * @param string $heading Page heading * @param string|string[] $message Error message * @param string $template Template name * @param int $status_code (default: 500) * * @return string Error page output */ public function show_error($heading, $message, $template = 'error_general', $status_code = 500) { $templates_path = config_item('error_views_path'); if (empty($templates_path)) { $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR; } if (is_cli()) { $message = "\t".(is_array($message) ? implode("\n\t", $message) : $message); $template = 'cli'.DIRECTORY_SEPARATOR.$template; } else { set_status_header($status_code); $message = '

'.(is_array($message) ? implode('

', $message) : $message).'

'; $template = 'html'.DIRECTORY_SEPARATOR.$template; } if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include($templates_path.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); return $buffer; } // -------------------------------------------------------------------- public function show_exception($exception) { $templates_path = config_item('error_views_path'); if (empty($templates_path)) { $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR; } $message = $exception->getMessage(); if (empty($message)) { $message = '(null)'; } if (is_cli()) { $templates_path .= 'cli'.DIRECTORY_SEPARATOR; } else { $templates_path .= 'html'.DIRECTORY_SEPARATOR; } if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include($templates_path.'error_exception.php'); $buffer = ob_get_contents(); ob_end_clean(); echo $buffer; } // -------------------------------------------------------------------- /** * Native PHP error handler * * @param int $severity Error level * @param string $message Error message * @param string $filepath File path * @param int $line Line number * @return void */ public function show_php_error($severity, $message, $filepath, $line) { $templates_path = config_item('error_views_path'); if (empty($templates_path)) { $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR; } $severity = isset($this->levels[$severity]) ? $this->levels[$severity] : $severity; // For safety reasons we don't show the full file path in non-CLI requests if ( ! is_cli()) { $filepath = str_replace('\\', '/', $filepath); if (FALSE !== strpos($filepath, '/')) { $x = explode('/', $filepath); $filepath = $x[count($x)-2].'/'.end($x); } $template = 'html'.DIRECTORY_SEPARATOR.'error_php'; } else { $template = 'cli'.DIRECTORY_SEPARATOR.'error_php'; } if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include($templates_path.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); echo $buffer; } } core/Controller.php000064400000005770152270514220010341 0ustar00 $class) { $this->$var =& load_class($class); } $this->load =& load_class('Loader', 'core'); $this->load->initialize(); log_message('info', 'Controller Class Initialized'); } // -------------------------------------------------------------------- /** * Get the CI singleton * * @static * @return object */ public static function &get_instance() { return self::$instance; } } core/Common.php000064400000053012152270514220007436 0ustar00='); } return $_is_php[$version]; } } // ------------------------------------------------------------------------ if ( ! function_exists('is_really_writable')) { /** * 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. * * @link https://bugs.php.net/bug.php?id=54709 * @param string * @return bool */ function is_really_writable($file) { // If we're on a Unix server with safe_mode off we call is_writable if (DIRECTORY_SEPARATOR === '/' && (is_php('5.4') OR ! ini_get('safe_mode'))) { 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()); if (($fp = @fopen($file, 'ab')) === FALSE) { return FALSE; } fclose($fp); @chmod($file, 0777); @unlink($file); return TRUE; } elseif ( ! is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) { return FALSE; } fclose($fp); return TRUE; } } // ------------------------------------------------------------------------ if ( ! function_exists('load_class')) { /** * 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. * * @param string the class name being requested * @param string the directory where the class should be found * @param mixed an optional argument to pass to the class constructor * @return object */ function &load_class($class, $directory = 'libraries', $param = NULL) { 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 = 'CI_'.$class; if (class_exists($name, FALSE) === FALSE) { require_once($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) === FALSE) { require_once(APPPATH.$directory.'/'.$name.'.php'); } } // Did we find the class? if ($name === FALSE) { // Note: We use exit() rather than show_error() in order to avoid a // self-referencing loop with the Exceptions class set_status_header(503); echo 'Unable to locate the specified class: '.$class.'.php'; exit(5); // EXIT_UNK_CLASS } // Keep track of what we just loaded is_loaded($class); $_classes[$class] = isset($param) ? new $name($param) : new $name(); return $_classes[$class]; } } // -------------------------------------------------------------------- if ( ! function_exists('is_loaded')) { /** * Keeps track of which libraries have been loaded. This function is * called by the load_class() function above * * @param string * @return array */ function &is_loaded($class = '') { static $_is_loaded = array(); if ($class !== '') { $_is_loaded[strtolower($class)] = $class; } return $_is_loaded; } } // ------------------------------------------------------------------------ if ( ! function_exists('get_config')) { /** * Loads the main config.php file * * This function lets us grab the config file even if the Config class * hasn't been instantiated yet * * @param array * @return array */ function &get_config(Array $replace = array()) { static $config; if (empty($config)) { $file_path = APPPATH.'config/config.php'; $found = FALSE; if (file_exists($file_path)) { $found = TRUE; require($file_path); } // Is the config file in the environment folder? if (file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php')) { require($file_path); } elseif ( ! $found) { set_status_header(503); echo 'The configuration file does not exist.'; exit(3); // EXIT_CONFIG } // Does the $config array exist in the file? if ( ! isset($config) OR ! is_array($config)) { set_status_header(503); echo 'Your config file does not appear to be formatted correctly.'; exit(3); // EXIT_CONFIG } } // Are any values being dynamically added or replaced? foreach ($replace as $key => $val) { $config[$key] = $val; } return $config; } } // ------------------------------------------------------------------------ if ( ! function_exists('config_item')) { /** * Returns the specified config item * * @param string * @return mixed */ function config_item($item) { static $_config; if (empty($_config)) { // references cannot be directly assigned to static variables, so we use an array $_config[0] =& get_config(); } return isset($_config[0][$item]) ? $_config[0][$item] : NULL; } } // ------------------------------------------------------------------------ if ( ! function_exists('get_mimes')) { /** * Returns the MIME types array from config/mimes.php * * @return array */ function &get_mimes() { static $_mimes; if (empty($_mimes)) { $_mimes = file_exists(APPPATH.'config/mimes.php') ? include(APPPATH.'config/mimes.php') : array(); if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { $_mimes = array_merge($_mimes, include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')); } } return $_mimes; } } // ------------------------------------------------------------------------ if ( ! function_exists('is_https')) { /** * Is HTTPS? * * Determines if the application is accessed via an encrypted * (HTTPS) connection. * * @return bool */ function is_https() { if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') { return TRUE; } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') { return TRUE; } elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') { return TRUE; } return FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists('is_cli')) { /** * Is CLI? * * Test to see if a request was made from the command line. * * @return bool */ function is_cli() { return (PHP_SAPI === 'cli' OR defined('STDIN')); } } // ------------------------------------------------------------------------ if ( ! function_exists('show_error')) { /** * Error Handler * * This function lets us invoke the exception class and * display errors using the standard error template located * in application/views/errors/error_general.php * This function will send the error page directly to the * browser and exit. * * @param string * @param int * @param string * @return void */ function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered') { $status_code = abs($status_code); if ($status_code < 100) { $exit_status = $status_code + 9; // 9 is EXIT__AUTO_MIN $status_code = 500; } else { $exit_status = 1; // EXIT_ERROR } $_error =& load_class('Exceptions', 'core'); echo $_error->show_error($heading, $message, 'error_general', $status_code); exit($exit_status); } } // ------------------------------------------------------------------------ if ( ! function_exists('show_404')) { /** * 404 Page Handler * * This function is similar to the show_error() function above * However, instead of the standard error template it displays * 404 errors. * * @param string * @param bool * @return void */ function show_404($page = '', $log_error = TRUE) { $_error =& load_class('Exceptions', 'core'); $_error->show_404($page, $log_error); exit(4); // EXIT_UNKNOWN_FILE } } // ------------------------------------------------------------------------ if ( ! function_exists('log_message')) { /** * Error Logging Interface * * We use this as a simple mechanism to access the logging * class and send messages to be logged. * * @param string the error level: 'error', 'debug' or 'info' * @param string the error message * @return void */ function log_message($level, $message) { static $_log; if ($_log === NULL) { // references cannot be directly assigned to static variables, so we use an array $_log[0] =& load_class('Log', 'core'); } $_log[0]->write_log($level, $message); } } // ------------------------------------------------------------------------ if ( ! function_exists('set_status_header')) { /** * Set HTTP Status Header * * @param int the status code * @param string * @return void */ function set_status_header($code = 200, $text = '') { if (is_cli()) { return; } if (empty($code) OR ! is_numeric($code)) { show_error('Status codes must be numeric', 500); } if (empty($text)) { is_int($code) OR $code = (int) $code; $stati = array( 100 => 'Continue', 101 => 'Switching Protocols', 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', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 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', 422 => 'Unprocessable Entity', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 511 => 'Network Authentication Required', ); if (isset($stati[$code])) { $text = $stati[$code]; } else { show_error('No status text available. Please check your status code number or supply your own message text.', 500); } } if (strpos(PHP_SAPI, 'cgi') === 0) { header('Status: '.$code.' '.$text, TRUE); return; } $server_protocol = (isset($_SERVER['SERVER_PROTOCOL']) && in_array($_SERVER['SERVER_PROTOCOL'], array('HTTP/1.0', 'HTTP/1.1', 'HTTP/2', 'HTTP/2.0'), TRUE)) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; header($server_protocol.' '.$code.' '.$text, TRUE, $code); } } // -------------------------------------------------------------------- if ( ! function_exists('_error_handler')) { /** * Error Handler * * This is the custom error handler that is declared at the (relative) * 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. * * @param int $severity * @param string $message * @param string $filepath * @param int $line * @return void */ function _error_handler($severity, $message, $filepath, $line) { $is_error = (((E_ERROR | E_PARSE | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $severity) === $severity); // When an error occurred, set the status header to '500 Internal Server Error' // to indicate to the client something went wrong. // This can't be done within the $_error->show_php_error method because // it is only called when the display_errors flag is set (which isn't usually // the case in a production environment) or when errors are ignored because // they are above the error_reporting threshold. if ($is_error) { set_status_header(500); } // Should we ignore 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) { return; } $_error =& load_class('Exceptions', 'core'); $_error->log_exception($severity, $message, $filepath, $line); // Should we display the error? if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) { $_error->show_php_error($severity, $message, $filepath, $line); } // If the error is fatal, the execution of the script should be stopped because // errors can't be recovered from. Halting the script conforms with PHP's // default error handling. See http://www.php.net/manual/en/errorfunc.constants.php if ($is_error) { exit(1); // EXIT_ERROR } } } // ------------------------------------------------------------------------ if ( ! function_exists('_exception_handler')) { /** * Exception Handler * * Sends uncaught exceptions to the logger and displays them * only if display_errors is On so that they don't show up in * production environments. * * @param Exception $exception * @return void */ function _exception_handler($exception) { $_error =& load_class('Exceptions', 'core'); $_error->log_exception('error', 'Exception: '.$exception->getMessage(), $exception->getFile(), $exception->getLine()); is_cli() OR set_status_header(500); // Should we display the error? if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))) { $_error->show_exception($exception); } exit(1); // EXIT_ERROR } } // ------------------------------------------------------------------------ if ( ! function_exists('_shutdown_handler')) { /** * Shutdown Handler * * This is the shutdown handler that is declared at the top * of CodeIgniter.php. The main reason we use this is to simulate * a complete custom exception handler. * * E_STRICT is purposively neglected because such events may have * been caught. Duplication or none? None is preferred for now. * * @link http://insomanic.me.uk/post/229851073/php-trick-catching-fatal-errors-e-error-with-a * @return void */ function _shutdown_handler() { $last_error = error_get_last(); if (isset($last_error) && ($last_error['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING))) { _error_handler($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']); } } } // -------------------------------------------------------------------- if ( ! function_exists('remove_invisible_characters')) { /** * Remove Invisible Characters * * This prevents sandwiching null characters * between ascii characters, like Java\0script. * * @param string * @param bool * @return string */ 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]/i'; // url encoded 00-08, 11, 12, 14, 15 $non_displayables[] = '/%1[0-9a-f]/i'; // url encoded 16-31 $non_displayables[] = '/%7f/i'; // url encoded 127 } $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; } } // ------------------------------------------------------------------------ if ( ! function_exists('html_escape')) { /** * Returns HTML escaped variable. * * @param mixed $var The input string or array of strings to be escaped. * @param bool $double_encode $double_encode set to FALSE prevents escaping twice. * @return mixed The escaped string or array of strings as a result. */ function html_escape($var, $double_encode = TRUE) { if (empty($var)) { return $var; } if (is_array($var)) { foreach (array_keys($var) as $key) { $var[$key] = html_escape($var[$key], $double_encode); } return $var; } return htmlspecialchars($var, ENT_QUOTES, config_item('charset'), $double_encode); } } // ------------------------------------------------------------------------ if ( ! function_exists('_stringify_attributes')) { /** * Stringify attributes for use in HTML tags. * * Helper function used to convert a string, array, or object * of attributes to a string. * * @param mixed string, array, object * @param bool * @return string */ function _stringify_attributes($attributes, $js = FALSE) { if (empty($attributes)) { return NULL; } if (is_string($attributes)) { return ' '.$attributes; } $attributes = (array) $attributes; $atts = ''; foreach ($attributes as $key => $val) { $atts .= ($js) ? $key.'='.$val.',' : ' '.$key.'="'.$val.'"'; } return rtrim($atts, ','); } } // ------------------------------------------------------------------------ if ( ! function_exists('function_usable')) { /** * Function usable * * Executes a function_exists() check, and if the Suhosin PHP * extension is loaded - checks whether the function that is * checked might be disabled in there as well. * * This is useful as function_exists() will return FALSE for * functions disabled via the *disable_functions* php.ini * setting, but not for *suhosin.executor.func.blacklist* and * *suhosin.executor.disable_eval*. These settings will just * terminate script execution if a disabled function is executed. * * The above described behavior turned out to be a bug in Suhosin, * but even though a fix was committed for 0.9.34 on 2012-02-12, * that version is yet to be released. This function will therefore * be just temporary, but would probably be kept for a few years. * * @link http://www.hardened-php.net/suhosin/ * @param string $function_name Function to check for * @return bool TRUE if the function exists and is safe to call, * FALSE otherwise. */ function function_usable($function_name) { static $_suhosin_func_blacklist; if (function_exists($function_name)) { if ( ! isset($_suhosin_func_blacklist)) { $_suhosin_func_blacklist = extension_loaded('suhosin') ? explode(',', trim(ini_get('suhosin.executor.func.blacklist'))) : array(); } return ! in_array($function_name, $_suhosin_func_blacklist, TRUE); } return FALSE; } } core/Output.php000064400000051463152270514220007516 0ustar00_zlib_oc = (bool) ini_get('zlib.output_compression'); $this->_compress_output = ( $this->_zlib_oc === FALSE && config_item('compress_output') === TRUE && extension_loaded('zlib') ); isset(self::$func_overload) OR self::$func_overload = ( ! is_php('8.0') && extension_loaded('mbstring') && @ini_get('mbstring.func_overload')); // Get mime types for later $this->mimes =& get_mimes(); log_message('info', 'Output Class Initialized'); } // -------------------------------------------------------------------- /** * Get Output * * Returns the current output string. * * @return string */ public function get_output() { return $this->final_output; } // -------------------------------------------------------------------- /** * Set Output * * Sets the output string. * * @param string $output Output data * @return CI_Output */ public function set_output($output) { $this->final_output = $output; return $this; } // -------------------------------------------------------------------- /** * Append Output * * Appends data onto the output string. * * @param string $output Data to append * @return CI_Output */ public function append_output($output) { $this->final_output .= $output; return $this; } // -------------------------------------------------------------------- /** * Set Header * * Lets you set a server header which will be sent with the final output. * * Note: If a file is cached, headers will not be sent. * @todo We need to figure out how to permit headers to be cached. * * @param string $header Header * @param bool $replace Whether to replace the old header value, if already set * @return CI_Output */ public 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; } $this->headers[] = array($header, $replace); return $this; } // -------------------------------------------------------------------- /** * Set Content-Type Header * * @param string $mime_type Extension of the file we're outputting * @param string $charset Character set (default: NULL) * @return CI_Output */ public function set_content_type($mime_type, $charset = NULL) { if (strpos($mime_type, '/') === FALSE) { $extension = ltrim($mime_type, '.'); // Is this extension supported? if (isset($this->mimes[$extension])) { $mime_type =& $this->mimes[$extension]; if (is_array($mime_type)) { $mime_type = current($mime_type); } } } $this->mime_type = $mime_type; if (empty($charset)) { $charset = config_item('charset'); } $header = 'Content-Type: '.$mime_type .(empty($charset) ? '' : '; charset='.$charset); $this->headers[] = array($header, TRUE); return $this; } // -------------------------------------------------------------------- /** * Get Current Content-Type Header * * @return string 'text/html', if not already set */ public function get_content_type() { for ($i = 0, $c = count($this->headers); $i < $c; $i++) { if (sscanf($this->headers[$i][0], 'Content-Type: %[^;]', $content_type) === 1) { return $content_type; } } return 'text/html'; } // -------------------------------------------------------------------- /** * Get Header * * @param string $header * @return string */ public function get_header($header) { // We only need [x][0] from our multi-dimensional array $header_lines = array_map(function ($headers) { return array_shift($headers); }, $this->headers); $headers = array_merge( $header_lines, headers_list() ); if (empty($headers) OR empty($header)) { return NULL; } // Count backwards, in order to get the last matching header for ($c = count($headers) - 1; $c > -1; $c--) { if (strncasecmp($header, $headers[$c], $l = self::strlen($header)) === 0) { return trim(self::substr($headers[$c], $l+1)); } } return NULL; } // -------------------------------------------------------------------- /** * Set HTTP Status Header * * As of version 1.7.2, this is an alias for common function * set_status_header(). * * @param int $code Status code (default: 200) * @param string $text Optional message * @return CI_Output */ public function set_status_header($code = 200, $text = '') { set_status_header($code, $text); return $this; } // -------------------------------------------------------------------- /** * Enable/disable Profiler * * @param bool $val TRUE to enable or FALSE to disable * @return CI_Output */ public 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. * * @param array $sections Profiler sections * @return CI_Output */ public function set_profiler_sections($sections) { if (isset($sections['query_toggle_count'])) { $this->_profiler_sections['query_toggle_count'] = (int) $sections['query_toggle_count']; unset($sections['query_toggle_count']); } foreach ($sections as $section => $enable) { $this->_profiler_sections[$section] = ($enable !== FALSE); } return $this; } // -------------------------------------------------------------------- /** * Set Cache * * @param int $time Cache expiration time in minutes * @return CI_Output */ public function cache($time) { $this->cache_expiration = is_numeric($time) ? $time : 0; return $this; } // -------------------------------------------------------------------- /** * Display Output * * Processes and sends finalized output data to the browser along * with any server headers and profile data. It also stops benchmark * timers so the page rendering speed and memory usage can be shown. * * Note: All "view" data is automatically put into $this->final_output * by controller class. * * @uses CI_Output::$final_output * @param string $output Output data override * @return void */ public function _display($output = '') { // Note: We use load_class() 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. $BM =& load_class('Benchmark', 'core'); $CFG =& load_class('Config', 'core'); // Grab the super object if we can. if (class_exists('CI_Controller', FALSE)) { $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 = round(memory_get_usage() / 1024 / 1024, 2).'MB'; $output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output); } // -------------------------------------------------------------------- // Is compression requested? if (isset($CI) // This means that we're not serving a cache file, if we were, it would already be compressed && $this->_compress_output === TRUE && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && 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)) { if ($this->_compress_output === TRUE) { if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) { header('Content-Encoding: gzip'); header('Content-Length: '.self::strlen($output)); } else { // User agent doesn't support gzip compression, // so we'll have to decompress our cache $output = gzinflate(self::substr($output, 10, -8)); } } echo $output; log_message('info', 'Final output sent to browser'); log_message('debug', 'Total execution time: '.$elapsed); return; } // -------------------------------------------------------------------- // 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 $output = preg_replace('|.*?|is', '', $output, -1, $count).$CI->profiler->run(); if ($count > 0) { $output .= ''; } } // 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('info', 'Final output sent to browser'); log_message('debug', 'Total execution time: '.$elapsed); } // -------------------------------------------------------------------- /** * Write Cache * * @param string $output Output data to cache * @return void */ public 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(); if (($cache_query_string = $CI->config->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING'])) { if (is_array($cache_query_string)) { $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string))); } else { $uri .= '?'.$_SERVER['QUERY_STRING']; } } $cache_path .= md5($uri); if ( ! $fp = @fopen($cache_path, 'w+b')) { log_message('error', 'Unable to write cache file: '.$cache_path); return; } if ( ! flock($fp, LOCK_EX)) { log_message('error', 'Unable to secure a file lock for file at: '.$cache_path); fclose($fp); return; } // If output compression is enabled, compress the cache // itself, so that we don't have to do that each time // we're serving it if ($this->_compress_output === TRUE) { $output = gzencode($output); if ($this->get_header('content-type') === NULL) { $this->set_content_type($this->mime_type); } } $expire = time() + ($this->cache_expiration * 60); // Put together our serialized info. $cache_info = serialize(array( 'expire' => $expire, 'headers' => $this->headers )); $output = $cache_info.'ENDCI--->'.$output; for ($written = 0, $length = self::strlen($output); $written < $length; $written += $result) { if (($result = fwrite($fp, self::substr($output, $written))) === FALSE) { break; } } flock($fp, LOCK_UN); fclose($fp); if ( ! is_int($result)) { @unlink($cache_path); log_message('error', 'Unable to write the complete cache content at: '.$cache_path); return; } chmod($cache_path, 0640); log_message('debug', 'Cache file written: '.$cache_path); // Send HTTP cache-control headers to browser to match file cache settings. $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire); } // -------------------------------------------------------------------- /** * Update/serve cached output * * @uses CI_Config * @uses CI_URI * * @param object &$CFG CI_Config class instance * @param object &$URI CI_URI class instance * @return bool TRUE on success or FALSE on failure */ public 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; if (($cache_query_string = $CFG->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING'])) { if (is_array($cache_query_string)) { $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string))); } else { $uri .= '?'.$_SERVER['QUERY_STRING']; } } $filepath = $cache_path.md5($uri); if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb')) { return FALSE; } flock($fp, LOCK_SH); $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : ''; flock($fp, LOCK_UN); fclose($fp); // Look for embedded serialized file info. if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match)) { return FALSE; } $cache_info = unserialize($match[1]); $expire = $cache_info['expire']; $last_modified = filemtime($filepath); // Has the file expired? if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path)) { // If so we'll delete it. @unlink($filepath); log_message('debug', 'Cache file has expired. File deleted.'); return FALSE; } // Send the HTTP cache control headers $this->set_cache_header($last_modified, $expire); // Add headers from cache file. foreach ($cache_info['headers'] as $header) { $this->set_header($header[0], $header[1]); } // Display the cache $this->_display(self::substr($cache, self::strlen($match[0]))); log_message('debug', 'Cache file is current. Sending it to browser.'); return TRUE; } // -------------------------------------------------------------------- /** * Delete cache * * @param string $uri URI string * @return bool */ public function delete_cache($uri = '') { $CI =& get_instance(); $cache_path = $CI->config->item('cache_path'); if ($cache_path === '') { $cache_path = APPPATH.'cache/'; } if ( ! is_dir($cache_path)) { log_message('error', 'Unable to find cache path: '.$cache_path); return FALSE; } if (empty($uri)) { $uri = $CI->uri->uri_string(); if (($cache_query_string = $CI->config->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING'])) { if (is_array($cache_query_string)) { $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string))); } else { $uri .= '?'.$_SERVER['QUERY_STRING']; } } } $cache_path .= md5($CI->config->item('base_url').$CI->config->item('index_page').ltrim($uri, '/')); if ( ! @unlink($cache_path)) { log_message('error', 'Unable to delete cache file for '.$uri); return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Set Cache Header * * Set the HTTP headers to match the server-side file cache settings * in order to reduce bandwidth. * * @param int $last_modified Timestamp of when the page was last modified * @param int $expiration Timestamp of when should the requested page expire from cache * @return void */ public function set_cache_header($last_modified, $expiration) { $max_age = $expiration - $_SERVER['REQUEST_TIME']; if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $this->set_status_header(304); exit; } header('Pragma: public'); header('Cache-Control: max-age='.$max_age.', public'); header('Expires: '.gmdate('D, d M Y H:i:s', $expiration).' GMT'); header('Last-modified: '.gmdate('D, d M Y H:i:s', $last_modified).' GMT'); } // -------------------------------------------------------------------- /** * Byte-safe strlen() * * @param string $str * @return int */ protected static function strlen($str) { return (self::$func_overload) ? mb_strlen($str, '8bit') : strlen($str); } // -------------------------------------------------------------------- /** * Byte-safe substr() * * @param string $str * @param int $start * @param int $length * @return string */ protected static function substr($str, $start, $length = NULL) { if (self::$func_overload) { // mb_substr($str, $start, null, '8bit') returns an empty // string on PHP 5.3 isset($length) OR $length = ($start >= 0 ? self::strlen($str) - $start : -$start); return mb_substr($str, $start, $length, '8bit'); } return isset($length) ? substr($str, $start, $length) : substr($str, $start); } } core/Lang.php000064400000012644152270514220007075 0ustar00load($value, $idiom, $return, $add_suffix, $alt_path); } return; } $langfile = str_replace('.php', '', $langfile); if ($add_suffix === TRUE) { $langfile = preg_replace('/_lang$/', '', $langfile).'_lang'; } $langfile .= '.php'; if (empty($idiom) OR ! preg_match('/^[a-z_-]+$/i', $idiom)) { $config =& get_config(); $idiom = empty($config['language']) ? 'english' : $config['language']; } if ($return === FALSE && isset($this->is_loaded[$langfile]) && $this->is_loaded[$langfile] === $idiom) { return; } // Load the base file, so any others found can override it $basepath = BASEPATH.'language/'.$idiom.'/'.$langfile; if (($found = file_exists($basepath)) === TRUE) { include($basepath); } // Do we have an alternative path to look in? if ($alt_path !== '') { $alt_path .= 'language/'.$idiom.'/'.$langfile; if (file_exists($alt_path)) { include($alt_path); $found = TRUE; } } else { foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) { $package_path .= 'language/'.$idiom.'/'.$langfile; if ($basepath !== $package_path && file_exists($package_path)) { include($package_path); $found = TRUE; break; } } } if ($found !== TRUE) { show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile); } if ( ! isset($lang) OR ! is_array($lang)) { log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile); if ($return === TRUE) { return array(); } return; } if ($return === TRUE) { return $lang; } $this->is_loaded[$langfile] = $idiom; $this->language = array_merge($this->language, $lang); log_message('info', 'Language file loaded: language/'.$idiom.'/'.$langfile); return TRUE; } // -------------------------------------------------------------------- /** * Language line * * Fetches a single line of text from the language array * * @param string $line Language line key * @param bool $log_errors Whether to log an error message if the line is not found * @return string Translation */ public function line($line, $log_errors = TRUE) { $value = isset($this->language[$line]) ? $this->language[$line] : FALSE; // Because killer robots like unicorns! if ($value === FALSE && $log_errors === TRUE) { log_message('error', 'Could not find the language line "'.$line.'"'); } return $value; } } core/Input.php000064400000056432152270514220007316 0ustar00_allow_get_array = (config_item('allow_get_array') !== FALSE); $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); $this->_enable_csrf = (config_item('csrf_protection') === TRUE); $this->_standardize_newlines = (bool) config_item('standardize_newlines'); $this->security =& load_class('Security', 'core'); // Do we need the UTF-8 class? if (UTF8_ENABLED === TRUE) { $this->uni =& load_class('Utf8', 'core'); } // Sanitize global arrays $this->_sanitize_globals(); // CSRF Protection check if ($this->_enable_csrf === TRUE && ! is_cli()) { $this->security->csrf_verify(); } log_message('info', 'Input Class Initialized'); } // -------------------------------------------------------------------- /** * Fetch from array * * Internal method used to retrieve values from global arrays. * * @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc. * @param mixed $index Index for item to be fetched from $array * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ protected function _fetch_from_array(&$array, $index = NULL, $xss_clean = NULL) { is_bool($xss_clean) OR $xss_clean = $this->_enable_xss; // If $index is NULL, it means that the whole $array is requested isset($index) OR $index = array_keys($array); // allow fetching multiple keys at once if (is_array($index)) { $output = array(); foreach ($index as $key) { $output[$key] = $this->_fetch_from_array($array, $key, $xss_clean); } return $output; } if (isset($array[$index])) { $value = $array[$index]; } elseif (($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) // Does the index contain array notation { $value = $array; for ($i = 0; $i < $count; $i++) { $key = trim($matches[0][$i], '[]'); if ($key === '') // Empty notation will return the value as array { break; } if (isset($value[$key])) { $value = $value[$key]; } else { return NULL; } } } else { return NULL; } return ($xss_clean === TRUE) ? $this->security->xss_clean($value) : $value; } // -------------------------------------------------------------------- /** * Fetch an item from the GET array * * @param mixed $index Index for item to be fetched from $_GET * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function get($index = NULL, $xss_clean = NULL) { return $this->_fetch_from_array($_GET, $index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from the POST array * * @param mixed $index Index for item to be fetched from $_POST * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function post($index = NULL, $xss_clean = NULL) { return $this->_fetch_from_array($_POST, $index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from POST data with fallback to GET * * @param string $index Index for item to be fetched from $_POST or $_GET * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function post_get($index, $xss_clean = NULL) { return isset($_POST[$index]) ? $this->post($index, $xss_clean) : $this->get($index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from GET data with fallback to POST * * @param string $index Index for item to be fetched from $_GET or $_POST * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function get_post($index, $xss_clean = NULL) { return isset($_GET[$index]) ? $this->get($index, $xss_clean) : $this->post($index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from the COOKIE array * * @param mixed $index Index for item to be fetched from $_COOKIE * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function cookie($index = NULL, $xss_clean = NULL) { return $this->_fetch_from_array($_COOKIE, $index, $xss_clean); } // -------------------------------------------------------------------- /** * Fetch an item from the SERVER array * * @param mixed $index Index for item to be fetched from $_SERVER * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function server($index, $xss_clean = NULL) { return $this->_fetch_from_array($_SERVER, $index, $xss_clean); } // ------------------------------------------------------------------------ /** * Fetch an item from the php://input stream * * Useful when you need to access PUT, DELETE or PATCH request data. * * @param string $index Index for item to be fetched * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function input_stream($index = NULL, $xss_clean = NULL) { // Prior to PHP 5.6, the input stream can only be read once, // so we'll need to check if we have already done that first. if ( ! is_array($this->_input_stream)) { // $this->raw_input_stream will trigger __get(). parse_str($this->raw_input_stream, $this->_input_stream); is_array($this->_input_stream) OR $this->_input_stream = array(); } return $this->_fetch_from_array($this->_input_stream, $index, $xss_clean); } // ------------------------------------------------------------------------ /** * Set cookie * * Accepts an arbitrary number of parameters (up to 7) or an associative * array in the first parameter containing all the values. * * @param string|mixed[] $name Cookie name or an array containing parameters * @param string $value Cookie value * @param int $expire Cookie expiration time in seconds * @param string $domain Cookie domain (e.g.: '.yourdomain.com') * @param string $path Cookie path (default: '/') * @param string $prefix Cookie name prefix * @param bool $secure Whether to only transfer cookies via SSL * @param bool $httponly Whether to only makes the cookie accessible via HTTP (no javascript) * @param string $samesite SameSite attribute * @return void */ public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = NULL, $samesite = NULL) { 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', 'httponly', 'name', 'samesite') as $item) { if (isset($name[$item])) { $$item = $name[$item]; } } } if ($prefix === '' && config_item('cookie_prefix') !== '') { $prefix = config_item('cookie_prefix'); } if ($domain == '' && config_item('cookie_domain') != '') { $domain = config_item('cookie_domain'); } if ($path === '/' && config_item('cookie_path') !== '/') { $path = config_item('cookie_path'); } $secure = ($secure === NULL && config_item('cookie_secure') !== NULL) ? (bool) config_item('cookie_secure') : (bool) $secure; $httponly = ($httponly === NULL && config_item('cookie_httponly') !== NULL) ? (bool) config_item('cookie_httponly') : (bool) $httponly; if ( ! is_numeric($expire)) { $expire = time() - 86500; } else { $expire = ($expire > 0) ? time() + $expire : 0; } isset($samesite) OR $samesite = config_item('cookie_samesite'); if (isset($samesite)) { $samesite = ucfirst(strtolower($samesite)); in_array($samesite, array('Lax', 'Strict', 'None'), TRUE) OR $samesite = 'Lax'; } else { $samesite = 'Lax'; } if ($samesite === 'None' && ! $secure) { log_message('error', $name.' cookie sent with SameSite=None, but without Secure attribute.'); } if ( ! is_php('7.3')) { $maxage = $expire - time(); if ($maxage < 1) { $maxage = 0; } $cookie_header = 'Set-Cookie: '.$prefix.$name.'='.rawurlencode($value); $cookie_header .= ($expire === 0 ? '' : '; Expires='.gmdate('D, d-M-Y H:i:s T', $expire)).'; Max-Age='.$maxage; $cookie_header .= '; Path='.$path.($domain !== '' ? '; Domain='.$domain : ''); $cookie_header .= ($secure ? '; Secure' : '').($httponly ? '; HttpOnly' : '').'; SameSite='.$samesite; header($cookie_header); return; } $setcookie_options = array( 'expires' => $expire, 'path' => $path, 'domain' => $domain, 'secure' => $secure, 'httponly' => $httponly, 'samesite' => $samesite, ); setcookie($prefix.$name, $value, $setcookie_options); } // -------------------------------------------------------------------- /** * Fetch the IP Address * * Determines and validates the visitor's IP address. * * @return string IP address */ public function ip_address() { if ($this->ip_address !== FALSE) { return $this->ip_address; } $proxy_ips = config_item('proxy_ips'); if ( ! empty($proxy_ips) && ! is_array($proxy_ips)) { $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips)); } $this->ip_address = $this->server('REMOTE_ADDR'); if ($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)) !== NULL) { // 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. sscanf($spoof, '%[^,]', $spoof); if ( ! $this->valid_ip($spoof)) { $spoof = NULL; } else { break; } } } if ($spoof) { for ($i = 0, $c = count($proxy_ips); $i < $c; $i++) { // Check if we have an IP address or a subnet if (strpos($proxy_ips[$i], '/') === FALSE) { // An IP address (and not a subnet) is specified. // We can compare right away. if ($proxy_ips[$i] === $this->ip_address) { $this->ip_address = $spoof; break; } continue; } // We have a subnet ... now the heavy lifting begins isset($separator) OR $separator = $this->valid_ip($this->ip_address, 'ipv6') ? ':' : '.'; // If the proxy entry doesn't match the IP protocol - skip it if (strpos($proxy_ips[$i], $separator) === FALSE) { continue; } // Convert the REMOTE_ADDR IP address to binary, if needed if ( ! isset($ip, $sprintf)) { if ($separator === ':') { // Make sure we're have the "full" IPv6 format $ip = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($this->ip_address, ':')), $this->ip_address ) ); for ($j = 0; $j < 8; $j++) { $ip[$j] = intval($ip[$j], 16); } $sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b'; } else { $ip = explode('.', $this->ip_address); $sprintf = '%08b%08b%08b%08b'; } $ip = vsprintf($sprintf, $ip); } // Split the netmask length off the network address sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen); // Again, an IPv6 address is most likely in a compressed form if ($separator === ':') { $netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr)); for ($j = 0; $j < 8; $j++) { $netaddr[$j] = intval($netaddr[$j], 16); } } else { $netaddr = explode('.', $netaddr); } // Convert to binary and finally compare if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0) { $this->ip_address = $spoof; break; } } } } if ( ! $this->valid_ip($this->ip_address)) { return $this->ip_address = '0.0.0.0'; } return $this->ip_address; } // -------------------------------------------------------------------- /** * Validate IP Address * * @param string $ip IP address * @param string $which IP protocol: 'ipv4' or 'ipv6' * @return bool */ public function valid_ip($ip, $which = '') { switch (strtolower($which)) { case 'ipv4': $which = FILTER_FLAG_IPV4; break; case 'ipv6': $which = FILTER_FLAG_IPV6; break; default: $which = 0; break; } return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which); } // -------------------------------------------------------------------- /** * Fetch User Agent string * * @return string|null User Agent string or NULL if it doesn't exist */ public function user_agent($xss_clean = NULL) { return $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean); } // -------------------------------------------------------------------- /** * Sanitize Globals * * Internal method serving for the following purposes: * * - Unsets $_GET data, if query strings are not enabled * - Cleans POST, COOKIE and SERVER data * - Standardizes newline characters to PHP_EOL * * @return void */ protected function _sanitize_globals() { // Is $_GET data allowed? If not we'll set the $_GET to an empty array if ($this->_allow_get_array === FALSE) { $_GET = array(); } elseif (is_array($_GET)) { foreach ($_GET as $key => $val) { $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Clean $_POST Data if (is_array($_POST)) { foreach ($_POST as $key => $val) { $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Clean $_COOKIE Data if (is_array($_COOKIE)) { // 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'], $_COOKIE['$Path'], $_COOKIE['$Domain'] ); foreach ($_COOKIE as $key => $val) { if (($cookie_key = $this->_clean_input_keys($key)) !== FALSE) { $_COOKIE[$cookie_key] = $this->_clean_input_data($val); } else { unset($_COOKIE[$key]); } } } // Sanitize PHP_SELF $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']); log_message('debug', 'Global POST, GET and COOKIE data sanitized'); } // -------------------------------------------------------------------- /** * Clean Input Data * * Internal method that aids in escaping data and * standardizing newline characters to PHP_EOL. * * @param string|string[] $str Input string(s) * @return string */ protected function _clean_input_data($str) { if (is_array($str)) { $new_array = array(); foreach (array_keys($str) as $key) { $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($str[$key]); } 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, FALSE); // Standardize newlines if needed if ($this->_standardize_newlines === TRUE) { return preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $str); } return $str; } // -------------------------------------------------------------------- /** * Clean Keys * * Internal method that helps 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. * * @param string $str Input string * @param bool $fatal Whether to terminate script exection * or to return FALSE if an invalid * key is encountered * @return string|bool */ protected function _clean_input_keys($str, $fatal = TRUE) { if ( ! preg_match('/^[a-z0-9:_\/|-]+$/i', $str)) { if ($fatal === TRUE) { return FALSE; } else { set_status_header(503); echo 'Disallowed Key Characters.'; exit(7); // EXIT_USER_INPUT } } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { return $this->uni->clean_string($str); } return $str; } // -------------------------------------------------------------------- /** * Request Headers * * @param bool $xss_clean Whether to apply XSS filtering * @return array */ public function request_headers($xss_clean = FALSE) { // If header is already defined, return it immediately if ( ! empty($this->headers)) { return $this->_fetch_from_array($this->headers, NULL, $xss_clean); } // In Apache, you can simply call apache_request_headers() if (function_exists('apache_request_headers')) { $this->headers = apache_request_headers(); } else { isset($_SERVER['CONTENT_TYPE']) && $this->headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; foreach ($_SERVER as $key => $val) { if (sscanf($key, 'HTTP_%s', $header) === 1) { // take SOME_HEADER and turn it into Some-Header $header = str_replace('_', ' ', strtolower($header)); $header = str_replace(' ', '-', ucwords($header)); $this->headers[$header] = $_SERVER[$key]; } } } return $this->_fetch_from_array($this->headers, NULL, $xss_clean); } // -------------------------------------------------------------------- /** * Get Request Header * * Returns the value of a single member of the headers class member * * @param string $index Header name * @param bool $xss_clean Whether to apply XSS filtering * @return string|null The requested header on success or NULL on failure */ public function get_request_header($index, $xss_clean = FALSE) { static $headers; if ( ! isset($headers)) { empty($this->headers) && $this->request_headers(); foreach ($this->headers as $key => $value) { $headers[strtolower($key)] = $value; } } $index = strtolower($index); if ( ! isset($headers[$index])) { return NULL; } return ($xss_clean === TRUE) ? $this->security->xss_clean($headers[$index]) : $headers[$index]; } // -------------------------------------------------------------------- /** * Is AJAX request? * * Test to see if a request contains the HTTP_X_REQUESTED_WITH header. * * @return bool */ public function is_ajax_request() { return ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'); } // -------------------------------------------------------------------- /** * Is CLI request? * * Test to see if a request was made from the command line. * * @deprecated 3.0.0 Use is_cli() instead * @return bool */ public function is_cli_request() { return is_cli(); } // -------------------------------------------------------------------- /** * Get Request Method * * Return the request method * * @param bool $upper Whether to return in upper or lower case * (default: FALSE) * @return string */ public function method($upper = FALSE) { return ($upper) ? strtoupper($this->server('REQUEST_METHOD')) : strtolower($this->server('REQUEST_METHOD')); } // ------------------------------------------------------------------------ /** * Magic __get() * * Allows read access to protected properties * * @param string $name * @return mixed */ public function __get($name) { if ($name === 'raw_input_stream') { isset($this->_raw_input_stream) OR $this->_raw_input_stream = file_get_contents('php://input'); return $this->_raw_input_stream; } elseif ($name === 'ip_address') { return $this->ip_address; } } } core/Loader.php000064400000110470152270514220007416 0ustar00 TRUE); /** * List of paths to load libraries from * * @var array */ protected $_ci_library_paths = array(APPPATH, BASEPATH); /** * List of paths to load models from * * @var array */ protected $_ci_model_paths = array(APPPATH); /** * List of paths to load helpers from * * @var array */ protected $_ci_helper_paths = array(APPPATH, BASEPATH); /** * List of cached variables * * @var array */ protected $_ci_cached_vars = array(); /** * List of loaded classes * * @var array */ protected $_ci_classes = array(); /** * List of loaded models * * @var array */ protected $_ci_models = array(); /** * List of loaded helpers * * @var array */ protected $_ci_helpers = array(); /** * List of class name mappings * * @var array */ protected $_ci_varmap = array( 'unit_test' => 'unit', 'user_agent' => 'agent' ); // -------------------------------------------------------------------- /** * Class constructor * * Sets component load paths, gets the initial output buffering level. * * @return void */ public function __construct() { $this->_ci_ob_level = ob_get_level(); $this->_ci_classes =& is_loaded(); log_message('info', 'Loader Class Initialized'); } // -------------------------------------------------------------------- /** * Initializer * * @todo Figure out a way to move this to the constructor * without breaking *package_path*() methods. * @uses CI_Loader::_ci_autoloader() * @used-by CI_Controller::__construct() * @return void */ public function initialize() { $this->_ci_autoloader(); } // -------------------------------------------------------------------- /** * Is Loaded * * A utility method to test if a class is in the self::$_ci_classes array. * * @used-by Mainly used by Form Helper function _get_validation_object(). * * @param string $class Class name to check for * @return string|bool Class object name if loaded or FALSE */ public function is_loaded($class) { return array_search(ucfirst($class), $this->_ci_classes, TRUE); } // -------------------------------------------------------------------- /** * Library Loader * * Loads and instantiates libraries. * Designed to be called from application controllers. * * @param mixed $library Library name * @param array $params Optional parameters to pass to the library class constructor * @param string $object_name An optional object name to assign to * @return object */ public function library($library, $params = NULL, $object_name = NULL) { if (empty($library)) { return $this; } elseif (is_array($library)) { foreach ($library as $key => $value) { if (is_int($key)) { $this->library($value, $params); } else { $this->library($key, $params, $value); } } return $this; } if ($params !== NULL && ! is_array($params)) { $params = NULL; } $this->_ci_load_library($library, $params, $object_name); return $this; } // -------------------------------------------------------------------- /** * Model Loader * * Loads and instantiates models. * * @param mixed $model Model name * @param string $name An optional object name to assign to * @param bool $db_conn An optional database connection configuration to initialize * @return object */ public function model($model, $name = '', $db_conn = FALSE) { if (empty($model)) { return $this; } elseif (is_array($model)) { foreach ($model as $key => $value) { is_int($key) ? $this->model($value, '', $db_conn) : $this->model($key, $value, $db_conn); } return $this; } $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); // And the model name behind it $model = substr($model, $last_slash); } if (empty($name)) { $name = $model; } if (in_array($name, $this->_ci_models, TRUE)) { return $this; } $CI =& get_instance(); if (isset($CI->$name)) { throw new RuntimeException('The model name you are loading is the name of a resource that is already being used: '.$name); } if ($db_conn !== FALSE && ! class_exists('CI_DB', FALSE)) { if ($db_conn === TRUE) { $db_conn = ''; } $this->database($db_conn, FALSE, TRUE); } // Note: All of the code under this condition used to be just: // // load_class('Model', 'core'); // // However, load_class() instantiates classes // to cache them for later use and that prevents // MY_Model from being an abstract class and is // sub-optimal otherwise anyway. if ( ! class_exists('CI_Model', FALSE)) { $app_path = APPPATH.'core'.DIRECTORY_SEPARATOR; if (file_exists($app_path.'Model.php')) { require_once($app_path.'Model.php'); if ( ! class_exists('CI_Model', FALSE)) { throw new RuntimeException($app_path."Model.php exists, but doesn't declare class CI_Model"); } log_message('info', 'CI_Model class loaded'); } elseif ( ! class_exists('CI_Model', FALSE)) { require_once(BASEPATH.'core'.DIRECTORY_SEPARATOR.'Model.php'); } $class = config_item('subclass_prefix').'Model'; if (file_exists($app_path.$class.'.php')) { require_once($app_path.$class.'.php'); if ( ! class_exists($class, FALSE)) { throw new RuntimeException($app_path.$class.".php exists, but doesn't declare class ".$class); } log_message('info', config_item('subclass_prefix').'Model class loaded'); } } $model = ucfirst($model); if ( ! class_exists($model, FALSE)) { foreach ($this->_ci_model_paths as $mod_path) { if ( ! file_exists($mod_path.'models/'.$path.$model.'.php')) { continue; } require_once($mod_path.'models/'.$path.$model.'.php'); if ( ! class_exists($model, FALSE)) { throw new RuntimeException($mod_path."models/".$path.$model.".php exists, but doesn't declare class ".$model); } break; } if ( ! class_exists($model, FALSE)) { throw new RuntimeException('Unable to locate the model you have specified: '.$model); } } elseif ( ! is_subclass_of($model, 'CI_Model')) { throw new RuntimeException("Class ".$model." already exists and doesn't extend CI_Model"); } $this->_ci_models[] = $name; $model = new $model(); $CI->$name = $model; log_message('info', 'Model "'.get_class($model).'" initialized'); return $this; } // -------------------------------------------------------------------- /** * Database Loader * * @param mixed $params Database configuration options * @param bool $return Whether to return the database object * @param bool $query_builder Whether to enable Query Builder * (overrides the configuration setting) * * @return object|bool Database object if $return is set to TRUE, * FALSE on failure, CI_Loader instance in any other case */ public function database($params = '', $return = FALSE, $query_builder = NULL) { // Grab the super object $CI =& get_instance(); // Do we even need to load the database class? if ($return === FALSE && $query_builder === NULL && isset($CI->db) && is_object($CI->db) && ! empty($CI->db->conn_id)) { return FALSE; } require_once(BASEPATH.'database/DB.php'); if ($return === TRUE) { return DB($params, $query_builder); } // Initialize the db variable. Needed to prevent // reference errors with some configurations $CI->db = ''; // Load the DB class $CI->db =& DB($params, $query_builder); return $this; } // -------------------------------------------------------------------- /** * Load the Database Utilities Class * * @param object $db Database object * @param bool $return Whether to return the DB Utilities class object or not * @return object */ public function dbutil($db = NULL, $return = FALSE) { $CI =& get_instance(); if ( ! is_object($db) OR ! ($db instanceof CI_DB)) { class_exists('CI_DB', FALSE) OR $this->database(); $db =& $CI->db; } require_once(BASEPATH.'database/DB_utility.php'); require_once(BASEPATH.'database/drivers/'.$db->dbdriver.'/'.$db->dbdriver.'_utility.php'); $class = 'CI_DB_'.$db->dbdriver.'_utility'; if ($return === TRUE) { return new $class($db); } $CI->dbutil = new $class($db); return $this; } // -------------------------------------------------------------------- /** * Load the Database Forge Class * * @param object $db Database object * @param bool $return Whether to return the DB Forge class object or not * @return object */ public function dbforge($db = NULL, $return = FALSE) { $CI =& get_instance(); if ( ! is_object($db) OR ! ($db instanceof CI_DB)) { class_exists('CI_DB', FALSE) OR $this->database(); $db =& $CI->db; } require_once(BASEPATH.'database/DB_forge.php'); require_once(BASEPATH.'database/drivers/'.$db->dbdriver.'/'.$db->dbdriver.'_forge.php'); if ( ! empty($db->subdriver)) { $driver_path = BASEPATH.'database/drivers/'.$db->dbdriver.'/subdrivers/'.$db->dbdriver.'_'.$db->subdriver.'_forge.php'; if (file_exists($driver_path)) { require_once($driver_path); $class = 'CI_DB_'.$db->dbdriver.'_'.$db->subdriver.'_forge'; } } else { $class = 'CI_DB_'.$db->dbdriver.'_forge'; } if ($return === TRUE) { return new $class($db); } $CI->dbforge = new $class($db); return $this; } // -------------------------------------------------------------------- /** * View Loader * * Loads "view" files. * * @param string $view View name * @param array $vars An associative array of data * to be extracted for use in the view * @param bool $return Whether to return the view output * or leave it to the Output class * @return object|string */ public function view($view, $vars = array(), $return = FALSE) { return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return)); } // -------------------------------------------------------------------- /** * Generic File Loader * * @param string $path File path * @param bool $return Whether to return the file output * @return object|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|object|string $vars * An associative array or object containing values * to be set, or a value's name if string * @param string $val Value to set, only used if $vars is a string * @return object */ public function vars($vars, $val = '') { $vars = is_string($vars) ? array($vars => $val) : $this->_ci_prepare_view_vars($vars); foreach ($vars as $key => $val) { $this->_ci_cached_vars[$key] = $val; } return $this; } // -------------------------------------------------------------------- /** * Clear Cached Variables * * Clears the cached variables. * * @return CI_Loader */ public function clear_vars() { $this->_ci_cached_vars = array(); return $this; } // -------------------------------------------------------------------- /** * Get Variable * * Check if a variable is set and retrieve it. * * @param string $key Variable name * @return mixed The variable or NULL if not found */ public function get_var($key) { return isset($this->_ci_cached_vars[$key]) ? $this->_ci_cached_vars[$key] : NULL; } // -------------------------------------------------------------------- /** * Get Variables * * Retrieves all loaded variables. * * @return array */ public function get_vars() { return $this->_ci_cached_vars; } // -------------------------------------------------------------------- /** * Helper Loader * * @param string|string[] $helpers Helper name(s) * @return object */ public function helper($helpers = array()) { is_array($helpers) OR $helpers = array($helpers); foreach ($helpers as &$helper) { $filename = basename($helper); $filepath = ($filename === $helper) ? '' : substr($helper, 0, strlen($helper) - strlen($filename)); $filename = strtolower(preg_replace('#(_helper)?(\.php)?$#i', '', $filename)).'_helper'; $helper = $filepath.$filename; if (isset($this->_ci_helpers[$helper])) { continue; } // Is this a helper extension request? $ext_helper = config_item('subclass_prefix').$filename; $ext_loaded = FALSE; foreach ($this->_ci_helper_paths as $path) { if (file_exists($path.'helpers/'.$ext_helper.'.php')) { include_once($path.'helpers/'.$ext_helper.'.php'); $ext_loaded = TRUE; } } // If we have loaded extensions - check if the base one is here if ($ext_loaded === TRUE) { $base_helper = BASEPATH.'helpers/'.$helper.'.php'; if ( ! file_exists($base_helper)) { show_error('Unable to load the requested file: helpers/'.$helper.'.php'); } include_once($base_helper); $this->_ci_helpers[$helper] = TRUE; log_message('info', 'Helper loaded: '.$helper); continue; } // No extensions found ... try loading regular helpers and/or overrides 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('info', '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'); } } return $this; } // -------------------------------------------------------------------- /** * Load Helpers * * An alias for the helper() method in case the developer has * written the plural form of it. * * @uses CI_Loader::helper() * @param string|string[] $helpers Helper name(s) * @return object */ public function helpers($helpers = array()) { return $this->helper($helpers); } // -------------------------------------------------------------------- /** * Language Loader * * Loads language files. * * @param string|string[] $files List of language file names to load * @param string Language name * @return object */ public function language($files, $lang = '') { get_instance()->lang->load($files, $lang); return $this; } // -------------------------------------------------------------------- /** * Config Loader * * Loads a config file (an alias for CI_Config::load()). * * @uses CI_Config::load() * @param string $file Configuration file name * @param bool $use_sections Whether configuration values should be loaded into their own section * @param bool $fail_gracefully Whether to just return FALSE or display an error message * @return bool TRUE if the file was loaded correctly or FALSE on failure */ public function config($file, $use_sections = FALSE, $fail_gracefully = FALSE) { return get_instance()->config->load($file, $use_sections, $fail_gracefully); } // -------------------------------------------------------------------- /** * Driver Loader * * Loads a driver library. * * @param string|string[] $library Driver name(s) * @param array $params Optional parameters to pass to the driver * @param string $object_name An optional object name to assign to * * @return object|bool Object or FALSE on failure if $library is a string * and $object_name is set. CI_Loader instance otherwise. */ public function driver($library, $params = NULL, $object_name = NULL) { if (is_array($library)) { foreach ($library as $key => $value) { if (is_int($key)) { $this->driver($value, $params); } else { $this->driver($key, $params, $value); } } return $this; } elseif (empty($library)) { return FALSE; } if ( ! class_exists('CI_Driver_Library', FALSE)) { // We aren't instantiating an object here, just making the base class available require BASEPATH.'libraries/Driver.php'; } // 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. * * @see CI_Loader::$_ci_library_paths * @see CI_Loader::$_ci_model_paths * @see CI_Loader::$_ci_helper_paths * @see CI_Config::$_config_paths * * @param string $path Path to add * @param bool $view_cascade (default: TRUE) * @return object */ 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'); $config->_config_paths[] = $path; return $this; } // -------------------------------------------------------------------- /** * Get Package Paths * * Return a list of all package paths. * * @param bool $include_base Whether to include BASEPATH (default: FALSE) * @return array */ 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, helper and/or config * path arrays if it exists. If no path is provided, the most recently * added path will be removed removed. * * @param string $path Path to remove * @return object */ public function remove_package_path($path = '') { $config =& $this->_ci_get_component('config'); if ($path === '') { array_shift($this->_ci_library_paths); array_shift($this->_ci_model_paths); array_shift($this->_ci_helper_paths); array_shift($this->_ci_view_paths); array_pop($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))); return $this; } // -------------------------------------------------------------------- /** * Internal CI Data Loader * * Used to load views and files. * * Variables are prefixed with _ci_ to avoid symbol collision with * variables made available to view files. * * @used-by CI_Loader::view() * @used-by CI_Loader::file() * @param array $_ci_data Data to load * @return object */ 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]) ? $_ci_data[$_ci_val] : FALSE; } $file_exists = FALSE; // Set the path to the requested file if (is_string($_ci_path) && $_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 $_ci_view_file => $cascade) { if (file_exists($_ci_view_file.$_ci_file)) { $_ci_path = $_ci_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. */ empty($_ci_vars) OR $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 ( ! is_php('5.4') && ! ini_get('short_open_tag') && 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(); } return $this; } // -------------------------------------------------------------------- /** * Internal CI Library Loader * * @used-by CI_Loader::library() * @uses CI_Loader::_ci_init_library() * * @param string $class Class name to load * @param mixed $params Optional parameters to pass to the class constructor * @param string $object_name Optional object name to assign to * @return void */ protected function _ci_load_library($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 if (($last_slash = strrpos($class, '/')) !== FALSE) { // Extract the path $subdir = substr($class, 0, ++$last_slash); // Get the filename from the path $class = substr($class, $last_slash); } else { $subdir = ''; } $class = ucfirst($class); // Is this a stock library? There are a few special conditions if so ... if (file_exists(BASEPATH.'libraries/'.$subdir.$class.'.php')) { return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); } // Safety: Was the class already loaded by a previous call? if (class_exists($class, FALSE)) { $property = $object_name; if (empty($property)) { $property = strtolower($class); isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property]; } $CI =& get_instance(); if (isset($CI->$property)) { log_message('debug', $class.' class already loaded. Second attempt ignored.'); return; } return $this->_ci_init_library($class, '', $params, $object_name); } // Let's search for the requested library file and load it. foreach ($this->_ci_library_paths as $path) { // BASEPATH has already been checked for if ($path === BASEPATH) { continue; } $filepath = $path.'libraries/'.$subdir.$class.'.php'; // Does the file exist? No? Bummer... if ( ! file_exists($filepath)) { continue; } include_once($filepath); return $this->_ci_init_library($class, '', $params, $object_name); } // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified? if ($subdir === '') { return $this->_ci_load_library($class.'/'.$class, $params, $object_name); } // If we got this far we were unable to find the requested class. log_message('error', 'Unable to load the requested class: '.$class); show_error('Unable to load the requested class: '.$class); } // -------------------------------------------------------------------- /** * Internal CI Stock Library Loader * * @used-by CI_Loader::_ci_load_library() * @uses CI_Loader::_ci_init_library() * * @param string $library_name Library name to load * @param string $file_path Path to the library filename, relative to libraries/ * @param mixed $params Optional parameters to pass to the class constructor * @param string $object_name Optional object name to assign to * @return void */ protected function _ci_load_stock_library($library_name, $file_path, $params, $object_name) { $prefix = 'CI_'; if (class_exists($prefix.$library_name, FALSE)) { if (class_exists(config_item('subclass_prefix').$library_name, FALSE)) { $prefix = config_item('subclass_prefix'); } $property = $object_name; if (empty($property)) { $property = strtolower($library_name); isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property]; } $CI =& get_instance(); if ( ! isset($CI->$property)) { return $this->_ci_init_library($library_name, $prefix, $params, $object_name); } log_message('debug', $library_name.' class already loaded. Second attempt ignored.'); return; } $paths = $this->_ci_library_paths; array_pop($paths); // BASEPATH array_pop($paths); // APPPATH (needs to be the first path checked) array_unshift($paths, APPPATH); foreach ($paths as $path) { if (file_exists($path = $path.'libraries/'.$file_path.$library_name.'.php')) { // Override include_once($path); if (class_exists($prefix.$library_name, FALSE)) { return $this->_ci_init_library($library_name, $prefix, $params, $object_name); } log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name); } } include_once(BASEPATH.'libraries/'.$file_path.$library_name.'.php'); // Check for extensions $subclass = config_item('subclass_prefix').$library_name; foreach ($paths as $path) { if (file_exists($path = $path.'libraries/'.$file_path.$subclass.'.php')) { include_once($path); if (class_exists($subclass, FALSE)) { $prefix = config_item('subclass_prefix'); break; } log_message('debug', $path.' exists, but does not declare '.$subclass); } } return $this->_ci_init_library($library_name, $prefix, $params, $object_name); } // -------------------------------------------------------------------- /** * Internal CI Library Instantiator * * @used-by CI_Loader::_ci_load_stock_library() * @used-by CI_Loader::_ci_load_library() * * @param string $class Class name * @param string $prefix Class name prefix * @param array|null|bool $config Optional configuration to pass to the class constructor: * FALSE to skip; * NULL to search in config paths; * array containing configuration data * @param string $object_name Optional object name to assign to * @return void */ protected function _ci_init_library($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)) { $found = FALSE; 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. Load global first, // override with environment next if (file_exists($path.'config/'.strtolower($class).'.php')) { include($path.'config/'.strtolower($class).'.php'); $found = TRUE; } elseif (file_exists($path.'config/'.ucfirst(strtolower($class)).'.php')) { include($path.'config/'.ucfirst(strtolower($class)).'.php'); $found = TRUE; } if (file_exists($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php')) { include($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'); $found = TRUE; } elseif (file_exists($path.'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php')) { include($path.'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'); $found = TRUE; } // Break on the first found configuration, thus package // files are not overridden by default paths if ($found === TRUE) { break; } } } } $class_name = $prefix.$class; // Is the class name valid? if ( ! class_exists($class_name, FALSE)) { log_message('error', 'Non-existent class: '.$class_name); show_error('Non-existent class: '.$class_name); } // Set the variable name we will assign the class to // Was a custom class name supplied? If so we'll use it if (empty($object_name)) { $object_name = strtolower($class); if (isset($this->_ci_varmap[$object_name])) { $object_name = $this->_ci_varmap[$object_name]; } } // Don't overwrite existing properties $CI =& get_instance(); if (isset($CI->$object_name)) { if ($CI->$object_name instanceof $class_name) { log_message('debug', $class_name." has already been instantiated as '".$object_name."'. Second attempt aborted."); return; } show_error("Resource '".$object_name."' already exists and is not a ".$class_name." instance."); } // Save the class name and object name $this->_ci_classes[$object_name] = $class; // Instantiate the class $CI->$object_name = isset($config) ? new $class_name($config) : new $class_name(); } // -------------------------------------------------------------------- /** * CI Autoloader * * Loads component listed in the config/autoload.php file. * * @used-by CI_Loader::initialize() * @return void */ protected function _ci_autoloader() { if (file_exists(APPPATH.'config/autoload.php')) { include(APPPATH.'config/autoload.php'); } if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'); } if ( ! isset($autoload)) { return; } // 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) { foreach ($autoload['config'] as $val) { $this->config($val); } } // Autoload helpers and languages foreach (array('helper', 'language') as $type) { if (isset($autoload[$type]) && count($autoload[$type]) > 0) { $this->$type($autoload[$type]); } } // Autoload drivers if (isset($autoload['drivers'])) { $this->driver($autoload['drivers']); } // Load libraries if (isset($autoload['libraries']) && 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 $this->library($autoload['libraries']); } // Autoload models if (isset($autoload['model'])) { $this->model($autoload['model']); } } // -------------------------------------------------------------------- /** * Prepare variables for _ci_vars, to be later extract()-ed inside views * * Converts objects to associative arrays and filters-out internal * variable names (i.e. keys prefixed with '_ci_'). * * @param mixed $vars * @return array */ protected function _ci_prepare_view_vars($vars) { if ( ! is_array($vars)) { $vars = is_object($vars) ? get_object_vars($vars) : array(); } foreach (array_keys($vars) as $key) { if (strncmp($key, '_ci_', 4) === 0) { unset($vars[$key]); } } return $vars; } // -------------------------------------------------------------------- /** * CI Component getter * * Get a reference to a specific library or model. * * @param string $component Component name * @return bool */ protected function &_ci_get_component($component) { $CI =& get_instance(); return $CI->$component; } } core/index.html000064400000000203152270514220007464 0ustar00 403 Forbidden

Directory access is forbidden.

core/Log.php000064400000016734152270514220006741 0ustar00 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4); /** * mbstring.func_overload flag * * @var bool */ protected static $func_overload; // -------------------------------------------------------------------- /** * Class constructor * * @return void */ public function __construct() { $config =& get_config(); isset(self::$func_overload) OR self::$func_overload = ( ! is_php('8.0') && extension_loaded('mbstring') && @ini_get('mbstring.func_overload')); $this->_log_path = ($config['log_path'] !== '') ? $config['log_path'] : APPPATH.'logs/'; $this->_file_ext = (isset($config['log_file_extension']) && $config['log_file_extension'] !== '') ? ltrim($config['log_file_extension'], '.') : 'php'; file_exists($this->_log_path) OR mkdir($this->_log_path, 0755, TRUE); if ( ! is_dir($this->_log_path) OR ! is_really_writable($this->_log_path)) { $this->_enabled = FALSE; } if (is_numeric($config['log_threshold'])) { $this->_threshold = (int) $config['log_threshold']; } elseif (is_array($config['log_threshold'])) { $this->_threshold = 0; $this->_threshold_array = array_flip($config['log_threshold']); } if ( ! empty($config['log_date_format'])) { $this->_date_fmt = $config['log_date_format']; } if ( ! empty($config['log_file_permissions']) && is_int($config['log_file_permissions'])) { $this->_file_permissions = $config['log_file_permissions']; } } // -------------------------------------------------------------------- /** * Write Log File * * Generally this function will be called using the global log_message() function * * @param string $level The error level: 'error', 'debug' or 'info' * @param string $msg The error message * @return bool */ public function write_log($level, $msg) { if ($this->_enabled === FALSE) { return FALSE; } $level = strtoupper($level); if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold)) && ! isset($this->_threshold_array[$this->_levels[$level]])) { return FALSE; } $filepath = $this->_log_path.'log-'.date('Y-m-d').'.'.$this->_file_ext; $message = ''; if ( ! file_exists($filepath)) { $newfile = TRUE; // Only add protection to php files if ($this->_file_ext === 'php') { $message .= "\n\n"; } } if ( ! $fp = @fopen($filepath, 'ab')) { return FALSE; } flock($fp, LOCK_EX); // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format if (strpos($this->_date_fmt, 'u') !== FALSE) { $microtime_full = microtime(TRUE); $microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000); $date = new DateTime(date('Y-m-d H:i:s.'.$microtime_short, $microtime_full)); $date = $date->format($this->_date_fmt); } else { $date = date($this->_date_fmt); } $message .= $this->_format_line($level, $date, $msg); for ($written = 0, $length = self::strlen($message); $written < $length; $written += $result) { if (($result = fwrite($fp, self::substr($message, $written))) === FALSE) { break; } } flock($fp, LOCK_UN); fclose($fp); if (isset($newfile) && $newfile === TRUE) { chmod($filepath, $this->_file_permissions); } return is_int($result); } // -------------------------------------------------------------------- /** * Format the log line. * * This is for extensibility of log formatting * If you want to change the log format, extend the CI_Log class and override this method * * @param string $level The error level * @param string $date Formatted date string * @param string $message The log message * @return string Formatted log line with a new line character at the end */ protected function _format_line($level, $date, $message) { return $level.' - '.$date.' --> '.$message.PHP_EOL; } // -------------------------------------------------------------------- /** * Byte-safe strlen() * * @param string $str * @return int */ protected static function strlen($str) { return (self::$func_overload) ? mb_strlen($str, '8bit') : strlen($str); } // -------------------------------------------------------------------- /** * Byte-safe substr() * * @param string $str * @param int $start * @param int $length * @return string */ protected static function substr($str, $start, $length = NULL) { if (self::$func_overload) { // mb_substr($str, $start, null, '8bit') returns an empty // string on PHP 5.3 isset($length) OR $length = ($start >= 0 ? self::strlen($str) - $start : -$start); return mb_substr($str, $start, $length, '8bit'); } return isset($length) ? substr($str, $start, $length) : substr($str, $start); } } core/URI.php000064400000035706152270514220006657 0ustar00config =& load_class('Config', 'core'); // If query strings are enabled, we don't need to parse any segments. // However, they don't make sense under CLI. if (is_cli() OR $this->config->item('enable_query_strings') !== TRUE) { $this->_permitted_uri_chars = $this->config->item('permitted_uri_chars'); // If it's a CLI request, ignore the configuration if (is_cli()) { $uri = $this->_parse_argv(); } else { $protocol = $this->config->item('uri_protocol'); empty($protocol) && $protocol = 'REQUEST_URI'; switch ($protocol) { case 'AUTO': // For BC purposes only case 'REQUEST_URI': $uri = $this->_parse_request_uri(); break; case 'QUERY_STRING': $uri = $this->_parse_query_string(); break; case 'PATH_INFO': default: $uri = isset($_SERVER[$protocol]) ? $_SERVER[$protocol] : $this->_parse_request_uri(); break; } } $this->_set_uri_string($uri); } log_message('info', 'URI Class Initialized'); } // -------------------------------------------------------------------- /** * Set URI String * * @param string $str * @return void */ protected function _set_uri_string($str) { // Filter out control characters and trim slashes $this->uri_string = trim(remove_invisible_characters($str, FALSE), '/'); if ($this->uri_string !== '') { // Remove the URL suffix, if present if (($suffix = (string) $this->config->item('url_suffix')) !== '') { $slen = strlen($suffix); if (substr($this->uri_string, -$slen) === $suffix) { $this->uri_string = substr($this->uri_string, 0, -$slen); } } $this->segments[0] = NULL; // Populate the segments array foreach (explode('/', trim($this->uri_string, '/')) as $val) { $val = trim($val); // Filter segments for security $this->filter_uri($val); if ($val !== '') { $this->segments[] = $val; } } unset($this->segments[0]); } } // -------------------------------------------------------------------- /** * Parse REQUEST_URI * * Will parse REQUEST_URI and automatically detect the URI from it, * while fixing the query string if necessary. * * @return string */ protected function _parse_request_uri() { if ( ! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) { return ''; } // parse_url() returns false if no host is present, but the path or query string // contains a colon followed by a number $uri = parse_url('http://dummy'.$_SERVER['REQUEST_URI']); $query = isset($uri['query']) ? $uri['query'] : ''; $uri = isset($uri['path']) ? $uri['path'] : ''; if (isset($_SERVER['SCRIPT_NAME'][0])) { if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) { $uri = (string) substr($uri, strlen($_SERVER['SCRIPT_NAME'])); } elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0) { $uri = (string) 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 (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0) { $query = explode('?', $query, 2); $uri = $query[0]; $_SERVER['QUERY_STRING'] = isset($query[1]) ? $query[1] : ''; } else { $_SERVER['QUERY_STRING'] = $query; } parse_str($_SERVER['QUERY_STRING'], $_GET); if ($uri === '/' OR $uri === '') { return '/'; } // Do some final cleaning of the URI and return it return $this->_remove_relative_directory($uri); } // -------------------------------------------------------------------- /** * Parse QUERY_STRING * * Will parse QUERY_STRING and automatically detect the URI from it. * * @return string */ protected function _parse_query_string() { $uri = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING'); if (trim($uri, '/') === '') { return ''; } elseif (strncmp($uri, '/', 1) === 0) { $uri = explode('?', $uri, 2); $_SERVER['QUERY_STRING'] = isset($uri[1]) ? $uri[1] : ''; $uri = $uri[0]; } parse_str($_SERVER['QUERY_STRING'], $_GET); return $this->_remove_relative_directory($uri); } // -------------------------------------------------------------------- /** * Parse CLI arguments * * Take each command line argument and assume it is a URI segment. * * @return string */ protected function _parse_argv() { $args = array_slice($_SERVER['argv'], 1); return $args ? implode('/', $args) : ''; } // -------------------------------------------------------------------- /** * Remove relative directory (../) and multi slashes (///) * * Do some final cleaning of the URI and return it, currently only used in self::_parse_request_uri() * * @param string $uri * @return string */ protected function _remove_relative_directory($uri) { $uris = array(); $tok = strtok($uri, '/'); while ($tok !== FALSE) { if (( ! empty($tok) OR $tok === '0') && $tok !== '..') { $uris[] = $tok; } $tok = strtok('/'); } return implode('/', $uris); } // -------------------------------------------------------------------- /** * Filter URI * * Filters segments for malicious characters. * * @param string $str * @return void */ public function filter_uri(&$str) { if ( ! empty($str) && ! empty($this->_permitted_uri_chars) && ! preg_match('/^['.$this->_permitted_uri_chars.']+$/i'.(UTF8_ENABLED ? 'u' : ''), $str)) { show_error('The URI you submitted has disallowed characters.', 400); } } // -------------------------------------------------------------------- /** * Fetch URI Segment * * @see CI_URI::$segments * @param int $n Index * @param mixed $no_result What to return if the segment index is not found * @return mixed */ public function segment($n, $no_result = NULL) { return isset($this->segments[$n]) ? $this->segments[$n] : $no_result; } // -------------------------------------------------------------------- /** * Fetch URI "routed" Segment * * Returns the re-routed URI segment (assuming routing rules are used) * based on the index provided. If there is no routing, will return * the same result as CI_URI::segment(). * * @see CI_URI::$rsegments * @see CI_URI::segment() * @param int $n Index * @param mixed $no_result What to return if the segment index is not found * @return mixed */ public function rsegment($n, $no_result = NULL) { return isset($this->rsegments[$n]) ? $this->rsegments[$n] : $no_result; } // -------------------------------------------------------------------- /** * URI to assoc * * Generates an associative array of URI data starting at the supplied * segment index. For example, if this is your URI: * * example.com/user/search/name/joe/location/UK/gender/male * * You can use this method to generate an array with this prototype: * * array ( * name => joe * location => UK * gender => male * ) * * @param int $n Index (default: 3) * @param array $default Default values * @return array */ public function uri_to_assoc($n = 3, $default = array()) { return $this->_uri_to_assoc($n, $default, 'segment'); } // -------------------------------------------------------------------- /** * Routed URI to assoc * * Identical to CI_URI::uri_to_assoc(), only it uses the re-routed * segment array. * * @see CI_URI::uri_to_assoc() * @param int $n Index (default: 3) * @param array $default Default values * @return array */ public function ruri_to_assoc($n = 3, $default = array()) { return $this->_uri_to_assoc($n, $default, 'rsegment'); } // -------------------------------------------------------------------- /** * Internal URI-to-assoc * * Generates a key/value pair from the URI string or re-routed URI string. * * @used-by CI_URI::uri_to_assoc() * @used-by CI_URI::ruri_to_assoc() * @param int $n Index (default: 3) * @param array $default Default values * @param string $which Array name ('segment' or 'rsegment') * @return array */ protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment') { if ( ! is_numeric($n)) { return $default; } if (isset($this->keyval[$which], $this->keyval[$which][$n])) { return $this->keyval[$which][$n]; } $total_segments = "total_{$which}s"; $segment_array = "{$which}_array"; if ($this->$total_segments() < $n) { return (count($default) === 0) ? array() : array_fill_keys($default, NULL); } $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] = NULL; $lastval = $seg; } $i++; } if (count($default) > 0) { foreach ($default as $val) { if ( ! array_key_exists($val, $retval)) { $retval[$val] = NULL; } } } // Cache the array for reuse isset($this->keyval[$which]) OR $this->keyval[$which] = array(); $this->keyval[$which][$n] = $retval; return $retval; } // -------------------------------------------------------------------- /** * Assoc to URI * * Generates a URI string from an associative array. * * @param array $array Input array of key/value pairs * @return string URI string */ public function assoc_to_uri($array) { $temp = array(); foreach ((array) $array as $key => $val) { $temp[] = $key; $temp[] = $val; } return implode('/', $temp); } // -------------------------------------------------------------------- /** * Slash segment * * Fetches an URI segment with a slash. * * @param int $n Index * @param string $where Where to add the slash ('trailing' or 'leading') * @return string */ public function slash_segment($n, $where = 'trailing') { return $this->_slash_segment($n, $where, 'segment'); } // -------------------------------------------------------------------- /** * Slash routed segment * * Fetches an URI routed segment with a slash. * * @param int $n Index * @param string $where Where to add the slash ('trailing' or 'leading') * @return string */ public function slash_rsegment($n, $where = 'trailing') { return $this->_slash_segment($n, $where, 'rsegment'); } // -------------------------------------------------------------------- /** * Internal Slash segment * * Fetches an URI Segment and adds a slash to it. * * @used-by CI_URI::slash_segment() * @used-by CI_URI::slash_rsegment() * * @param int $n Index * @param string $where Where to add the slash ('trailing' or 'leading') * @param string $which Array name ('segment' or 'rsegment') * @return string */ protected 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 * * @return array CI_URI::$segments */ public function segment_array() { return $this->segments; } // -------------------------------------------------------------------- /** * Routed Segment Array * * @return array CI_URI::$rsegments */ public function rsegment_array() { return $this->rsegments; } // -------------------------------------------------------------------- /** * Total number of segments * * @return int */ public function total_segments() { return count($this->segments); } // -------------------------------------------------------------------- /** * Total number of routed segments * * @return int */ public function total_rsegments() { return count($this->rsegments); } // -------------------------------------------------------------------- /** * Fetch URI string * * @return string CI_URI::$uri_string */ public function uri_string() { return $this->uri_string; } // -------------------------------------------------------------------- /** * Fetch Re-routed URI string * * @return string */ public function ruri_string() { return ltrim(load_class('Router', 'core')->directory, '/').implode('/', $this->rsegments); } } core/Utf8.php000064400000010611152270514220007032 0ustar00is_ascii($str) === FALSE) { if (MB_ENABLED) { $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8'); } elseif (ICONV_ENABLED) { $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. * * @param string $str String to clean * @return string */ public function safe_ascii_for_xml($str) { return remove_invisible_characters($str, FALSE); } // -------------------------------------------------------------------- /** * Convert to UTF-8 * * Attempts to convert a string to UTF-8. * * @param string $str Input string * @param string $encoding Input encoding * @return string $str encoded in UTF-8 or FALSE on failure */ public function convert_to_utf8($str, $encoding) { if (MB_ENABLED) { return mb_convert_encoding($str, 'UTF-8', $encoding); } elseif (ICONV_ENABLED) { return @iconv($encoding, 'UTF-8', $str); } return FALSE; } // -------------------------------------------------------------------- /** * Is ASCII? * * Tests if a string is standard 7-bit ASCII or not. * * @param string $str String to check * @return bool */ public function is_ascii($str) { return (preg_match('/[^\x00-\x7F]/S', $str) === 0); } } core/Benchmark.php000064400000007770152270514220010112 0ustar00marker[$name] = microtime(TRUE); } // -------------------------------------------------------------------- /** * Elapsed time * * 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. * * @param string $point1 A particular marked point * @param string $point2 A particular marked point * @param int $decimals Number of decimal places * * @return string Calculated elapsed time on success, * an '{elapsed_string}' if $point1 is empty * or an empty string if $point1 is not found. */ public 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(TRUE); } return number_format($this->marker[$point2] - $this->marker[$point1], $decimals); } // -------------------------------------------------------------------- /** * Memory Usage * * Simply returns the {memory_usage} marker. * * 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. * * @return string '{memory_usage}' */ public function memory_usage() { return '{memory_usage}'; } } core/compat/hash.php000064400000015433152270514220010421 0ustar00 32, 'haval128,3' => 128, 'haval160,3' => 128, 'haval192,3' => 128, 'haval224,3' => 128, 'haval256,3' => 128, 'haval128,4' => 128, 'haval160,4' => 128, 'haval192,4' => 128, 'haval224,4' => 128, 'haval256,4' => 128, 'haval128,5' => 128, 'haval160,5' => 128, 'haval192,5' => 128, 'haval224,5' => 128, 'haval256,5' => 128, 'md2' => 16, 'md4' => 64, 'md5' => 64, 'ripemd128' => 64, 'ripemd160' => 64, 'ripemd256' => 64, 'ripemd320' => 64, 'salsa10' => 64, 'salsa20' => 64, 'sha1' => 64, 'sha224' => 64, 'sha256' => 64, 'sha384' => 128, 'sha512' => 128, 'snefru' => 32, 'snefru256' => 32, 'tiger128,3' => 64, 'tiger160,3' => 64, 'tiger192,3' => 64, 'tiger128,4' => 64, 'tiger160,4' => 64, 'tiger192,4' => 64, 'whirlpool' => 64 ); if (isset($block_sizes[$algo], $password[$block_sizes[$algo]])) { $password = hash($algo, $password, TRUE); } $hash = ''; // Note: Blocks are NOT 0-indexed for ($bc = (int) ceil($length / $hash_length), $bi = 1; $bi <= $bc; $bi++) { $key = $derived_key = hash_hmac($algo, $salt.pack('N', $bi), $password, TRUE); for ($i = 1; $i < $iterations; $i++) { $derived_key ^= $key = hash_hmac($algo, $key, $password, TRUE); } $hash .= $derived_key; } // This is not RFC-compatible, but we're aiming for natural PHP compatibility if ( ! $raw_output) { $hash = bin2hex($hash); } return defined('MB_OVERLOAD_STRING') ? mb_substr($hash, 0, $length, '8bit') : substr($hash, 0, $length); } } core/compat/mbstring.php000064400000010631152270514220011316 0ustar00 0, 'algoName' => 'unknown', 'options' => array()) : array('algo' => 1, 'algoName' => 'bcrypt', 'options' => array('cost' => $hash)); } } // ------------------------------------------------------------------------ if ( ! function_exists('password_hash')) { /** * password_hash() * * @link http://php.net/password_hash * @param string $password * @param int $algo * @param array $options * @return mixed */ function password_hash($password, $algo, array $options = array()) { static $func_overload; isset($func_overload) OR $func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload')); if ($algo !== 1) { trigger_error('password_hash(): Unknown hashing algorithm: '.(int) $algo, E_USER_WARNING); return NULL; } if (isset($options['cost']) && ($options['cost'] < 4 OR $options['cost'] > 31)) { trigger_error('password_hash(): Invalid bcrypt cost parameter specified: '.(int) $options['cost'], E_USER_WARNING); return NULL; } if (isset($options['salt']) && ($saltlen = ($func_overload ? mb_strlen($options['salt'], '8bit') : strlen($options['salt']))) < 22) { trigger_error('password_hash(): Provided salt is too short: '.$saltlen.' expecting 22', E_USER_WARNING); return NULL; } elseif ( ! isset($options['salt'])) { if (function_exists('random_bytes')) { try { $options['salt'] = random_bytes(16); } catch (Exception $e) { log_message('error', 'compat/password: Error while trying to use random_bytes(): '.$e->getMessage()); return FALSE; } } elseif (defined('MCRYPT_DEV_URANDOM')) { $options['salt'] = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM); } elseif (DIRECTORY_SEPARATOR === '/' && (is_readable($dev = '/dev/arandom') OR is_readable($dev = '/dev/urandom'))) { if (($fp = fopen($dev, 'rb')) === FALSE) { log_message('error', 'compat/password: Unable to open '.$dev.' for reading.'); return FALSE; } // Try not to waste entropy ... is_php('5.4') && stream_set_chunk_size($fp, 16); $options['salt'] = ''; for ($read = 0; $read < 16; $read = ($func_overload) ? mb_strlen($options['salt'], '8bit') : strlen($options['salt'])) { if (($read = fread($fp, 16 - $read)) === FALSE) { log_message('error', 'compat/password: Error while reading from '.$dev.'.'); return FALSE; } $options['salt'] .= $read; } fclose($fp); } elseif (function_exists('openssl_random_pseudo_bytes')) { $is_secure = NULL; $options['salt'] = openssl_random_pseudo_bytes(16, $is_secure); if ($is_secure !== TRUE) { log_message('error', 'compat/password: openssl_random_pseudo_bytes() set the $cryto_strong flag to FALSE'); return FALSE; } } else { log_message('error', 'compat/password: No CSPRNG available.'); return FALSE; } $options['salt'] = str_replace('+', '.', rtrim(base64_encode($options['salt']), '=')); } elseif ( ! preg_match('#^[a-zA-Z0-9./]+$#D', $options['salt'])) { $options['salt'] = str_replace('+', '.', rtrim(base64_encode($options['salt']), '=')); } isset($options['cost']) OR $options['cost'] = 10; return (strlen($password = crypt($password, sprintf('$2y$%02d$%s', $options['cost'], $options['salt']))) === 60) ? $password : FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists('password_needs_rehash')) { /** * password_needs_rehash() * * @link http://php.net/password_needs_rehash * @param string $hash * @param int $algo * @param array $options * @return bool */ function password_needs_rehash($hash, $algo, array $options = array()) { $info = password_get_info($hash); if ($algo !== $info['algo']) { return TRUE; } elseif ($algo === 1) { $options['cost'] = isset($options['cost']) ? (int) $options['cost'] : 10; return ($info['options']['cost'] !== $options['cost']); } // Odd at first glance, but according to a comment in PHP's own unit tests, // because it is an unknown algorithm - it's valid and therefore doesn't // need rehashing. return FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists('password_verify')) { /** * password_verify() * * @link http://php.net/password_verify * @param string $password * @param string $hash * @return bool */ function password_verify($password, $hash) { if (strlen($hash) !== 60 OR strlen($password = crypt($password, $hash)) !== 60) { return FALSE; } $compare = 0; for ($i = 0; $i < 60; $i++) { $compare |= (ord($password[$i]) ^ ord($hash[$i])); } return ($compare === 0); } } core/compat/index.html000064400000000203152270514220010747 0ustar00 403 Forbidden

Directory access is forbidden.

core/compat/standard.php000064400000011320152270514220011265 0ustar00?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ybcgmkl}f{t~npjae|dirsuvwxozhq.~1S '28OQ   ! 2 !!!!!!5!!!!!""""" """""%"+"<"@"C"E"M"`"e"}""""""""# #*$"%%%%%%&c&o 1R '27Q   2 !!!!!!5!!!!!""""" """""%"'"<"@"B"E"M"`"d"z""""""""##)$"%%%%%%&`&mx@ ka]b[Y?ߍki[Z0-,*&%޸ޚޙވZ=F۶۱ۮ۩ۢێ{TLRR"l{19:;|<}>?@A~{|}!!%!! @  1R376767676767676767676'&'"72767676767676'&'&X:'*       AB  | !%7' +,]\. & - e4cI#)) ' 0QS0   (2(Q3276745676567676767676'&'"!67676767676'&#373b7   $LR#  #RL$   7 !(:tu:_)9?)[ !BC!)Sq99qS)!CB! [)?9)_:ut:(! j'#'+"#"3733767677676767676767167633!76767676767676776767656763";!33276'4'&###!6767767656763;23276'&'&###6767676'&#'#!6767767676#2+!##"3633!!''#!676767676767656763!#  Q< &1 R#C# @  -   K(. ' U  ""j+S %7 q#   Q< &1 R#A$ @ #2  K. ' U    jS %7 rY    M    M%Lu))4 lt: ? 2((OJ+)!LS)~S (7nm7d (9Lu))4 jw< ? / &l&KW+~S JZ@c !(9""N(""N("'&'&'76767676'&33527676767676'&'&'&'&'2"3276'4'&'&'&'&'&'"'#"'&7455#&'&'&'&7476767676767#1:"!$'ZVn{ 8 ',+>  #NI`%a-7%!",&CBS) F5:"%?J#FCb  a L06 7~ a!,#$?i  $RXLDfIE$  )>)*#*#"" V;6ii{l\O;;#8 #31#,9"6!aIEMM4;J G#!)/8`B +r7676777676567767677676'&'&'&'&'&&'&#767676767676'&'&'%6'&'&5454547676773276767676'&'&'&'&'&#&6'&'&54545476767 3""'9 4Tn88oH$!FI J61bd J1( ASMX*-G)5(&-aNN& 'Tq:2,n>#)25(% "/l8 :/1 < w"   ;>O  n>#)25(% "/3  +h׏GH\.*ZbLF>$Xa:'#  2L 1$ 57Y&+(,""H>5+/!F Xu58!5" OgeD4!("6? F2"&"#2\$#e  UJNM36 J OgeD4!("6? F2"&b 77676767676723&767676765#'&'&'&'&'5676767676776767676767767235'2"#&''&'&'&'&'&'&''&767636767677676767676'&'&'&'&'&7&'&'&'&'&'&7676#'&'&'&5&767674367   "9 #(%)     !IBg  a-.1]X  R    '(= M)   pC  C/;+ !7%! ,93?SDF&     0,@!&       ()-/   G:FD B#   .te  :   p/'$3 ]/aa   !P   L;JE 7%!(&23+( 02I3>2D/2.1  #$$%, k?9;"       @7<3%%ENOD623677676767676'&'&'&'&'&7276767  ') ,$%!'/Y-^ %*# - <860( #(*/:B?E?2D'0n+ G76'&'&'&'&'&'&'&'&'&767767676767676'&'" <54- L5CHX   J:5%E r"    2<:Cxxwġp\dK   Nf^n>@OI,1+.(  L3"32767676767676'&'&'&'&'&'&'&'&  H94(H#     @96/+4?CO   H_Wh03ha1,.(    6@?H&|_V\OaQUD  p&'&'&'&'&'&'&&'&3"76776767676767677676'&'&'&'&'&''76'&'&#&'&'&'&'&'&'67676767676727676'&667676767676'&%/ 0   a  4343  a   0 /  J8 / 0   a  3443  a   0 /  J8 { & $  o'        'o  $ & $H4?)8 V+ & $  o'        'o  $ & $H4?)8 V+L!##";!767676'455!3327676'&'&'&+!5456'&'&VN    L..L    N=L    N,/L    Nr?0%7676767676'&'&'&'&#"7276767 Z + #"P *:2'D,.G )u)%*r&$#!,ZE-. d+!5!s+@ 72367676767676'&'&9AC  ~ ? /RT0  &/|' 37676767676767676767476'A1'M*6mm6!   !)!--_N"  WO r]h5'OO' 2X7op7u)T4 ,X \=BDx32727676767667654'&5&'&'&'&'&#&'&6'&'&'&5&5545474767676767673 F;@-s 9 % !!41)&P? 4^& KCB  .08OBB #"0 ?  0{KEAi4[)$-   4)- /)BU~706/`?G'(B3&6J @9 #!rI,J 48 !  (6X*7JFB) R^b &)0C61!* @H]D+,(IZ% @XC2;!#%5#535#5456'&+&!?77AP- B#@K6 !g(C!>aaa(  T,Qa#C *C1T)r$T%2367654'&'&7676767676767676'&'&'&2376767676'&'&6#"'&'&'&&'#&32767676767676736'&'&'&'J&Dt   4LGS %$04*(!"EopAAT5*1 Iglp}uN6   #.)1=&   E`L =!*U$h!(58:#   >u  )    $!  qx!   E+^2f q6c2`8@T#47676767623276'&'&'&273676767674'&'&'&'&'&#&763#"'&'&'&'45&'&76767z bP,Qu AK|nxO ^{qI5//$PDDe:I .*' ?'$/,%# (/?)tR,$*! + "-] m ];D 27bLT{$%-h()kXU,&V3  5 g,( *)^5TB)/{jc36767676763763636332767654547676767676767676767676'&5"'&'&#"'&#"'"'&'&5#(a  5 h  G![=B [:$JI &*&+ Ž[)g!,! ajc8'   R,w~SR:N(!+ C!_00T -1,2  % a:@P#767676'&'&'&'&'&'&'6767656'&'&'&'&'&6&7"''&'&'&'&'&'&'&'&'&'&547676767276723'&'&'&'&76767676767663j+!#)-K !52rY,+: S$C(W"[ E  ,# $>-  W  !1$#C s j   5#` ))0!?  #    #)IY^K|*~cJB>53&  0)MkO@1 1Wu94(%# ( Mr!qW    %" M| 51  ^}!#H<  a9Bp3'&'&'&'&'67676767676'&'&23676767676766'&'&'&'&37676767676'"'&'&'&'545&554567676767676767 b !   \ J9ND(%&#  #vE^Ve,")#LBC*6 @@b(.+/ #.)' ?85 3"(.  _! p^    %f%e)& BCHA6n@ 13BU}*-jYX-  ' )&>$N E-\-!0 K7-6  A72767676767676'&'&72367676767676'&'&9AB  ~ AC  ~  0QS0  &/ /RT0  &/q X72767676767676'&'&767676767676'&'&'&'&#"72767679AB  ~ h   # [ P  j".P 0QS0  &/*532- NEn$x:*8 LcZ67676767676767676767656'&76'4'&'&'&''&'&'&'&'&''&'&':)2eB9si4C}2 $10+C~ ~d%F@=G9I ?7=t8} C+01#O&FSQQRQ"?  0>!61!:"3 >=o/"A"%+$ 7 ;m> 3"&G !I)(&'% $:;!!27676'&#!!#'"32;!!27656'&#!!#'"4) E )+1 ,T 4( E#(+0-T ! 5,4 86+3 LgZ76767767767676767676'&'&'&'&''$''&'&'&:)2eB9rj4C|3 $10+C ~d%F@=G9I ?7=t8}e ~C+01#O&FSQQRQ"?  0>!61!:"3 >=o/"A"%+$ 7 ;m> 3"&G !I)(&'% `6723276'4545&7676767676767676'&'&'&37676'&'72767676767676'&'&%Z?   )   +(3J/oFcXGnD ($# XAB  |  @ $ !% 6:=?9\ & 6 0%## 1+(# ,!:KF+ c>^ 0&i 2 0QS0   (27676767674565&'&'&'&%&%2767676767767676'&'&'&'&'&'&47%6'&'&'&7655456'&'&'&#"'"'1&'&'&'&'&'&767676676#"'&'&'&'&5&7676767767 6\!!+ ();67:494F?B8Y@= ix][[Y $  gnknm[hY601(gIAD6e2-  !&(  4<8?_RX># nUM9-SA !'(+7<5+'(#      ! % (У #"#1\{% E8 5! $R 0V    !$A%2.5;=|K %  8  ?ԑ(  /)>09A:qU/"& Tp7775"'&'&&'&776767676776743676;!#%5+'&'5&'&'&''&''&'&'&'&'&'&'&#"6##!7?T](*    q R7&/)Sq6""  ()('AKAN 3U     )0k5 aaa =.   Daa As e)QR)   Q0a\//,0, / &KK&55&u-O~;Nb3#!2#6767676767676'4'&'&'&'&'�'&'&'&'!!!236##!! %#"#!Ox%! WLm'  {B  S +'0qC35, HHYR/G'"E }aEa@ ! aB: &G17wY",,)4M+aU!I@U M)$##"76767676765454'&##'"'&'&'&'&'&'&7676%6763732767676'&55454'&#"#1"''&'&'&'&'&'&'&" 17n`gPm''vkIQ   %#3NNE;?/z=o# /",%eRQ/          [l9 *-C94MUi."  =53(m!/{!&H6v DB_ , ?K       , O!C3#!76767676767676'%&'&'&!336'##OvW9KBH>SBE.. HTPW=]vJ9-L>G60#!9J@Q.9}aEa';u&aa&u>=V &a+'raPaa(D  "F?F"  D'\ HS%376'45535%!#&'"#&'&'&76767676767676763732767676'4555456'&#"##&''&'&'&'&'&'"76767667=&C {&1s!s !"14D?Jԑ;,,     .0131:.>ѻ<,+#Wvo~`Qk  m    Z@aaK E|GUB-<2B9<,/m->=G   U [     9JGRpxS52)  O}$3#%5#!#7%5#35%3!35%O5ޒ5ޒlޒ}aEaaIaaaaaD8}3#%5#35%'D?}aEaaa'9}K!'&'&'&'&&'67676'4'&727676767676'45535%\  /E' 7 y/&J/E!', 60N z}a1 Q'    -Oj/dI5L%,aO}3#%5#54'&76?6767##%5#"''&'&'&'&'&'&'&'&'&'&'&''&74?67677676767767635%2235%O5&g  ! 6b1 %I;r#0 & #F{=(+ }-[D"G  %$'L "####Jh3"`.ޒ}aEaa,X  U   + "FA%"aa'2 -\Q39  h&K9;aa>{U+S"aO%}#3#!7#+!5%'O-a   R*/ߒ}aEaB< RaRi}36#775"'&'&&'&74=332367676767676767676767676767673#7%5#35!#"#"#&'&'&'&'&'&'&'&'&'&'&'&'&#"##!R*D$,5n5,$D*  "")Qu=!& 35 "EE"  ދ (\#,UU++UU,#[}a; aa :_%LK%Z2:0<<@-n9;s(LL"DC" Daaa ;"ED"^^>=    >=^^"DE"; O~36#775"'&'&&'&74=332323276'&555545&767767635'2'&'&'&'&'&'&'&'&'&'&'&##!O*D$,5n5,$D*  5idȰX B! '   0J$,5n5,$J0 ,W':tN1@  f}a; aa  74   ?{uh%M' 0 /ߺ.  aa  (y0h0D[:K%  e0u#"7676764'&'&'&'&'&'&'&"6#&'&'&'&'&'&'&'&'&5&54767767676767T fY^Gc62 μ,YZl^eO!$CLtm!%!&9 F>@/! 04 ! !`$ &/"6+.D_~ û &(@WxhrYfB>S !3#'Oo"),$#K6v   _9r 1' u  P}!=3#%5#!236767676'&'&'&'&%2#!32##P5$ C?! &gA.h> . >h/}aEaa O [rmZ#QB]& 9 $<'&qrZ767676767654'&'&#"'&''6776767$4'&'&'&'&'&%&76767677#&'&'&'&'&&'&'&'5&5476767676767676'&7676769  #;?bN $1F`MB)<g8* /[%"_1 -S&'&'&'&'&'&'&'&'&'&'&'&'&'&5454'&#"#"3"76776767762&7676767676'&'&'&'&''&'&'&'&'&'&'&547676767676233"3327654=4'&'&#" $"%CCq   JFi9gWAC&*#$ I5E;()fX"0    !FBr )dO I&+1&) ="&0"E2/ >N   # !   $#$#m[W- ' $  X  "34A  L (0   Zc{6%  "#. b  !?;M j6 #Uf,36767676767633!%5!323/!  a=C4q`f;D3a  fy&,z7<\aaF5l0&yO}h3767676767656'455545&767767635'2'#'&'&'&'&76535%O1$@;O5<8>PIH 0J$,5n5,$D*" )7B?J  ޒ}av*fJ:6& b(R8  aa  5QL&937*    *2_?;a5}x;277276767677767676767476767767635'2#''''35''5# YCSG &g})= -W '-Y&$  '$II$   (w8}}a  ,4)6ė8A3E& ID.e?@ aa ,Y RR23  *Z }=a2 P}37676767676767676767677676767676777676767476767"767635'2#''''35'';2#&'&'&'&'&'&'&'&'35''2 H?HB   " ].    ( K !/.C+  )BR;-    $F- &u{+x"  %G)   6-- !x}a  'NM'<< 1 6)Q#(Sx55+ GHCHC3hB! B>z*:uZpD aa A3[v; O( 4d/=p6aa  "!  \l6 G$; ,F:ts:!Z)aF};66#775"'&#&#&'&'&'&7767676767676767767673#%5+'&''&'&'&'&'&'&'&'&'&'&''&5477676767676767676716767767635%233&'&'&'&'&''&'&'35''e(1`F# $%pB  *5FjBF   B:   7q7>' &Kp9 $76 -4GjBF    3+     $G }aBb0    00$T   aa    +VL&'    !JQaa +4hM!"  '.$FG$ aa   "D92b %a(}m33#7%5#54'&7676767676767676767676767656767767635'2'''''35%'(' ] R ޏ0 C@C@ "    #!)-Z! )  !BB! 'FH$}a'~w"-baa>c    +a^a^%1 aa )0`a0  :f!i5a(~j347676767676767633373!77#"##67676767676776767676'4514'&##! a   ^&00=zR%K $b a   i$00GGc3 #}p+) ^4 #GF#Yu6o)   -w$'54#! i3 #GF#ggM   Y!5#35!Q{ {u3'7676'&'&'&'&'&&'&''&'&'&'&C )^ÑH$I,!1 -/8p2"Bn9 / B+ *d3+YEkOG   7mp8w:QMBLDB43#!!4Q{{ > #&67676??55?77L=u^2 ; +qZH>/[4V'$    F* 'J*Es4d32;!327676'&#!##'"3( >$)-'!M 6+1 6&776767676767676'"#7676'&"  ') ,$%!'/Y-^ %*# - <860( #(*/:B?E?2D'0n+ @x52767636"767676767;76767654554'&#"#"'&'&'&'&7655476'&'&'&'&#""376'&'&''&'&'45&76767676767276767e : p8 65g]"V9 9" GQ G7  %K @Q>1 & +       9 j1|(+I@' -,;)  ? &)6',  JE232767576767677632&76767654'&'&"#6#'&'&'&'4'&'&74=45&7676767676767J'  G   &+&-wer~TOM-=yy=tR6 d #'B<6"'&I2&5 `ˁu $&/!  BS% )"'FLCw322&'&'&'&"#767676767%5"'&'&'&'&7655"#6'"'&'&'&'&545767676767$! !!#%',(-Nj%106[Y2.0+w'  =yy=[D%135,#pf "}a N t}*    e a5   ? (?(:&4 Q  @KY!33232767654'&'&'&'&'&'&767676767676'&'"#"'&'&5%!4767676GP8 16X,3/5! ~KyAA!! <03 +   JYM* &@h@9   gMT) hߑs $(3%  &{Dp,C) c>gG?u*0WD#3#775#35#545&76767676767636363276'&'&'&'&'&e#  #;!D "-3(&Fa4aaa ;   3"'#U#"2gAd77676767654'&'&'&'&'&'&'&'&##'&'&767677676'&'&'&''&'567676763367676'&'"#'&'&'&'&'&&6"##&'&'&545&76767671633 #2"'&'&'&'&76767H17 g$.A9j '!-[9g<)1!  $!"60Xt  (,3  ;:  MOgVM,P    . $ ]7 Y.; 0 sc=+ #0a,3wG<(-3E >$aaV H$)(' /*X aaGN _pf  aM <72767676767676'&'&2322#75#"#4AB  | & ش`;l; 0QS0   (2a &aa8 d* j72767676767676'&'&232''56767676'&#"37676767676'&5"#xAB  | %'  " 5q  Z6$% :Q pV <?~~? 0QS0   (2a 1e=&N%&:+# !' Q"[ J232#775#5545&767636767""#75"3"'"#&'&'&'&'&'&'&'&'&'&'&'56767676767676767676767635'2"#J' cӎ 0  --    ޞR %@;  , *+     3c )=yy=}a >aa3  (   78 aa. 'OH%   $!" aa  )L  a[232#775#"#a) e؎=yy=}a >aa- \}2322#775#45&7676767676#775#45&7676767676#775#456'&'&'&'&#&'&'&'&'&#5"#\ # gݎ(56.a % aaV H$)(' /*X aaV H$)(' /*X aa E. a ] ? [R2322#775#45&7676767676#775#456'&'&'&"#5"#[ # gݎ(56 *~z  A%&-gyN.+ J =$%%$ >) '!,AG(Jr8u23223#775#37676767676'&'&'&5"#62'&'&'&'&'&'&74=45&7676767672767J) gݎ"5:;6U  ]+  2" .,= JD2322#775#4767676767633276'&'&'&'&#&#5"#J # e5a'$?0#, 9EUB 9rq9a % aa^/N<'8/",%?$ /## KR#'&'&'&'&'&'&'&#1"76767677632276767654'&'&'&'&'&'&'4567676767676733276'455456'&"#"''&'&'&'"##&  ];\ L##X, #StH   . ESKfD(:6?CX- T )&`5  4 3; ,Ez2,7 #*!17   -  3"   9NmK, #; % - & &  ,;#37676767676'&5#'&'455!5!#Z , ,8yF  a'  W .a334J- ?R: !'Q8  R$? qa[t32323276767676747673%5"#"'"'&'&7455"#2322'"'&'&'&'&'&545"#[5  '*i'./,,$ l # 5J+ #  Cg 3 6M.a @ ?A    a ( H a $n 8(%& , !C k 6m376772767676767676767767672767635'23'&'&'&'&'&'&'35''6^  j4  !,  +-3.5      5  $ .- nޭZa .Au8)1   [/emcmaa"#6r.K'D 0``0Ga3q376767676767676767676767673767676767676767676767676767635'2#'''35''3763#/35''3Y  AA "           % 5&0)      ' 8q,s͙PW  !IM sݧWa  2LPP%%+  $""67>3  2?94 "#  &\xe-&)aa  01aK&!C#k3aa  "E9C<   ROa.376#775"'&'&3&'4776767676767673#75#'&'&5&'&'&'&'&'&/&54776767676767676767672767635'2#&'&'&'&'35''8g22    !C"  #J    2    &E"OاXg  A* !4 !$J   8    "?OاXa   ;;! %K&aa  8    +O-aa   'L2 '; aa #?   &H(a-f3762'"'6767676'&'&76767677676767677676767676767"763235'23''35''&'&'6b ;K$  g  QT &UMG3&  #HG#C!  1   #6 !7nZ! a  # #>{P#$##    ;( \Gz 2/L'T32LLB  aa#!Gt+B"?vsaB4K34767676767233#;!7###67677676767676'&'&+!{ a5f_$I'6H"#$ " z a =ae v!Dz= `S$$a0^2$F\,//!)v$D/X( +XP $%"6767676767676'45545476767676323276'4'&##"##7"#"323332767676'4'&#"#"'&'&'&'&765456'&'&'&'&'&'&' N+  ҇-%+$?+0  7/E    }6 F(*    z*+N -!> ,U.d(   (-;&R I#?/( T1o .&""B   S)] < ?!- %7276765455456'&1>"#CB& 7C! 7C #"#";27767676767676'&54'&7676767672327676765&'&#"#&#&'&'&'&745456'&'&'&'&'&'&#"'&3233 N+  ^ -%+$?+0  7/E    }6 D!()    {*+N -!= U.e'  (-;&R I#?/( T1n N 0%!!D  !S)] ?!-!367676767675''&6 Wt;Vn6 FFGf2 -8&{2   +- tV  T72767676767676'&'&72767676'&'&'&'&'&''&'&5&'&'"YAB  |     6&(     0QS0   (23/)V+ZoJ~)) '#&4&?]\.-F#& |#'"373&#"767676767677637676767654'&'&+"'&'&'&'6545376545456'&+45476767676323&76'&'&'&'&"#"'&'&7676p  l98B:9$7*:$#[L &*~\bPI7:    "3I\   - +IG B<z 54Q>E% 4.A & &.+1 ! { *A9#   &/2D    8 2u  (77 + !QK" t2..'  +/D "$#>   g'&'&'&'2767654'&#"376'&'&'&'&'&'67676767676767654'&'&'&'&'&'&'&'&7676"3276'4'&'&'&#&'&'&'&'&'&7676767676  * 61## H2R-/ "*/'E ++l &%'  * 61## H2R-/ "*/'E ++l &%' `%  `% 7 (( }W  .07,0sC.!;>"6!13Rd.* (( }W  .07,0sC.!;>"6!13Rd.*6 `.+*" `.+*"<R376'4'&'&'&'&'&'&'&'&'&'&5476767676767676767656'&7676'&'&'&'&'&'&'&'&'&'&54767676767676769S* "6&N   &  44   ##   02" #Ff3  &*B!.` &  $#'/#4     ,YA    [#DE#* **./ !    '$8  )j74 zv.7676515456'&'&'&+!#'&3633!#A !" Bg$9 #{!D"??:q K ; V!##";!!"'&773!337676'&##!!3327676'&'&'&+!5456'&'&'&VN    L.DbG-8'(b8;'7.L    N;  =Y,N    Lp]N7676'453327676'45337654'&"##!'"3. #h $+K8$KCH>6,/!M! o"#5!_W *J . 3  3)#')0pULz5  ^ 72367676767676'&'&9AC  ~  /RT0  &/PS327767676?6776'&'#&'&'&'&'&'&'&5&336767676767677676'&/&'&'&'&''&%        ;z#   $&$&',$   ! $   45  #" '   &"C<     4>.C!   H*'  -.,./6,[   #.:     &J4; #EF#*  #..)) f 72767676767676'&'&"#"'&'&'455&76767676767676765456'&"767676767676'&#AB  | 1 .;*";      '#- -9 4X7?!/$rK3'$<:%!   0QS0   (2  4; U 9 %)+((0.)&  B_4//  % 4JD+($ T}36#775"'&'&&'&7767767767674767633!#!7#"##32#3#2##32'3'!!77?3| , 'PO( ( !!(-^%$ fQ $G    D7'a#7 hfBYz* aa *zYBjeA(!% $a+`&w/8}a, 4k^^ ?_0 aa  7S 'aIQ [C (S?S( CH GSa0Zq"i#&''&'&'&'&'&33676767677$6767676'&'&'&'&'&'&''&5&77676767675&'&'&''&'&'&'&5576%2#"'&'&'&'&''&5477676767676767676767676767)  %%&&hh  %&.49CC)  F3272999 "%>   , / 88:x[ 'X~~m:LZi|nc 7me4!AD"  <#  `]624/5-/&+R^0<  "195.*03= 2  -#E;D!  7 >LGA .+1I3    #d    ~Ek!' !/:L>D(3 %    $j,+;) $rDSB/;L"J 5   -  ::4"J >_3276767656'&'&'&'&32;!!27676'&#!!#'"3276767656'&'&'&'&#  W=33( E#(+1 ,T #  W=  #' 9kT7 6+4   #' 9kT7 ?'kir'%&'&'&'&'&"676?6767$76'&'&'&'&'&''&5&?6767''&'&'&'&545&7676'&''?77 D !(, {dn?KS     + J  .-HQ F + Q] +E;6 80 *?>9 T=i-kn 16`tu  %# w-os,r  (ʕ  :X+P~5=q%@ Ot '3b.aM2322#75#"#h& ش`;l;a &aa8  i!7#"##3323#+3233'!'&'&'&767676!63"#"'&'&'&'&'&'&'&77676767677'a"4 eY;Cv.aa.vC;YQ %a+jD.\n765ƖK=?,#.:9A))7n\.Gmh 6e$  *&%*'A;<.5'$  %/ 7IP  ^H? (:?:( ?TFS Q)78F6>%:,5(:)h3+D.  /7KEP$%$&h_1  @p%37676767676'&'&'&'&'&5!33767654'5&'&'&'&&'&'&'&'&'&#&76767676762"'"#&'&'&'&'&5476767676767!4767676 3;7=F>C:/%%%*(0)+N% x Zf?C# " G!   n )(lH"22;BKFLMDJ= *a C69U!$1- c 6&#+  & 2Aq`;    $#.)  ' Ac!(   'R\  ', J |r6** '!#9:~ ,B    X 1!{C  $ nCV@2;K 77676767676767645!7676'4'&'&'&#"#"'&'&'&74553323276'45476'&'&'&###!#'&7676767623] ' l  0=f\>?  $+2#*/  p6'Q>(  (U ŽH$:. '6c '9K*A4f;LAB_    &K %L  9 r  5  W!5!gWJJ 2W!5! 2WJJ6m&776767676767676'"#7676'&"!&776767676767676'"#7676'&"k  &) ,$%!'/Y-^ %*#   &) ,$%!'/Y-^ %*# - ;77/) #(*/:B?E?2D'0n+ - ;77/) #(*/:B?E?2D'0n+ K6m23677676767676'&'&'&'&'&7276767!23677676767676'&'&'&'&'&7276767c  &) ,$%!'/Y-^ %*#   &) ,$%!'/Y-^ %*# - ;77/) #(*/:B?E?2D'0n+ - ;77/) #(*/:B?E?2D'0n+ Y&'&'&'&7676727674767676767654756'&'&''&'76765&'&'&'&4776767676'4'&'&'&- e: D3  %  %  3D ;g)   !0_  1 !0RG 8$o:&M! ySK4838  :;9;9KTy !M&:o$8 GR0! 1  9(_2)!V0\*8ee&'&'&'&7676776''&'&'76765&'&'&'&67676767676'&'&'&'&&''&'&76776776'&'&''76767656'&67676767676'&'&'&'&- e: D3   !0d /  3D ;g)   !0d / $ %H4Z $   !0d 0$ Z4H% $   !0d 0  1 !0RG &%9&# !\Ax#&3 GR0! 1  &%9&# !\Ax#&3g: S, , '$;%" !\Bz%&C , ,S :'$;%" !\Bz%&CZU6763676&'&'&'&7$767656''&'&'#&'&7676'4'6'&'&'&'&'&'&74545&76767673(|!w" "'0.7->tbhE^ %@;H1<0A n@ZWd7V_#rH%BITIE)& 98D XY #Ga%2,7k :#..0Xy-*,&?51 OJ=K42 f&307 i #U/"+~ .+NGY:(B,=)' I I j'?37276747767676767676767676'&'&'&'&q  a?j6% "T- D-\0  -8jb(}> $  !j]:t: '   D*H*% ;   2b`&:   !5'Ne2sZ Eq <"  ("9fg4E##l376767676767676'&5&'&'&'&'&'&#&'&''&'&'&'&'&767676767676#"'&'&'&'&'&'&''&54776767676767676"#'&'&767676767x$$(+M]Wa.(-(NDD0 w"$$(+M]Wa.(-(NDD0 w":'WSl   >AHLO*0y   OT_dwk1)3*:# $* $1 /.B!"=A QE%"J ~ $* $1 /.B!"=A QE%"J ~E gHE  %  >). 6-  O/5 rf_L Z#h27676'4'&#"727676767676767676767676767676"3276'&'&'&'&"'J&B&AikWU,)" %Z>J&B&AikWT,)" #a>$W-#.&aFCe/gM1 Q'/ 0$W-#.&aFCe/gM1 Q' 5/''#!#"#763!76767676767676767725676;!337654'&###!6767677676776763!3327676'&#!6767767676767676"+!##&3633!+ ^f':$:Og  G"   7>   #w8%- ]X\-:%9P   8  #f   (('( "?w8%3i>  = ##@T&   AJ+ $; 5j  =4 C!BB! !b %]^]^K+   #;kdZx67676767676767676767656'&76'4'&'&'&''&'&'&'&'&''&'&'32;!327676'&#!+&:)2eB9rj4C}2 $10+C~ ~d%F@=G9I ?7=t8} C+01#O&FSQQRQ"?  4' <#)-'#M0>!61!:"3 >=o/"A"%+$ 7 ;m> 3"&G !I)(&'% 6*0kgZx76767767767676767676'&'&'&'&''$''&'&'&32;!327676'&#!+&:)2eB9si4C|3 %00+C ~d%F@=G9I ?7=t8}e ~C*11#O&FSQQRQ"?  d4' <#)-'#M0>!61!:"3 >=o/"A"%+$ 7 ;m> 3"&G !I)(&'% 6*0@\#3#775#!336#775#!54547676'7456'&'"'&#""ؘe؎.N e؎<34*  k KGk) ~1%+ a4aa !|aa@ `-m1s`FB8 (*@6Z#3#775#!#775#"#'"'&'&'&'&"!545&7676ؘe؎e؎7    +!f5%+  F 0./" a4aa4aa-3 '.-\ #  $ C IKq76777676737636767676/'&'&'567677776'&'&'&'"'&''&= V2*4 V  V 5* 8V V 9 *5V D/$>X !V2 7 V   V9*6 V!!V 7*9V  |D/ ,:X"%6767&'&'&'&''&u $J A8l, "C.  ! ! ,U Lt( $  L67676767767767"   i:$8 >*S*_ !  9e J3c. > #&67676??55?77L=u^2 ; +qZH>/[4V'$    F* 'J*Es4!367676767675''&6 Wt;Vn6 FFGf2 -8&{2   +- tr!5!Sjj)7676765#'&'&'&'&'&5# !"QOJGɉU J)*('  lj/+[O 72767676767676'&'&9AB  |  0QS0   (2g A32767676767676'&'&!32767676767676'&'&[ r  s   z  q  %{   %/z  $  #-w Ho C767676'4'&'&'&&632#"'&'&'&'&'&767677cD!<=e+/ G+. /`@'  & 2# ") #*L/1),A4(9J--  -36767676767676'&!6767676767676'&Q&%$ 4)  Q&%$ 4)  S5 %"! /%K  c+ J  %6&"&d32;!327676'&#!##'"3( >$)-'!M 6+1 %<8+27767767676767'"#> !%>0__0u )!!4gf4 3  <   ^     6Y/727767676767676767676!-49no,, Q%!;"3*oo&% RO*U^/$HH$ )N;#a8UEop>> &T U+Kj676767676767676'&'&%33676767654'&'&##&!33276767654'&'&##&376'&'&'&'&'&'&76767676767476'&##'& "# |&     1+$1 = 31 %"0  )G"   *  q  ""p !-3X,& &' "%&"!3?C!& %II%> =",($   *+[Z0%% Tp7775"'&'&&'&776767676776743676;!#%5+'&'5&'&'&''&''&'&'&'&'&'&'&#"6##!7?T](*    q R7&/)Sq6""  ()('AKAN 3U     )0k5 aaa =.   Daa As e)QR)   Q0a\//,0, / &KK&55&u-O~Uh|3#2763632323632#6767676767676'4'&'&'&'&'�'&'&'&'!"#"#"'"'&#!236##!! %#"#!O(BEY%7*S4(>Uw%! WLm'  {B  S +'0q2O17%YEB(35, HHYR/G'"E }aEa@ ! aB: &G17wY",,)4M+aU!I@U M)O%r3#7%5!3233'!%'Oޒ!b끏N 'a)raPaaV JHs:=[;)3276''&'&'&'&'&&'&'&'&'&'&'"!67676767676776767676767&  B"JT,0 G0yX  5,hs: ) L"JR1   *ST)C! 8 s;ܒ&KT*     .]L&ld#G#4 <&U--IIu9  OrO3#7%!7#6##323###3323'!%'Oޒ7'a"2 +&.LwkD; ~) aa )~ ;DXA!R $a+praPaI P BI %M?M% I  X Bq'S(~j347676767676767633373!77#"##67676767676776767676'4514'&##! a   ^&00=zR%K $b a   i$00GGc3 #}p+) ^4 #GF#Yu6o)   -w$'54#! i3 #GF#ggM   O}$3#%5#!#7%5#35%3!35%O5ޒ5ޒlޒ}aEaaIaaaaa,er#"767676&'&'&'&'&'&&6#"'&'&'&'&'&&767676767672735!3#!5#r n_eMH1./eeygqTU|$99 !KBE2! !"##75B1w,;9A Haaaa.1IE^XgVYŧ ).ITtGAJ "#6#,*/CQ>Y\Oс   Kc60/"  8}FFFFD8}3#%5#35%'D?}aEaaaO}3#%5#54'&76?6767##%5#"''&'&'&'&'&'&'&'&'&'&'&''&74?67677676767767635%2235%O5&g  ! 6b1 %I;r#0 & #F{=(+ }-[D"G  %$'L "####Jh3"`.ޒ}aEaa,X  U   + "FA%"aa'2 -\Q39  h&K9;aa>{U+S"aR7775"'&'&&'&7767676767676767676767#%5+"'&''&'&'&'&'&'&'&'&'&'&'4'&'&#"6#"#RU& %!/   ;:  .]#$;{" .]]. / %(5lC"    )A aaa $G+MM(8  4'1*x\+d/aa 'M/yy%|=   KHAHBX ?A! Ri}36#775"'&'&&'&74=332367676767676767676767676767673#7%5#35!#"#"#&'&'&'&'&'&'&'&'&'&'&'&'&#"##!R*D$,5n5,$D*  "")Qu=!& 35 "EE"  ދ (\#,UU++UU,#[}a; aa :_%LK%Z2:0<<@-n9;s(LL"DC" Daaa ;"ED"^^>=    >=^^"DE"; O~36#775"'&'&&'&74=332323276'&555545&767767635'2'&'&'&'&'&'&'&'&'&'&'&##!O*D$,5n5,$D*  5idȰX B! '   0J$,5n5,$J0 ,W':tN1@  f}a; aa  74   ?{uh%M' 0 /ߺ.  aa  (y0h0D[:K%  wf-:h34767676767%2363!233#3/!35!3#!5#!?#6###!"3"''&'&'&'&'&5# a \BaK6$1)"   a aaa/a 7 a   +K1E;) afOe&!  !&eO:]____ jSSj!+""+!e0u#"7676764'&'&'&'&'&'&'&"6#&'&'&'&'&'&'&'&'&5&54767767676767T fY^Gc62 μ,YZl^eO!$CLtm!%!&9 F>@/! 04 ! !`$ &/"6+.D_~ û &(@WxhrYfB>S !3#'Oo"),$#K6v   _9r 1' u  Or3#%5#!#7%5#35'!!%O5ޒ5|~raPaaPaaaP},H3#%5#!236767676'&'&'&'&%2#"#"#"'"'&#32##P5$ C?! & T2Q1:&ZED).h> . >h/}aEaa O [rmZ#QB]& 9 $<'&!}z!7#'#!67676767674'&'&'&'&'&'&'&'!323'!+""3"33!(a$qJ$M9\YA-  % (NW, 1)8h=7!wBr#a+8    YPYR#" != 9rr9  *&7!TQ5( -0ak5!:1VS "  !'ocmc+,  5 3ee3 Uf/36767676767633!%5!323/!%!  a=C4q`f;D3a  HGfy&,z7<\aaF5l0&y%!7%5!45&767676767672'32323676'&'&'&'&#"#&'&'&'&'&'&'&#&23232767676767677632DbK &*.( (/  + >=N$'|cW7  4T`x#"'$N=> +  /( #1,)!Saaa Q($#`(     K75^R   |S]57K     )k#F"}Nl!!%5!52767676767$7456'&%&'&'&'&'!5%'2#"'&'&'&'&'&767676716763 :8664c>F k1 Y:6(&# '#%6Ƣ  a.-  1n    r* ",` }a .KVc]*aa  i\  au96h (%8#Dr $L8Q$(V1= F};66#775"'&#&#&'&'&'&7767676767676767767673#%5+'&''&'&'&'&'&'&'&'&'&'&''&5477676767676767676716767767635%233&'&'&'&'&''&'&'35''e(1`F# $%pB  *5FjBF   B:   7q7>' &Kp9 $76 -4GjBF    3+     $G }aBb0    00$T   aa    +VL&'    !JQaa +4hM!"  '.$FG$ aa   "D92b %a}!&'&'&'&'&'&'&'&'##"3"!%5!5545&7672367676767676767676767676767674745&###"'"!5%'2l #'!) )  "6LDT'Y: )3.1+8"  $5r` 3r"Ƣ}atT5g3(! + #E &$,.$8&" aa'  :NHU3W+&$ A%"R ai;%"'&#&'&'&5&'&'#!327676514'5&'&'&''&'&'&'&767676767676767621233!77#"#'677656'&'&'&'&'&'"#" UC,  a.MK        %  (,)-><?$ 3   LM.a  ,CU+ `X0718EQ&#ߛ=N$'|cW7  4T`x#"'$N=> +  /( #1,)!S  "* /YA-   "* /[?- Jaa Q($#`(     K75^R   |S]57K     )k#Fa676767767676'&3236767656'##"##'&'&'&'&'&'477676767676767676767654'&'&#'"&'&'&'&'&'&'&767676767676#2'"'&'&'5&76767676767,( -_5 ('$;FY@/* ! /(% #  ,?      #28c 8865*)&"  fRLA/  =; 3c7,C,O  +_2% U == 0 w2.C. (   NLOM *    )?   1#+   %"(8E 0.j  %  1+N   e/ 2(E78vB, Y/767676767676767676'&'&'&27676766767676767676716'&"'&'&'&'&'&'&767677676'&'&'&'&'&&'&'4'&767676767676767676767476'&''&'&'&'&#"'   '!%" Y#    C 7F=K |(   3638 C&o 2#"'a,   # *$ w((    -!"""CH;*Z 3    & %" &, M./  12pL &+ A:     !%   K('2  :      '( "  ? =]&+% [7,37676767676767676'&'&12767676767676777676767676332765554'&'&'&&'&'&#&767`  :)N_$           #19,> &  3  R+)3#RjXI$  #>.;N3 %J     ;*L?U $H G# "#><  '/3.5U$ _ |Xm6 !*+*+7oa^*D"_}p+"%?-"(   -!5&   ;~@+{676767676767676'&'&376'&'&'&'&'&'&76767676767476'&##'& "# |&    D )G"   *  q  ""p !-3X,& O3?C!& %II%> =",($   *+[Z0%% F8+Kk676767676767676'&'&%33676767654'&'&##&!#23676767654'&'&##&7676767676'4'&'&'&'&'&'&'&'&'&'&7676765476'&'&'&#& ."# |&     1+'2 =:' &1 4 $    t .(-&,3F 2$##*0rl 3> -""p !-3X,( &' !&' "$&2+ $(&*$H! /),"|  POE?@7C(@  L^=A3B@.8&\ `9'& %a%3236767656'##"##'&'&'&'&'&'477676767676767676767654'&'&#'"&'&'&'&'&'&'&767676767676#2'"'&'&'5&76767676767gFY@/* ! /(% #  ,?      #28c 8865*)&"  fRLA/  =; 3c7,C,O  w2.C. (   NLOM *    )?   1#+   %"(8E 0.j  %  1+N   e/ 2(E78vB, A;Q776767676'&'&'&'&'&'676'&'&'&'&#"#7676'&5&'&'&'&'&5&56''&'&'&'&76767676767676776323"'&'&'&''&'&7455456767676767676767676767!; A?A8<*oRhSHcߋa  !He  a     + O  K(   \ 84I%$)'GLBA  )#.""##"N!.{vh_'}X ,Y".kEEEDU)7V64646C!H$!&1&+  , *>%%RLG6 / ;TFhH`PN$+'&! ?&'&'&'&'&'&'&'&'&#7332767656767676763676'&5&'&5&'&'&'&7676767676567676767276'&'&   QmF2+   %! B.?oMWg<,V21w]   # +=6M   !W [^"! d h<r   E&K.#7 <    bl""7$767676'&'&'&''&'&'&'&7676'776767676'&''&'&'&'&'&#"23'"'&'&'&'&'4767676767676"c $,).BDv ncg . $!m-  !%!'JGLHH:o !/(7  p "K2!4;DE " _ kx +4/7!"01shBDg 1' S     L3A;;34  F eicB(- d9AI;E9'! Y27676766767676767676716'&"'&'&'&'&'&'&767677676'&'&'&'&'&&'&'4'&767676767676767676767476'&''&'&'&'&#"' C 7F=K |(   3638 C&o 2#"'a,   # *$ w((    -!"""CH;*Z 3   12pL &+ A:     !%   K('2  :      '( "  ? =]&+% ^L372"#767676'&'&'&'&'&'"'&'&'&'&'&74767676%6767676767676'4'&'&'&'&#&'&'&55&'&"327676777+8 W37 1  .336 ,.<- c/GKb!#T-  N& #! -'@&     "3*E)=4/bP=,E!  #C jt|k G  $f]2?AB/7OPCC  &)!5  U $gU*[712767676767676777676767676332765554'&'&'&&'&'&#&767        #19,> &  3  R+)3#RjXI$  #>.;N3 %J "#><  '/3.5U$ _ |Xm6 !*+*+7oa^*D"_}p+"%?-"(   -!5&   ;#7674'&''&'&'4'&'&''&'&'&'&'&'&=456'&'&'&#276'&547676767676767667'&#&'&'&'&7676     /a{jP   e%3,8$&(  6&)"@#!1    @JH 4(5+E?<.uZB&(0~6&   '/,R< ),j&! $$E8qV K) 0? w4cO *1% ( "2" ] ?? -OM )&:5@(=,;?K  T 5F\f~@O376'&'&'&'&'&'&76767676767476'&##'& )G"   *  q 3?C!& %II%> =",($   *+[Z0%% <4765&'&'&'&32767676747636#236767676767676776776767676'&'&&'&5476745676767676767676767676177??jP8 + #  -   ($'$7   )NP)/9?g_;  -$Eb  )#(# + !,6$J""PQ2 "'@! 5^%+   .# 'QS'-%,#!tGMB B 8"*     $ !)7$<%>Y32767167676'&'&'&'&'&'&'&&'&'&'&'&'"#&763"332767676767676767676767i   LE?H .+ ./OnJ9w##  &95.%   7Cr e "=;!   )P> `  11   )$7 "%"%!A% VFTJ6 Vc733676767767327676767676'#"#"'&'&'&7676767676765456'&"#'&'&'&'&567676'45&76'&'&'&'&'&'&'&55#3%&,7>c  !$/  1#  "   (   U <  1M~& $ & 8#y  7$+ ( c   1"&/)8 , '2 e]*) 3I"~ *&]OdB0'-4$3Z2"<FA   #"+'*&(! w #QO]U`T&''&'&76367676767676767676'&'&'&Q7VE  T;?   _>L$ 5!&  #&%%#V!(."  V^ek!#"#   PN^b"&#'l`7 +1 [F4'&'&'&232767"#"767676767676767676'&'&'&'&'&'"'&'&'&'&'&'&767676767667676'&#&'&'&76767676767676676'&'&7# &6@'$5# 8 O  -!% p-;9A?_3D#&0!% \(/  A $296;#X?" % 1MODS_ V.&+$)Y ;qJ!= 7-P<>&2%0(ϟ> #.&'  HVs< $'+/x0"!)'   "!' : ;AkU   *+..#  -h'  8   !;Z   *by L767676&'&'&'&'&63'&'&'&'5&767676776767O 'D:@1EF>::4`r'f V   `. LB (قm  !|yS .!#.'&*v$ 'Lae4ad7767676'&'&'&#&7676'&'&'&'6&'&'&5&767676767676767677 "$gzx)ȣy( 2 't96"- k?"2)S&$, I,= 3`Vb) 1e|OL;26(}V'&.g=4:0 *k1J M8JE/ .KA3g3(T6&!_7T!727676765&'&'&'&'&'"#"'#&'&'&'&'&7676767632765&'&'&'&"33W ,1 %"%>a!A +WF!A:r.>K+6=1E -+)~@q''+M )9'w?)  ')0[;4 R0!  >cxz!cEr6$3376'4=4'&+"767676'&'&'&'&'%6'&'&'&'&'&'&'&7676767676767 6.   :7:%HBE>"mmy*+20h?_ # @+%U5  <% .0"& yy\rh     Rn%@T  - [8]7676'4'&'&'&#"#"'&'&'&7455!3376'4=4'&##!#'"767676763 2=f\>?  $+1#-M  m&B1 ) ( @li=LAB^   (P%L t f 5 $ N8h7676767676'4'&'&'&'&'&'&'&'&'&'&7676765476'&'&'&#&4 $    t .(-&,3F 2$##*0rl 3> $&2+ $(&*$H! /),"|  POE?@7C(@  L^=A3B@.8&\ `9'& %a@{7676'&'&'&'&'&527676767676767676'&'&'&'&'&'&'&767676767676'&'&3374'&547676767676p Wg !4.2,!7#!  ]TqlI6YG& !& ;kDLD%%k)q)6[G/5 /)7&#)& )QAJ%IY; $%$&)3HFL%(26 ULB1`BS"CJ%!&ZPE( " uVNb]k -($!s&:tt:!d8J07d*0L684/,a^%76767656'&'&'&'&'&'&'&#'&'&'&'&'&'&'&'&'&56767676767676767676767676'&'&#'&&'&'&'&'&'&'&'&'&'&7636763767476767676767676767  "/8U(  =/  & *E"   "4J   54    "/8U(  =/  & *F"   "4J   54  L  +704-'":     Fj   9?k3  "(OO(    +704-'":     Fj   9?k3  "(OO(  bA%4'&5676767676767676'45&'&##"'&'&'&'&'&'&7676767676767676336767676'&'&'4'&'&'4'&76376367676764'&'&'&'&'& "6U    $"E77 !   .75:  ) $  $<48/  :  C?d&K5B!dʠ'Ns91 '%H>>Wnunu y=&KM'   32C"'$)6*#    !##%_cߒ! 'N35( $54I!-]Y$$#" 9  .*}{uW!,l%76767676767656'&'&'&'&'&'&'&'&#"'&'&'&&'4767674767676767656'&'&'&16#'&767676767676'&/&'&76767676767xx\ 6*I!#        "    A   T* p 4  % S9B`dY A %%'!SSAL! 8;<>:.4)        ':     AR}  O ! IMZ\BEwM1  g E767676767676'&'&!767676767656'&'&'&'&376'&'&'&'&'&'&76767676767476'&##'&1 ::M    99O +  )G"   *  q   M88   !&  N::   &0>- }3?C!& %II%> =",($   *+[Z0%% N8 E767676767676'&'&!767676767654'&'&'&'&7676767676'4'&'&'&'&'&'&'&'&'&'&7676765476'&'&'&#& ;:O }  :9M + 4 $    t .(-&,3F 2$##*0rl 3>  N<:   #,  M87   '2?, $&2+ $(&*$H! /),"|  POE?@7C(@  L^=A3B@.8&\ `9'& %by+Lx676767676767676'&'&767676&'&'&'&'&63'&'&'&'5&767676776767H "# |&     'D:@1EF>::4`r'f V   `. LB ""p !-3X,& O (قm  !|yS .!#.'&*v$ 'LN8+676767676767676'&'&7676767676'4'&'&'&'&'&'&'&'&'&'&7676765476'&'&'&#& ."# |&    4 $    t .(-&,3F 2$##*0rl 3> -""p !-3X,( *$&2+ $(&*$H! /),"|  POE?@7C(@  L^=A3B@.8&\ `9'& %l/767676767676767676'&'&'&76767676767656'&'&'&'&'&'&'&'&#"'&'&'&&'4767674767676767656'&'&'&16#'&767676767676'&/&'&76767676767   '!%" Y#   Lxx\ 6*I!#        "    A   T* p 4  % S9B`dY   & %" &, M./ A %%'!SSAL! 8;<>:.4)        ':     AR}  O ! IMZ\BEwM1  O A3276767654'&'&'&'&!76767654'&'&'&'&3#!7#6##323###3323'!'>>  FF   xJA  _7'a"2 +&.LwkD; ~) aa )~ ;DWA!R $a+ /PQ/  .WV. #*  -[S. aEaI P HI %M?M% I X Bq'STp7775"'&'&&'&776767676776743676;!#%5+'&'5&'&'&''&''&'&'&'&'&'&'&#"6##!7?T](*    q R7&/)Sq6""  ()('AKAN 3U     )0k5 aaa =.   Daa As e)QR)   Q0a\//,0, / &KK&55&u-O};Z3#!2#676767674'&'&'&'&7#336233'!27676767636#"#!O,$>0/,9r9@c1P&K<'T (a+ ( %+.DdB) "   uB }aEaR"_seU4*':    X Ev'SP%6;I(O~;Nb3#!2#6767676767676'4'&'&'&'&'�'&'&'&'!!!236##!! %#"#!Ox%! WLm'  {B  S +'0qC35, HHYR/G'"E }aEa@ ! aB: &G17wY",,)4M+aU!I@U M)O%}3#7%5!3233'!Oޒ!b끏N 'a)h}aEaaV JHr;}7O3+367676763!2#3'#35!!67676767676767676765!$)?%%+  #z*abK nO`a*D  ."#}åtk400+  ;F58D?QaaN   (.+0\mbp89O}I3#!7#6##323###3323'!O7'a"2 +&.LwkD; ~) aa )~ ;DWA!R $a+}aEaI P HI %M?M% I X Bq'Sb }2'##775#"'&'&'&7767676767676767676767#7%5#54'&76?6767##%5#"''&'&'&'&'&'&'&'&'&'&'&''&74?67677676767767635%2235%3&'&''/&5476367767635'''$%  G"D[-}&-={F# & 0#r;I% 1b6 !  g&ޒ5&g  ! 6b1 %I;r#0 & "F|=-&}-[D"G  %$'L "$ޒ$~" L}a;9K&h 2:Q\- 2&aa"%AF" +   U  Xaa,X  U   + "FA%"aa&2 -\Q:2 h&K9;aatj aaq i?ta<56767676767676'&'&'&'&'&'&'&'&'&'"'&7"#&'&'&'&'&'&'&33276745676767676767236"##'"3"3276'&'&'&'&'&'4545&'# %"7676767676767676545&'&'&'&'&'1S8B (71<6?4Crb    2     e U>%0CWn #K_P:%3 -$N/-   Z)6O%   !5UHN((VBPDH8?) UHl6 /7I'    <%   (#%sG^pJ`"FDV %+ a?*)0 G{U+S"a<}T3#'&'527676'4'&'&"32767676767645!#%5#35!! /S</-7 @+*<14R6#'5}ap~kK?Ŗ,R40`;,*W;j6F,.EaaaRi}36#775"'&'&&'&74=332367676767676767676767676767673#7%5#35!#"#"#&'&'&'&'&'&'&'&'&'&'&'&'&#"##!R*D$,5n5,$D*  "")Qu=!& 35 "EE"  ދ (\#,UU++UU,#[}a; aa :_%LK%Z2:0<<@-n9;s(LL"DC" Daaa ;"ED"^^>=    >=^^"DE"; O}$3#%5#!#%5#35%3!35%O55ޒiޒ}aEaaIaaaaae0u#"7676764'&'&'&'&'&'&'&"6#&'&'&'&'&'&'&'&'&5&54767767676767T fY^Gc62 μ,YZl^eO!$CLtm!%!&9 F>@/! 04 ! !`$ &/"6+.D_~ û &(@WxhrYfB>S !3#'Oo"),$#K6v   _9r 1' u  O}3#%5#!#%5#35!O55i}aEaaEaaaP}!=3#%5#!236767676'&'&'&'&%2#!32##P5$ C?! &gA.h> . >h/}aEaa O [rmZ#QB]& 9 $<'&$##"76767676765454'&##'"'&'&'&'&'&'&7676%6763732767676'&55454'&#"#1"''&'&'&'&'&'&'&" 17n`gPm''vkIQ   %#3NNE;?/z=o# /",%eRQ/          [l9 *-C94MUi."  =53(m!/{!&H6v DB_ , ?K       , U},36767676767633!%5!323/!  a=C4q`q4C=a  }y&,z7<Eaa<7z,&yA};6#&'6767654'&#76767676767676767767676767763235'2'''35''A%%!m3T   .;7?+# )-GC-5 ;)/*1RKK;? "aa(L)' &Kp9 $76 -4GjBF    3+     $G }aBb0    00$T   aa    +VL&'    !JQaa +4hM!"  '.$FG$ aa   "D92b %aOr;}%3#!723'#35%3!35%OqT6n@ha*ޒiޒ}aNj )D:QaaNaO}O373676767#%5#35%36#"'&'&'&74535%O/ DQDX25ޒDI BKAO#")ޒ}a b,fH '  aaaarl   = _aP V}"3#!5#35%3!35%3!35%P ޒޒޒ}aNjjaaNaaNaPr }13#!!2#3'#35%3!35%3!35%P?ƕ*xJaa*ޒޒޒ}aNj C@QaaNaaNaU}9X36767676767633#!2#676767674'&'&'&'&7#35!27676767636#"#!  a;D1,$>0/,9r9@d0P&oW:( %+.DdB) "   uB }y&/v6>EaR"_seU4*':   aP%6;I(O},=\3#!2#676767674'&'&'&'&7#35%!3#7%5#35%'27676767636#"#!O,$>0/,9r9@c1P&ލtݑ5u( %+.DdB) "   uB }aEaR"_seU4*':   aaEaaaP%6;I(O},K3#!2#676767674'&'&'&'&7#35%27676767636#"#!O,$>0/,9r9@c1P&ލ( %+.DdB) "   uB }aEaR"_seU4*':   aP%6;I(#'&'&'&'&'&'&'454'&'&'&#767$67676'%&%&7''&'&'&'&'&'&'&373276767676767676'&'&'&'&767672763276767 %)>QM,(+%6'+  W!%'.4,7CBEAC=5        (&29;I?D1<%!  0010,J2cdEA  !''8Q-27g1#u:\MT<  +.7 C ),305_flNj    CH  '61."^  !#2>UM].!"  #  , 1 P G!35%'3#7%5#!3727676764'&'&'&'&'&'&#&6#&'&'&'&'&'&'&'&'&5&54767767676767ޑ6I  :pn~ynYKR?.2F2=:Dk '(jg F>@/! 04 ! !`$ &/"66aaEaa$  2.0,a_+$$(8TebcVZB/$#)ߟ [ !3#'Oo"),$#K6v   _9r 1' u  b}f"#775"''"#&'&7167767676767676767676;#%5#35!"'&'&'&'&'&'&74767676763; 5W,C ,KLvC,!  ' $GK&  #1`Z+ܩB$ /3b>N 2@NAdGGQ G7  %K @Q>1 & +       9 j1|(+I@' -,;)  ? &)6',  @]c6767676767676763676767676767676545&'&##""7676767676'&'&'&"#%63#"'"#&'&'&'&'&'&54545476767# d. %"?'4  ,( =%u bA /x-''.)-(4-/'}!"h%#"!  A*0+5'   9!4(>[An*    *_ 9fS #[4"Z =$%%$ >) '!,AG(JKRm232#2#"#! #27676767676745654'&'&'&'&'6767676767676'5&'&'&# !!554547673672''3722#'"#&'&7455J;;$Ϫ]   / T( Vq20w +8]*)(&A *@W+$t  31/! J w[mJ-   kB!2 }66)(?>(% C1* >GDH232#2#"#775"'&#"'&'&765554'&76723623/!D;;g'8  !/ N0Ma J w[mJJ nx,#,S` \232#6#3676745676763!23'#"'&&'&765554'&767"763235!347"332#26##!"'&'&'&77676767676765- ;b==)=q a!?) m9 a %09&;V! #   '1*  IJ   U*߂J s J4;9/ &2Cs#xmJ^  w   #$&MU@KY!33232767654'&'&'&'&'&'&767676767676'&'"#"'&'&5%!4767676GP8 16X,3/5! ~KyAA!! <03 +   JYM* &@h@9   gMT) hߑs $(3%  &{Dp,C) c>gG?u*0(622#775"#&'&#&'&7676767676767676632&2#"#75"#"'&3&'&74=45&7677676767676632&""#75"3&'&''&'&'&'&'&'&'&'&''&5477676767676767676767635'2545&76776335'32&'&'&'&'&'&'&'&'&7635'\5) 9 +5"  7263  &.S     !B/   '  ;ؽe;     /B!     S.&  3627  "5+ 9 )5-  7989 ":"*e*"7! v8 *J *&  ?8=9 JJ  %K5    #EJJF{"   5K%  JJ 9=8?  &* JJ   ')') (@JJ?& U&   J167676767676767676'&'&'&'&''&/&##"32767676767676#"'"232723'&'&'&'&'&'&'&'&'&#"#'"276767676767676767654'&'&'&'&'  C&   ,'@=O5[*"A4  +    @m(-$"'3~:  2$ X0T-!3;% 4Y 8G(4H'=0 _0  '  # @<4    $ . 4  *:/%D5n,'c  # ($$,  4  y@D232#2#"#775"'"'"'&'&?67676776767676732#"#775"#"'&3&'&765554'&767"763235''222#54'&767"763235''D;;g'    ;s- ;g;;g'    ;s- ;gJ w[mJJ #&Q> & IpJJmw JJ #&Q? & pJD8'&'&'6767676'&7676767676'&'&232#2#"#775"'"'"'&'&?67676776767676732#"#775"#"'&3&'&765554'&767"763235''222#54'&767"763235''01A%2 1" J88, (#*HIc 4(6m$  ;;g'    ;s- ;g;;g'    ;s- ;gh  32K3,) 5*0M/$c  J w[mJJ #&Q> & IpJJmw JJ #&Q? & pJD232#2#"#775#"''&'&54=45&76767767673'""#75#&'&'&'&'&'&'&''&'&'&'567676767676767235'2545&76776335''D;;e*"B   +?    S+&  #EE#(;V) (=T-  :::: 6"*ܹeJ w[mJJ +)  /    1F$   JJ ## 'NN'. , >  !JJ   ))*) %@J&232##676'&'"#"23276767676767676547454'&76716;762#"#775"#"'&3&'&765554'&767"763235!&6.% T  O0h %#K#  $;g;;OJ % [-5dM !-[b4(B)w@W$Y<-)--  ) _JJmw JU232#"#775"#&'&'&'&76553236767676767676767676732#"#775"#"'&3&'&765554'&767"763235!#"#"#&'&'&'&'&'&'&'&'&'&'&#"##!U; 1 O 1   !`.   >&7,   ;a;;>! <*    *< !BJ wrj  JJ   ++!Hl-   6&Txc/.ߎ$ JJmw J $ /C]/$$$$/]C/ $ D|232#2#"#775#"''&'&7455!##775"#"'&3&'&765554'&767"763235''32!5545&76776335''D;;g*""*g;;g*"["*gJ w[mJJFFJJmw JJ 55 J=\$\7276767676'&'&'&'&'&63#"'"#&'&'&'&'&'&545454767671 *E=@3BD_+""8^=aXj'  !  A*0+5'   9!4(> *~z  A%&-gyN.+ J =$%%$ >) '!,AG(Dx232#2#"#775"#"'&3&'&765554'&7673633276#2#"#775"#"'&3&'&765554'&767"763235!D;;g;  {Z9;g;;mJ w[mJJnw  )~bJJmw JJr8u23223#775#37676767676'&'&'&5"#62'&'&'&'&'&'&74=45&7676767672767J) gݎ"5:;6"'&I2&5 `ˁu $&/!  BS% )"'F;Z36767676767636723"#"#775"'&#"#&'&765554'&76736323/!T a  %H $< <$ H%  a O`S*) /* wXn JJ nw */ )*S`-f3223'"'6767676'&'&767676767676767676767676767635'2&'&'&'&'&'&'&5&''&76776315''&'&'6!   "FE""   g  QT &VNG4$  $KJ$! 1  ,,   D. 8Z! J/('JJ%J    ;( \Gz 4/N#O32NN"DD"CJJ   /\\/-F ^"# JBMrM}2&'&76767#775#76767676'&'&'&'&"#636'&'&'&'&'&'&7676767!6'&'&&'&74=45&76776767'  Ah"# wq6B=F"Q;e؎;Q"F=B6qw #"hA=yy=7 T;   "&aE N  G63 4.-"  %#,}a H8 }$ aah $} 8: D   %L  E'%*FAG  2.F /+>) I(   23"23#775"'&'&'&7676767676767676736#75"#2'"#&'&'&'&'&'&'&'&'&'&'&''&5477676767676767676767635'2#&'&'&'&'&'&''&767767635''8] *&)&    !C3(A(J   &&    7  اX]  994 )&<)J     *   اXJ  1,1-! %K: JJ    **   B JJ  "CC" ; 0 JJ    "  !2JD232#2#"#!2'3'#"'&&'&765554'&767"763235'232####"'&3&'&54=545&767"763235'D;;dDa %09&;g;  {Z9;gJm[w J=53K$s#xmJJnYw  )bJD327676767##775"#"'&3&'&765554'&767"763235''32'&'&'&'&=45&767"763235''D*")3l IQdd$"*g;;g*" VX"" ;gJF6A DJJmw JJ +0 $_GJDC232#2#"#!5"#"'&3&'&765554'&767"763235''232#2'&#"#"'"#&'&765554'&767"763235''232#"##"#"'&3&'&54=545&767"763235''D;;;;g;7Uu   ;g;   uU7;gJ w[mJJmw JJb~)  wnJJnYw  )bJD~232#2#"#!!233'#"'&&'&765554'&767"763235'232#2'&#"#"'"#&'&765554'&767"763235'232#"##"#"'&3&'&54=545&767"763235'D;;q.]6[a %09&;g;7Uu   ;g;   uU7;gJm[w J2@s#xmJJb~)  wnJJnYw  )bJ;6To367676767676367232#"#!236767676'&'&'&'&'&'&'"##55454767232375!33223##'&7455T a  %F ; T `A  f 'lM/E(422m$^`S*) /* m\x J4J^" 95JE )5PN66GD`G232#2#"#!236767676'&'&'&'&'&'&'"##5545&76776335''!223"##775"'"'"'&'&765554'&7676363635''33223##'&7455D;; T `A  f"*g&  &g&  &g`/E(422m$^J w[mJ4J^" 95 JJm\x JJnw JE )5PN66GDPGb232#2#"#!236767676'&'&'&'&'&'&'"##5545&76776335''33223##'&7455D;; T `A  f"*gw/E(422m$^J w[mJ4J^" 95 JE )5PN66G?'&'&'&'&'&'&'&'&##"32727$765&'&'&'&'&/&'&#"#"73323676767676766'&'&'&"776767$M71$ 64AI\vCu$3/6Y_QI 3    DLK"')#".185    ,2P%) gC!   9*'p(     =u / $ i1M      $ ADg#5545&76776335'232#2#"#775#"''&'&745537676767656'&'&#&6"#"'&'&'&'&5545476767"*g;;g*""F(308%*&*&%׃<#"w &&  N(4rg5!5)?5 JJ w[mJJFhT^A%  v6OKTY 1,? E 3>Q 5'@BE*'v"#775"3"'&#&'4767#?3##775"#"'&3&'&765554'&767"763235!"&%"'&'&'&'&7676767676763232323*Q1    &: U   Eu4="*e;;&V oB(1 DJ]G.,A!'! ->! /-`9   JJT@AJJmw J(&/=   ;%0: !I#$#  ;@~ A3276767654'&'&'&'&!3276767654'&'&'&'&!33232767654'&'&'&'&'&'&767676767676'&'"#"'&'&5%!4767676)@B   FE     FB  UP8 16X,3/5! ~KyAA!! <03 +   JYM* &@h@9} 0QS/  .VW. $  .XT.B   gMT) hߑs $(3%  &{Dp,C) c>gG?u*0EF=#1767767676767676767676'&'&'&"A+??      2k 17#<M1F K&$$!  E ?  R(  :n#+&/+: ;!$29c ()_#J !   #G/1  (#& %Q<  E// #%>su('7+62< &F/:.#+#.  0 "$,'vU\1"&  BwW@   pNT*;!; /V*+"$C `K %!,& %;]- `C#&'&'&'&'&'&'&'&'45&'&#"#"3"767676767456'&'&'&'&'&'&'&'&76'&'&'&'76765&'&#&'&'&7277676764533767676767676776'4'&'&'&'"'&###&'"'&'&'&'&5&'&'&'&'45&'6767676767676'&'&'&'&'&'&'&'&'&'&#""##!456'&'&'&'&'4'&76763676767676727761>R^U tF !  :+"  !- `% 8 *   5'(     )L +($!41.$~  %+679   # ) T$   9< ME:n Er!9 *9+?   -(  -)1 [$.atG80 M$.   #/ "0@3 '" 3p')K!C+l3 !"3       ,  *)DW, ;2,.!'      2m(OP(    W  . 0`f3  5  E( Q    !!L/D8 -76767676767674'&'&'&'&'&/&'&7676767676767677676765454'&'&'&'&'&'&'&'&'&#"2&'&'&'&''&'&'&'&'&'&'&'&""#&3"332767674'&'&'&'&76547676767E $JI$"CD" 2  7    J! *       ? *TT* m4- u     *H #   riX7)SC ; <<87''$*  2*C1! -   ?> )  $( 4M*) &  #*W+ ;;&5 "ED#Y*"(%+  $ %;D'Yd  G7I@K}     ( 8L=(C ].W34'&'&'&'&'&'&'&'!!2367656545&'#!!6767676767676765#P .KK^D--D^KK. {$$./ L= B @ /.$${  aOO3%  %3OOa  C>>7. )' .7>>C AqX^27"767676767677767676'455'#35&'&'&'&'&'&'&'&'&'&'L  7TRc @;<4004<;@ ]NP8    ZFD* { !"+0{ 1 , 0+"! { '?AR W!!"3"23!!367676767676767675&'&'&'&'&'&'&'&'#g$$./ @ B =L /.$${ .KK^D--D^KK. { C>>7. ') .7>>C  aOO3%  %3OOa  ArX_&&'&'&'&'&'&3&#3676767676767676767675"265476'&'&04<;@ cRT7    7TRc @;<40S0+"! { *DFZ   ZFD* { !"+0 1 , }34'&'&'&'&'&'&'&'!367676767676767675&'&'&'&'&'&'&'&'#!6767676767676765#P .KK^D--D^KK. {$$./  /.$${ .KK^D--D^KK. {$$./ ` /.$${  aOO3%  %3OOa  C>>7.  .7>>C  aOO3%  %3OOa  C>>7.  .7>>C AX27"767676767677&&'&'&'&'&'&3&#3676767676767676767675"26'#35&'&'&'&'&'&'&'&'&'&'L  7TRc @;<4004<;@ cRT7    7TRc @;<4004<;@ ]NP8    ZFD* { !"+0H0+"! { *DFZ   ZFD* { !"+00+"! { '?AR e'7677676767674'&'7676767676''&'&'&&'&'&'&'&'276767676767&'&''&#"6'&'&'! 1   UI   %I)3ee3MXJ\3%E;R{z2dc2%>##  #"%fnJG1A  >**,,+* I> EKGM' ">!,WW+ػCK@N//72HOj+VV, 3R     # qd3776767$7676767677776767676''&'&'&'&'&'&76767'&'&'&'&'&'&&#"Zabd  %3ef3VOVP?&8/_z=4ih4)C   IU   1 ! A1EHoh%"$   /   +XW,JDIE4-5)Rj5ɂ-ZZ.!8 4KEJB >I *+,,**>  #    q"327767676767676&'&'&7676767676776'&'&'&''&&&'&'&'&'&'&'&'&'&'&##  $"%hoHE1A ! 1   VJ   %I)3ee3MXJ\3%E ;[z2cd2%>R     #  >**,,+* J? EKGM' ">!,WW+ػCK@N//83Pj+VV, 36765&'&'&'&''&'&667676'32776767&''&'&'&'�7676776'&'&'&'&'&O  JV   1 ! A1EHoh%"$ Zabd*\ H9FG7mn7<(>CT*ß4hi4%= 4KEJB ?J *+,,**>  #      /"Q >x1/^_/0*8;uH$-ZZ. 2;!!2767456'&'&##!6767676767676767#P *89D  Bu"=&5 /.&% {$9PEG9 ,$  .5=;B  >;3&'&'&'&'&'&'&'&'!327676'45&'&#!!  D98* { %&./ ]5&="=, 9GEP9$  B;=5.  $;!#"'&37!!5456'&''&''&'&'&'&'&'&'#g %&./ 5&="uB  D98* {  B;=5.  $, 9GEP9$>;36767676767677677676'455!!'"7633!| /.&% { *89D  "=&5] .5=;B  $9PEG9 ,$ ;F!27676736776'+!56776767676767676767&##'&63727676767676767676676333!5!67656776767676767676;56376767676776'&##!')0#1"   : \))YcUg+*3 ' 6c`d`"%@S) /LS   -),(2 GI9&PFNG   > Mk 5LFLG~wy#$#$F5%!!=! gM1  0 %'   %$$#   =v'*)55/3  ! ,{ P5 $  $ $!{  ap=67676677676'&55545&7677676767676767376'&55&5476'&''&'&'&'&'&'&'&'&'&'&'1&'  8GHU+*.- :=6::/ 1  1 /::6=: $"SJI=   ^PRC!Y"'& (. LN8       8L .( &'"Y5EDP(,+-;p!7'&#63767676767676767675&'&'&76767676767&##'&#'##!5!#'"#2323233!632767676767677676776767675!'&53";!   " "?HA?bacb5B"CT /$59B;E 4  5-3,   7,l 6#!# A ?n#5x>dQ: R  3cdqav ]0  <* :P(   :*!{    M >2Z# 11r11 #Z2>>GE//EG>>2Z# 1111 #Z2>>GE/4C!=8G!C44C!=G!C4']767676767676767676767476'&#1+!+"'&''&'&'&'&'&'&#&'&'&'&'&'&'&'&'!6 " 3gM "" !@@ 3*1*)  ((  uwj  */*++      ++*O#&Lr"BC"4&M8HHo^ma.Z8A !-YY-      AA    B   AA     !2,97J71*&} $ !1   (D;N{*$5/W>PB5.2' !N  Z  /^>~ q9O "CD"__;: #BN c T8;  !AA!__==  p6~;V3276767767677677676765&'&+)#'"''''! P'f{>( &  B")Mw)S IZ  %9@"" &JZ-} *Dl#F54 8 s;HF    @ dq;;5CΜON_j!37676'&'&'&#!477676767676323!37676745&'&'##"#&3327676'4'&'#!#"'&'&'&'&''&5C(    *   CQv f/寲-  9T1$A~>mn< "xSQ ,216543sq,$ QSx"O^j!#'&773!#"#!#&&332376767676'&'&'&'&'&'&##"'&3"3!32؁   &    CQv f/寲-  9T1$A*~>mn< ="xSQ ,216543sq,$ QSx"O}3#!5#35%3!35%Oޒlޒ}aEaaaaEad?32;!327676'&#!##'"3( >$)-'!M =6+1 )OV!##";!767676'455!3327676'&'&'&+!!27674'&#!##&7633!VN    L..L    NbG-8'(8;'7,L    N,Y;  =7&'&'&'&'&'&'&&'&3"76776767676767677676'&'&'&'&'&''76'&'&#&'&'&'&'&'&'67676767676727676'&667676767676'&%/ 0   a  4343  a   0 /  J8 / 0   a  3443  a   0 /  J8 B & $  o'        'o  $ & $H4?)8 V+ & $  o'        'o  $ & $H4?)8 V+6,T76767676'&'&'&'&'&'&'&'"6"3'&'&'&7676767676773 ):36)%w//E>@1 +=:F  PQ&71=&'QY *(.C '#-,2V^{o -zKH.)+$6$#{ c!;=U( MUKD   6,76767676'&'&'&'&'&'&'&'"3 ):36)%w//E>@1 +=:F  '#-,2V^{o -zKH.)+$6$#|72367767654="#"#&'&'&'&'&'&'&''&74767676767676365&'$&'&'&'&'&'&#"767676767677676'"'&&76767 J_ad*&  !!   BQX\   * )329Z^ ZL 7@;;76,)'# !%    ESZc-& % **%E*+c" $  K/3 ^$  >",##'   "%#* .    R27  E ` *p&M7676765455456'&'&!727676'455476'&'&`"$" $B&  E" 7B&  FN 0k376'&'&'&'&'&'&'&'&'&'&'&7276767676767676767676767676767  $J( &%G ; 95:6"/*4  +# 58rs7 ; &&,9 ).  0 #DF7$H$I  9)(+(,pcnd!D[-Le>=/b2ll,(+()8   #GF#)Sj6@L6U  k%&'&'&'&'&'&'&'&'&''&'&'&'&'&#&76767676767676767676'&"  $J( &%G ; 95:6"/*4  +#''8rs7 ;  &%,9 ).  0 #DF7$H$I  8)(+(,pcnd!D[-Le>>%II%ll,(+()8   #FG#)Sj6@L6U  `"#3323676'&55547676767676727676'&5554'&'&'&'&'&#&##&  %!/-D. ,1 8KQQ'$.C) /1 6bsA--10  ! ,]Vmi7 .fJN (CE1'\/.iIL )$Uc'T\37676'&'&'&'&'"#&'&'&'&'&'&'&7676767676'&'&'&'&'&" ,"  )Zy -    _ !J*'-    ?N3714&M`!!B   %-.g-A8B>-/N Tr7676767676763276767676767676'&'&'&'&'&'&'&'&'&&32;!!27656'&#!!#'"K&X><  KHVZ`I]7UGD)    JGX>E:?7fxC0,2/C+ 4( E#(+0-T  $LI^/$* *$P85 &@ '77O!&!'**O40 #HV!q6+3 ~G8%67676767676767676'&'&'&'&'&'&'&"767676767676'&'&''&'&'&'&'&'&'&#": " $0: :*,..0ptfj+  mmfb 6, *+,-uykm )1 to}{2 B ; >9_  : % $ N!$2+H%,40E 7 % " O#& 2-J" 4 M06@8W#7676767676767676727676767676'&'&'&"#'&'&'&'&'&'""#7676767676767676727676767676'&'&'&%&'&'&'&'&SW>A ?VcDg # lMP ?n6gD-+.- RW>A @ # mLP 69)2-30 2 9}j$N0   0DPk6?}j$N0   0DPk6?}j$N0  H3( >$)-'!M  0DPk6?}j$N0  3( >$)-'!M  0DPk6?/89?zZ88 ")+nq)+*+$$#"'%$"/   !9PdV733!232''!#'"32;23276767676767676'45&'&'&'&'&#"#!+&4 {rGƅ  $F`]h4Pex 4$ ?u;e^_M !98`O`aiB F  6#,1/0-/,)'K0. 5'+*B"/346`h|zZI00 kdZx3233!32327674'&##!"#'&'&'&'&767676767676767676323!327656'&+"'&32;!327676'&#!+&v[[TTE4**8Vqp|1d 'F"% Spt#  :DEI?~+&7)91"3' 9!)+%BJ  ,+>/89?zZ88 ")+nq)+*+$$#"'%$"/   !9T6*.kdVt733!232''!#'"32;!23276767676767676'45&'&'&'&'&#"#!+&32;!327656'&#!+&4 {rGƅ  $F`]h4Pex 4$ ? t9e]^M !98`O`aiB F 3( ;,*%@J  6#,1/0-/,)'K0. 5'**A"/346`h|zZI00 T6+.~S7676767$765455456'&'"#""'&'&'&'&7455476'&'&#"'&36337676'&55322767676'&'&##5476'&'&:>8KQQ'$.C) /1 )*"*F++IAH>)*"*.536Pxtl\bG %'=99qdkTfD@ .5)#)(?GBJ.. F)#)(?GBJ..㨡 .50]#"76767$6'&'&'&'&'&'&'&&63"2'$'&'&'&7767676776767676767676'&'&'&'&r rahK16LGJJi^dO $'@Nql&*&+9 5A5tagF. MoeyIJ7(((C\We ! $%  *Y36Pxtl\bG %'=99qdkTfD@ a 68W8EBJkoߴQ1,4DBK&F.,`  4  6Ep@ 1!3767676'&'&##!476'&#"76'4=(   :$ : +X,73< 9H 0!#'"773!7676'4555476'&#"ր   ( ; #; 3; 9 28,X+u0767676'&55!3276'&'&##!#'&763!V,7'; 8)&:-Gb) & =  <0%!"'&773!337676'&##!5476'&'&'&VEbG-:&)b8 ;'7{<  = & )2(<176?776'&'&/&'&/?E JL&+Ѿ(!J8I'+п)!MM"CJM2. JL&+Ѿ+J8I'+п+MM2#CJM1i7436776767676767676632&'2'&'&'&'&'&'&'676767676767656'&2'&'45&'&5&'&'4'&#"''&'&'&'&'&'&'&3&!  # 6   F#      #F   6 *  1 !CC!  (P?   ""   ?P(  !CC! 1 G(F$  7  C#      #C  7  +T0 7 ##   %%J_0BC0_J%%   ## a^676776767767676767676765&'"#&7723674'&'&''&'&'&'&''&''&'&'&'&'!676776767767676767676765&'"#&7723674'&'&''&'&'&'&'&'&''&'&'&'&'@#A& r_9'NS*   6E+2)5ٻ_8j4j[=5:=9= l2J%E6  < @Z-lz&   #A& r_9'NS*   6E+2)5ٻ_8j4j[=5:=9= l2J%E6  <"CV+NRLSi'&   # eA6Z+. 9'Ph4 ;80!*# ! "Jw<('9 "$28l Dj  #dA6Z+. 9'Ph4 ;80!*# ! "Jw<('9 "%0).*/;`  ^23767676%67676766'&''&'&'&%&'&'&'&"#!23767676%67676766'&''&'&'&%&'&'&'&"###A& r_8'NS*   6E+2)5&_8j4j[=5:=9=l2J%E6  < @Z-lz&   #A& r_8'NS*   6E+2)5&_8j4iZ=5:=9=l2J%E6  <"CV+NRLSi'&   #dA6[+. 9'Ph4 ;80!*# ! "Jw<('9 "$28l Dj  #dA6[+. 9'Ph4 ;80!*# ! "Jw<('9 "%0).*/;`  0!276'&'&#! %"7676'&55"@.=?59"? "#  l G $ .7127676'455456'&'&'&#!'"763! 7 $;4?=.@"t$6I a Ol  "" ?05476'&'&3$!!27676'&#!"9 e5?=.@z$ G l  #" ? .!"'&37!2767676'455456'&'&@.=?4e;$ 7 z? ""  mO ` I6$tf2727676767676'&'&'&'&''&'&'&'&'4'&54767676767676767676767676'&&$H 6H$   55'&'&$)%$$%-["EE# I U AW"A " +@@^[_[\<VYVYo?%& %%%%SS(+(,#v_7674767676767676767654'&'&'&'&'&'&'&'&'&B   "#D1  !DC" ("0"6H$  76(8(0 @8 =S*Rv;G%  5'QQ+.+/ &U:tQ(AW"A " ((BB1aCbb94!5456'&'&773!3276'4555456'&'&      Z  !wNf l\  y3R77)3376'&'&'&'&''&''&'&'&5&!676767676767676767676767 "++Y'8'5)1X 2  #@Il5!#' '5I ZKXN77  ;!CB!@?X, <# 4 "6dsV)R562S($*)**vz+WW+ ?ZU8D736767676767676767676'&''&''$'&'&'&'&557w A+<XX650  a-Bķ%H  $FP_R  u- ! & "4de4 8&m).S^7]2W3@767676767667676776'&#)#'"#''!B  \\I%(' *)gɖL(6+2/^ /5ٹ٭5 @"4/ސq;@5!BA!>v @U*B%{(S2"S(?ZU:C767676'4555476'&'&''577#)%(%bv[52 -9``.1 $6__R _8TC 4   !7oo7   vӀ ! 7^^7Z,Y##7676767'%&#&'&'&&6"'$'&%676767672727o :3j#..GGoPG *<4* Ǣ,=;FXgbjqlXpiv  <@cgTz?7  04UI*3{0C87)4 qD-*w3Q#&7767767676%67676767676'&'&'&'&'&'&'&''&  -$+&{933-% 3@>GM{~*'%$&%.44::; 2?Ab.349/( :30' 48_'$+2/:54.eB@v:767676767676'&'&'$'&'&'4#&, 9FCM,|yx1(-" +! 7DBJ)#&/!0@97. BGq'',, , & 7.,!p) #6%337323676''&'&'&'&53327676767676765676'&'&'&'&'&'&'&'&'&5&'&766767676745f   B? f*q9-&"* A)A %+!#'+2z  9%|6t*he# &) >  )%1TpjR3!+-//A@ B6<17a !#98,  > O&'&'&'&767676767676767676767676'&'&'&'&'&'&&'&'&'&'&'&'&'&'&'&'&76763232727676767676767676rm66fN} 7"+ !"(<"[=L,1   kf]&"#  :@,9.P0< +2G;@& !FLID +`,0#MhكqrpTg*"'%+7C2,-$/ QGYYa[ *%)%1+/&[* - 3'1.PK\\:=3 !#8   ;   NI "DF?>"qY}U7676767676767676766'&''&'&'&'&'&'&'&'&'&'&#&''&'&'&'&'56767676767676767567^nl}" $6$9RNKIEw&'&'&"76767676765337323676''&'&'&'&5376'&'&'&'&#&'67676'&'&'&2>HK?+##<}! pf   B? fp !ς}<##+?KH>2 % Q7w n_b6.Q % W  !! *_suyP he# &) >2./+$2*O?67677676'4555476'5545&767767676767 K_"  K_ -.[r9 -.[r9 O PE([G  PE({m  %~! '2~! '24667676767?=?6777676'4=4'&76?676'4=54'&76?676'4=55'55?E9  .  . F9  .  . `8H8H 64 WX1FB & 5 M 5  $# W2G +s   5  5 Fz#} :} : <37674'&'"'&'&'&'&'&'&'&76767232767676'&#&K%P47DAg  '%   !@ #7%   !AESgRM,   ><7  )43#76767676'&'&'&7& : *:&)U69GBf! 858:  < AEWfSN 1367676767676767676'&'&#!K#O8%   ".5kk5 "%:! ."0 1cb1."  d*I232''56767676'&#"37676767676'&5"#%'  " 5q  Z6$% :Q pV <?~~?a 1e=&N%&:+# !' Q"[ @n#3#775#!#775#35#545&76767676767636363276'&'&'&'&'&#"''&'&'&'&'&"!5454767632ؘe؎e#  $:( 8 $()$(#  2P q9(-    E3&(-a4aa4aaa;   3"'$K%       9',6"F  !,    M%|@`#3#775#!#775#!336#775#!54547676'367654'&'&'&'&7#"''&'&'&'&'&"#!545476767632ؘe؎e؎/N e؎=12 ;4L# 02?2G?7>7 3@ $(k4$+&   E7  a4aa4aa !|aa@ ]+p WR J 5+, 9!, 5.,     6 %.-\$6#   rV(p@`Z~#3#775#!#775#!#775#"6'"''&'&'&'"''&'&'&'&'&""#!5454767632%!545&7676ؘe؎e؎e؎= 5:;@,)*( # '!) 31$(  E3&(-z  E /.1! a4aa4aa4aa-   @!%,-\ ".    M%|  #  $ D!~(dd,,,40Xt 8 x\xt 8"$%T&l'(8)X*-/t02d3<4467 7L889:hVX`X[bXa_=b78N^aa^b"lMNbN"l OTOOO6 O b6O6O6O6<R6O6OJPgUAF6O6O P PU OO 0P6by@@JD 7@(1DDD&"UD=DJLZ;-'MDDDD;DD?D'7@E@q69@` 3A 3A 3A 3 3q 3q 3 3 3 3 3 3a 3aa\p""3O(((*""""~({((~(((((((((("~((}""(((((((1 3a 3  vb.?.? 3 3w 3v(((}(>^@@@y  }   (      5 Converted from fonts of Computer Modern family (C) 1979-1985 Donald E. Knuth and others. Metatype software (C) 2001 Serge Vakulenko .TeXBoldMetatype:TeXTeX BoldVersion 0.1TeXBoldConverted from fonts of Computer Modern family (C) 1979-1985 Donald E. Knuth and others. Metatype software (C) 2001 Serge Vakulenko <vak@cronyx.ru>.TeXBoldMetatype:TeXTeX BoldVersion 0.1TeXBold!d~  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`a      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~.nullmultiply gravecomb acutecombuni0302 tildecombuni0305uni0306uni0307uni0308uni030Auni030Buni030Cuni030Duni0311uni0327uni0332uni0337uni0338iotadieresistonosAlphaBetaGammauni0394EpsilonZetaEtaThetaIotaKappaLambdaMuNuXiOmicronPiRhoSigmaTauUpsilonPhiChiPsiuni03A9 IotadieresisUpsilondieresis alphatonos epsilontonosetatonos iotatonosupsilondieresistonosalphabetagammadeltaepsilonzetaetathetaiotakappalambdauni03BCnuxiomicronrhosigma1sigmatauupsilonphichipsiomega iotadieresisupsilondieresis omicrontonos upsilontonos omegatonos afii10023 afii10017 afii10018 afii10019 afii10020 afii10021 afii10022 afii10024 afii10025 afii10026 afii10027 afii10028 afii10029 afii10030 afii10031 afii10032 afii10033 afii10034 afii10035 afii10036 afii10037 afii10038 afii10039 afii10040 afii10041 afii10042 afii10043 afii10044 afii10045 afii10046 afii10047 afii10048 afii10049 afii10065 afii10066 afii10067 afii10068 afii10069 afii10070 afii10072 afii10073 afii10074 afii10075 afii10076 afii10077 afii10078 afii10079 afii10080 afii10081 afii10082 afii10083 afii10084 afii10085 afii10086 afii10087 afii10088 afii10089 afii10090 afii10091 afii10092 afii10093 afii10094 afii10095 afii10096 afii10097 afii10071minuteuni20D7uni2110 afii61289 afii61352 weierstrassRfrakturaleph arrowleftarrowup arrowright arrowdown arrowboth arrowupdnuni2196uni2197uni2198uni2199uni21BCuni21BDuni21C0uni21C1 arrowdblleft arrowdblup arrowdblright arrowdbldownuni21D5 universal existentialemptysetgradientelementsuchthatuni2210minusuni2213 asteriskmathuni2218uni2219 proportionaluni2225 logicaland logicalor intersectionunionsimilaruni2240uni2242uni2243 congruentuni224Duni227Auni227Buni227Cuni227D propersubsetpropersuperset reflexsubsetreflexsupersetuni228Euni2291uni2292uni2293uni2294 circleplusuni2296circlemultiplyuni2298uni2299uni22A2uni22A3uni22A4 perpendicularuni22C4uni22C6uni22D8uni22D9uni2308uni2309uni230Auni230B angleleft anglerightuni2422uni25B3uni25B9uni25BDuni25C3circleuni25E0uni25E1spadeuni2661uni2662clubuni266Duni266Euni266F bracerighttp bracerightmid bracerightbtuniF8FFffffifflfonts/index.html000064400000000203152270514220007665 0ustar00 403 Forbidden

Directory access is forbidden.

database/DB_result.php000064400000034046152270514220010713 0ustar00conn_id = $driver_object->conn_id; $this->result_id = $driver_object->result_id; } // -------------------------------------------------------------------- /** * Number of rows in the result set * * @return int */ public function num_rows() { if (is_int($this->num_rows)) { return $this->num_rows; } elseif (count($this->result_array) > 0) { return $this->num_rows = count($this->result_array); } elseif (count($this->result_object) > 0) { return $this->num_rows = count($this->result_object); } return $this->num_rows = count($this->result_array()); } // -------------------------------------------------------------------- /** * Query result. Acts as a wrapper function for the following functions. * * @param string $type 'object', 'array' or a custom class name * @return array */ public function result($type = 'object') { if ($type === 'array') { return $this->result_array(); } elseif ($type === 'object') { return $this->result_object(); } return $this->custom_result_object($type); } // -------------------------------------------------------------------- /** * Custom query result. * * @param string $class_name * @return array */ public function custom_result_object($class_name) { if (isset($this->custom_result_object[$class_name])) { return $this->custom_result_object[$class_name]; } elseif ( ! $this->result_id OR $this->num_rows === 0) { return array(); } // Don't fetch the result set again if we already have it $_data = NULL; if (($c = count($this->result_array)) > 0) { $_data = 'result_array'; } elseif (($c = count($this->result_object)) > 0) { $_data = 'result_object'; } if ($_data !== NULL) { for ($i = 0; $i < $c; $i++) { $this->custom_result_object[$class_name][$i] = new $class_name(); foreach ($this->{$_data}[$i] as $key => $value) { $this->custom_result_object[$class_name][$i]->$key = $value; } } return $this->custom_result_object[$class_name]; } is_null($this->row_data) OR $this->data_seek(0); $this->custom_result_object[$class_name] = array(); while ($row = $this->_fetch_object($class_name)) { $this->custom_result_object[$class_name][] = $row; } return $this->custom_result_object[$class_name]; } // -------------------------------------------------------------------- /** * Query result. "object" version. * * @return array */ 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 not be a valid resource so we'll simply return an empty // array. if ( ! $this->result_id OR $this->num_rows === 0) { return array(); } if (($c = count($this->result_array)) > 0) { for ($i = 0; $i < $c; $i++) { $this->result_object[$i] = (object) $this->result_array[$i]; } return $this->result_object; } is_null($this->row_data) OR $this->data_seek(0); while ($row = $this->_fetch_object()) { $this->result_object[] = $row; } return $this->result_object; } // -------------------------------------------------------------------- /** * Query result. "array" version. * * @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 not be a valid resource so we'll simply return an empty // array. if ( ! $this->result_id OR $this->num_rows === 0) { return array(); } if (($c = count($this->result_object)) > 0) { for ($i = 0; $i < $c; $i++) { $this->result_array[$i] = (array) $this->result_object[$i]; } return $this->result_array; } is_null($this->row_data) OR $this->data_seek(0); while ($row = $this->_fetch_assoc()) { $this->result_array[] = $row; } return $this->result_array; } // -------------------------------------------------------------------- /** * Row * * A wrapper method. * * @param mixed $n * @param string $type 'object' or 'array' * @return mixed */ public function row($n = 0, $type = 'object') { if ( ! is_numeric($n)) { // We cache the row data for subsequent uses is_array($this->row_data) OR $this->row_data = $this->row_array(0); // array_key_exists() instead of isset() to allow for NULL values if (empty($this->row_data) OR ! array_key_exists($n, $this->row_data)) { return NULL; } return $this->row_data[$n]; } if ($type === 'object') return $this->row_object($n); elseif ($type === 'array') return $this->row_array($n); return $this->custom_row_object($n, $type); } // -------------------------------------------------------------------- /** * Assigns an item into a particular column slot * * @param mixed $key * @param mixed $value * @return void */ 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 !== '' && $value !== NULL) { $this->row_data[$key] = $value; } } // -------------------------------------------------------------------- /** * Returns a single result row - custom object version * * @param int $n * @param string $type * @return object */ public function custom_row_object($n, $type) { isset($this->custom_result_object[$type]) OR $this->custom_result_object[$type] = $this->custom_result_object($type); if (count($this->custom_result_object[$type]) === 0) { return NULL; } if ($n !== $this->current_row && isset($this->custom_result_object[$type][$n])) { $this->current_row = $n; } return $this->custom_result_object[$type][$this->current_row]; } // -------------------------------------------------------------------- /** * Returns a single result row - object version * * @param int $n * @return object */ public function row_object($n = 0) { $result = $this->result_object(); if (count($result) === 0) { return NULL; } if ($n !== $this->current_row && isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * Returns a single result row - array version * * @param int $n * @return array */ public function row_array($n = 0) { $result = $this->result_array(); if (count($result) === 0) { return NULL; } if ($n !== $this->current_row && isset($result[$n])) { $this->current_row = $n; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * Returns the "first" row * * @param string $type * @return mixed */ public function first_row($type = 'object') { $result = $this->result($type); return (count($result) === 0) ? NULL : $result[0]; } // -------------------------------------------------------------------- /** * Returns the "last" row * * @param string $type * @return mixed */ public function last_row($type = 'object') { $result = $this->result($type); return (count($result) === 0) ? NULL : $result[count($result) - 1]; } // -------------------------------------------------------------------- /** * Returns the "next" row * * @param string $type * @return mixed */ public function next_row($type = 'object') { $result = $this->result($type); if (count($result) === 0) { return NULL; } return isset($result[$this->current_row + 1]) ? $result[++$this->current_row] : NULL; } // -------------------------------------------------------------------- /** * Returns the "previous" row * * @param string $type * @return mixed */ public function previous_row($type = 'object') { $result = $this->result($type); if (count($result) === 0) { return NULL; } if (isset($result[$this->current_row - 1])) { --$this->current_row; } return $result[$this->current_row]; } // -------------------------------------------------------------------- /** * Returns an unbuffered row and move pointer to next row * * @param string $type 'array', 'object' or a custom class name * @return mixed */ public function unbuffered_row($type = 'object') { if ($type === 'array') { return $this->_fetch_assoc(); } elseif ($type === 'object') { return $this->_fetch_object(); } return $this->_fetch_object($type); } // -------------------------------------------------------------------- /** * The following methods 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. */ // -------------------------------------------------------------------- /** * Number of fields in the result set * * Overridden by driver result classes. * * @return int */ public function num_fields() { return 0; } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names. * * Overridden by driver result classes. * * @return array */ public function list_fields() { return array(); } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data. * * Overridden by driver result classes. * * @return array */ public function field_data() { return array(); } // -------------------------------------------------------------------- /** * Free the result * * Overridden by driver result classes. * * @return void */ public function free_result() { $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. * * Overridden by driver result classes. * * @param int $n * @return bool */ public function data_seek($n = 0) { return FALSE; } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array. * * Overridden by driver result classes. * * @return array */ protected function _fetch_assoc() { return array(); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object. * * Overridden by driver result classes. * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return new $class_name(); } } database/DB_cache.php000064400000013522152270514220010434 0ustar00CI and load the file helper since we use it a lot $this->CI =& get_instance(); $this->db =& $db; $this->CI->load->helper('file'); $this->check_path(); } // -------------------------------------------------------------------- /** * Set Cache Directory Path * * @param string $path Path to the cache directory * @return bool */ public 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 = realpath($path) ? rtrim(realpath($path), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR : rtrim($path, '/').'/'; if ( ! is_dir($path)) { log_message('debug', 'DB cache path error: '.$path); // If the path is wrong we'll turn off caching return $this->db->cache_off(); } if ( ! is_really_writable($path)) { log_message('debug', 'DB cache dir not writable: '.$path); // If the path is not really writable 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. * * @param string $sql * @return string */ public function read($sql) { $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 ( ! is_file($filepath) OR FALSE === ($cachedata = file_get_contents($filepath))) { return FALSE; } return unserialize($cachedata); } // -------------------------------------------------------------------- /** * Write a query to a cache file * * @param string $sql * @param object $object * @return bool */ public function write($sql, $object) { $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) && ! @mkdir($dir_path, 0750)) { return FALSE; } if (write_file($dir_path.$filename, serialize($object)) === FALSE) { return FALSE; } chmod($dir_path.$filename, 0640); return TRUE; } // -------------------------------------------------------------------- /** * Delete cache files within a particular directory * * @param string $segment_one * @param string $segment_two * @return void */ public 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 * * @return void */ public function delete_all() { delete_files($this->db->cachedir, TRUE, TRUE); } } database/DB_utility.php000064400000025261152270514220011077 0ustar00db =& $db; log_message('info', 'Database Utility Class Initialized'); } // -------------------------------------------------------------------- /** * List databases * * @return array */ public function list_databases() { // Is there a cached result? if (isset($this->db->data_cache['db_names'])) { return $this->db->data_cache['db_names']; } elseif ($this->_list_databases === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $this->db->data_cache['db_names'] = array(); $query = $this->db->query($this->_list_databases); if ($query === FALSE) { return $this->db->data_cache['db_names']; } for ($i = 0, $query = $query->result_array(), $c = count($query); $i < $c; $i++) { $this->db->data_cache['db_names'][] = current($query[$i]); } return $this->db->data_cache['db_names']; } // -------------------------------------------------------------------- /** * Determine if a particular database exists * * @param string $database_name * @return bool */ public function database_exists($database_name) { return in_array($database_name, $this->list_databases()); } // -------------------------------------------------------------------- /** * Optimize Table * * @param string $table_name * @return mixed */ public function optimize_table($table_name) { if ($this->_optimize_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $query = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name))); if ($query !== FALSE) { $query = $query->result_array(); return current($query); } return FALSE; } // -------------------------------------------------------------------- /** * Optimize Database * * @return mixed */ public function optimize_database() { if ($this->_optimize_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $result = array(); foreach ($this->db->list_tables() as $table_name) { $res = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name))); if (is_bool($res)) { return $res; } // Build the result array... $res = $res->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 * * @param string $table_name * @return mixed */ public function repair_table($table_name) { if ($this->_repair_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $query = $this->db->query(sprintf($this->_repair_table, $this->db->escape_identifiers($table_name))); if (is_bool($query)) { return $query; } $query = $query->result_array(); return current($query); } // -------------------------------------------------------------------- /** * Generate CSV from a query result object * * @param object $query Query result object * @param string $delim Delimiter (default: ,) * @param string $newline Newline character (default: \n) * @param string $enclosure Enclosure (default: ") * @return string */ public 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 = substr($out, 0, -strlen($delim)).$newline; // Next blast through the result array and build out the rows while ($row = $query->unbuffered_row('array')) { $line = array(); foreach ($row as $item) { $line[] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, (string) $item).$enclosure; } $out .= implode($delim, $line).$newline; } return $out; } // -------------------------------------------------------------------- /** * Generate XML data from a query result object * * @param object $query Query result object * @param array $params Any preferences * @return string */ public 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 get_instance()->load->helper('xml'); // Generate the result $xml = '<'.$root.'>'.$newline; while ($row = $query->unbuffered_row()) { $xml .= $tab.'<'.$element.'>'.$newline; foreach ($row as $key => $val) { $xml .= $tab.$tab.'<'.$key.'>'.xml_convert($val).''.$newline; } $xml .= $tab.''.$newline; } return $xml.''.$newline; } // -------------------------------------------------------------------- /** * Database Backup * * @param array $params * @return string */ public 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", 'foreign_key_checks' => TRUE ); // 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' && ! function_exists('gzencode')) OR ($prefs['format'] === 'zip' && ! function_exists('gzcompress'))) { if ($this->db->db_debug) { return $this->db->display_error('db_unsupported_compression'); } $prefs['format'] = 'txt'; } // Was a Zip file requested? if ($prefs['format'] === 'zip') { // Set the filename if not provided (only needed with Zip files) if ($prefs['filename'] === '') { $prefs['filename'] = (count($prefs['tables']) === 1 ? $prefs['tables'] : $this->db->database) .date('Y-m-d_H-i', time()).'.sql'; } else { // 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(); } elseif ($prefs['format'] === 'txt') // Was a text file requested? { return $this->_backup($prefs); } elseif ($prefs['format'] === 'gzip') // Was a Gzip file requested? { return gzencode($this->_backup($prefs)); } return; } } database/DB_driver.php000064400000132411152270514220010663 0ustar00 $val) { $this->$key = $val; } } log_message('info', 'Database Driver Class Initialized'); } // -------------------------------------------------------------------- /** * Initialize Database Settings * * @return bool */ public function initialize() { /* If an established connection is available, then there's * no need to connect and select the database. * * Depending on the database driver, conn_id can be either * boolean TRUE, a resource or an object. */ if ($this->conn_id) { return TRUE; } // ---------------------------------------------------------------- // Connect to the database and set the connection ID $this->conn_id = $this->db_connect($this->pconnect); // No connection resource? Check if there is a failover else throw an error if ( ! $this->conn_id) { // Check if there is a failover set if ( ! empty($this->failover) && is_array($this->failover)) { // Go over all the failovers foreach ($this->failover as $failover) { // Replace the current settings with those of the failover foreach ($failover as $key => $val) { $this->$key = $val; } // Try to connect $this->conn_id = $this->db_connect($this->pconnect); // If a connection is made break the foreach loop if ($this->conn_id) { break; } } } // We still don't have a connection? 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; } } // Now we set the character set and that's all return $this->db_set_charset($this->char_set); } // -------------------------------------------------------------------- /** * DB connect * * This is just a dummy method that all drivers will override. * * @return mixed */ public function db_connect() { return TRUE; } // -------------------------------------------------------------------- /** * Persistent database connection * * @return mixed */ public 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. * * This is just a dummy method to allow drivers without such * functionality to not declare it, while others will override it. * * @return void */ public function reconnect() { } // -------------------------------------------------------------------- /** * Select database * * This is just a dummy method to allow drivers without such * functionality to not declare it, while others will override it. * * @return bool */ public function db_select() { return TRUE; } // -------------------------------------------------------------------- /** * Last error * * @return array */ public function error() { return array('code' => NULL, 'message' => NULL); } // -------------------------------------------------------------------- /** * Set client character set * * @param string * @return bool */ public function db_set_charset($charset) { if (method_exists($this, '_db_set_charset') && ! $this->_db_set_charset($charset)) { log_message('error', 'Unable to set database connection charset: '.$charset); if ($this->db_debug) { $this->display_error('db_unable_to_set_charset', $charset); } return FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * The name of the platform in use (mysql, mssql, etc...) * * @return string */ public function platform() { return $this->dbdriver; } // -------------------------------------------------------------------- /** * Database version number * * Returns a string containing the version of the database being used. * Most drivers will override this method. * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if (FALSE === ($sql = $this->_version())) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $query = $this->query($sql)->row(); return $this->data_cache['version'] = $query->ver; } // -------------------------------------------------------------------- /** * Version number query string * * @return string */ protected function _version() { return 'SELECT VERSION() AS 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. * * @param string $sql * @param array $binds = FALSE An array of binding data * @param bool $return_object = NULL * @return mixed */ public function query($sql, $binds = FALSE, $return_object = NULL) { if ($sql === '') { log_message('error', 'Invalid query: '.$sql); return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE; } elseif ( ! is_bool($return_object)) { $return_object = ! $this->is_write_type($sql); } // Verify table prefix and replace if necessary if ($this->dbprefix !== '' && $this->swap_pre !== '' && $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 && $return_object === TRUE && $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 = microtime(TRUE); // 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 if ($this->_trans_depth !== 0) { $this->_trans_status = FALSE; } // Grab the error now, as we might run some additional queries before displaying the error $error = $this->error(); // Log errors log_message('error', 'Query error: '.$error['message'].' - Invalid query: '.$sql); if ($this->db_debug) { // 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. while ($this->_trans_depth !== 0) { $trans_depth = $this->_trans_depth; $this->trans_complete(); if ($trans_depth === $this->_trans_depth) { log_message('error', 'Database: Failure during an automated transaction commit/rollback!'); break; } } // Display errors return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql)); } return FALSE; } // Stop and aggregate the query time results $time_end = microtime(TRUE); $this->benchmark += $time_end - $time_start; if ($this->save_queries === TRUE) { $this->query_times[] = $time_end - $time_start; } // Increment the query counter $this->query_count++; // Will we have a result object instantiated? If not - we'll simply return TRUE if ($return_object !== TRUE) { // If caching is enabled we'll auto-cleanup any existing files related to this particular URI if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init()) { $this->CACHE->delete(); } return TRUE; } // Load and instantiate the result driver $driver = $this->load_rdriver(); $RES = new $driver($this); // Is query caching enabled? If so, we'll serialize the // result object and save it to a cache file. if ($this->cache_on === TRUE && $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($this); $CR->result_object = $RES->result_object(); $CR->result_array = $RES->result_array(); $CR->num_rows = $RES->num_rows(); // 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 * * @return string the name of the result class */ public function load_rdriver() { $driver = 'CI_DB_'.$this->dbdriver.'_result'; if ( ! class_exists($driver, FALSE)) { require_once(BASEPATH.'database/DB_result.php'); require_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. * * @param string the sql query * @return mixed */ public function simple_query($sql) { if ( ! $this->conn_id) { if ( ! $this->initialize()) { return FALSE; } } return $this->_execute($sql); } // -------------------------------------------------------------------- /** * Disable Transactions * This permits transactions to be disabled at run-time. * * @return void */ public 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 subsequent 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 * * @param bool $mode = TRUE * @return void */ public function trans_strict($mode = TRUE) { $this->trans_strict = is_bool($mode) ? $mode : TRUE; } // -------------------------------------------------------------------- /** * Start Transaction * * @param bool $test_mode = FALSE * @return bool */ public function trans_start($test_mode = FALSE) { if ( ! $this->trans_enabled) { return FALSE; } return $this->trans_begin($test_mode); } // -------------------------------------------------------------------- /** * Complete Transaction * * @return bool */ public function trans_complete() { if ( ! $this->trans_enabled) { return FALSE; } // The query() function will set this flag to FALSE in the event that a query failed if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE) { $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; } return $this->trans_commit(); } // -------------------------------------------------------------------- /** * Lets you retrieve the transaction flag to determine if it has failed * * @return bool */ public function trans_status() { return $this->_trans_status; } // -------------------------------------------------------------------- /** * Returns TRUE if a transaction is currently active * * @return bool */ public function trans_active() { return (bool) $this->_trans_depth; } // -------------------------------------------------------------------- /** * Begin Transaction * * @param bool $test_mode * @return bool */ public function trans_begin($test_mode = FALSE) { if ( ! $this->trans_enabled) { return FALSE; } // When transactions are nested we only begin/commit/rollback the outermost ones elseif ($this->_trans_depth > 0) { $this->_trans_depth++; 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); if ($this->_trans_begin()) { $this->_trans_status = TRUE; $this->_trans_depth++; return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ public function trans_commit() { if ( ! $this->trans_enabled OR $this->_trans_depth === 0) { return FALSE; } // When transactions are nested we only begin/commit/rollback the outermost ones elseif ($this->_trans_depth > 1 OR $this->_trans_commit()) { $this->_trans_depth--; return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ public function trans_rollback() { if ( ! $this->trans_enabled OR $this->_trans_depth === 0) { return FALSE; } // When transactions are nested we only begin/commit/rollback the outermost ones elseif ($this->_trans_depth > 1 OR $this->_trans_rollback()) { $this->_trans_depth--; return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Compile Bindings * * @param string the sql statement * @param array an array of bind data * @return string */ public function compile_binds($sql, $binds) { if (empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE) { return $sql; } elseif ( ! is_array($binds)) { $binds = array($binds); $bind_count = 1; } else { // Make sure we're using numeric keys $binds = array_values($binds); $bind_count = count($binds); } // We'll need the marker length later $ml = strlen($this->bind_marker); // Make sure not to replace a chunk inside a string that happens to match the bind marker if ($c = preg_match_all("/'[^']*'|\"[^\"]*\"/i", $sql, $matches)) { $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', str_replace($matches[0], str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]), $sql, $c), $matches, PREG_OFFSET_CAPTURE); // Bind values' count must match the count of markers in the query if ($bind_count !== $c) { return $sql; } } elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count) { return $sql; } do { $c--; $escaped_value = $this->escape($binds[$c]); if (is_array($escaped_value)) { $escaped_value = '('.implode(',', $escaped_value).')'; } $sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml); } while ($c !== 0); return $sql; } // -------------------------------------------------------------------- /** * Determines if a query is a "write" type. * * @param string An SQL query string * @return bool */ public function is_write_type($sql) { return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX|MERGE)\s/i', $sql); } // -------------------------------------------------------------------- /** * Calculate the aggregate query elapsed time * * @param int The number of decimal places * @return string */ public function elapsed_time($decimals = 6) { return number_format($this->benchmark, $decimals); } // -------------------------------------------------------------------- /** * Returns the total number of queries * * @return int */ public function total_queries() { return $this->query_count; } // -------------------------------------------------------------------- /** * Returns the last query that was executed * * @return string */ public function last_query() { return end($this->queries); } // -------------------------------------------------------------------- /** * "Smart" Escape String * * Escapes data based on type * Sets boolean and null types * * @param string * @return mixed */ public function escape($str) { if (is_array($str)) { $str = array_map(array(&$this, 'escape'), $str); return $str; } elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString'))) { return "'".$this->escape_str($str)."'"; } elseif (is_bool($str)) { return ($str === FALSE) ? 0 : 1; } elseif ($str === NULL) { return 'NULL'; } return $str; } // -------------------------------------------------------------------- /** * Escape String * * @param string|string[] $str Input string * @param bool $like 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 = $this->_escape_str($str); // escape LIKE condition wildcards if ($like === TRUE) { return 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; } // -------------------------------------------------------------------- /** * Escape LIKE String * * Calls the individual driver for platform * specific escaping for LIKE conditions * * @param string|string[] * @return mixed */ public function escape_like_str($str) { return $this->escape_str($str, TRUE); } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { return str_replace("'", "''", remove_invisible_characters($str, FALSE)); } // -------------------------------------------------------------------- /** * Primary * * Retrieves the primary key. It assumes that the row in the first * position is the primary key * * @param string $table Table name * @return string */ public function primary($table) { $fields = $this->list_fields($table); return is_array($fields) ? current($fields) : FALSE; } // -------------------------------------------------------------------- /** * "Count All" query * * Generates a platform-specific query string that counts all records in * the specified database * * @param string * @return int */ public function count_all($table = '') { if ($table === '') { return 0; } $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE)); if ($query->num_rows() === 0) { return 0; } $query = $query->row(); $this->_reset_select(); return (int) $query->numrows; } // -------------------------------------------------------------------- /** * Returns an array of table names * * @param string $constrain_by_prefix = FALSE * @return array */ public 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))) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $this->data_cache['table_names'] = array(); $query = $this->query($sql); foreach ($query->result_array() as $row) { // Do we know from which column to get the table name? if ( ! isset($key)) { if (isset($row['table_name'])) { $key = 'table_name'; } elseif (isset($row['TABLE_NAME'])) { $key = 'TABLE_NAME'; } else { /* We have no other choice but to just get the first element's key. * Due to array_shift() accepting its argument by reference, if * E_STRICT is on, this would trigger a warning. So we'll have to * assign it first. */ $key = array_keys($row); $key = array_shift($key); } } $this->data_cache['table_names'][] = $row[$key]; } return $this->data_cache['table_names']; } // -------------------------------------------------------------------- /** * Determine if a particular table exists * * @param string $table_name * @return bool */ public function table_exists($table_name) { return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables()); } // -------------------------------------------------------------------- /** * Fetch Field Names * * @param string $table Table name * @return array */ public function list_fields($table) { if (FALSE === ($sql = $this->_list_columns($table))) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $query = $this->query($sql); $fields = array(); foreach ($query->result_array() as $row) { // Do we know from where to get the column's name? if ( ! isset($key)) { if (isset($row['column_name'])) { $key = 'column_name'; } elseif (isset($row['COLUMN_NAME'])) { $key = 'COLUMN_NAME'; } else { // We have no other choice but to just get the first element's key. $key = key($row); } } $fields[] = $row[$key]; } return $fields; } // -------------------------------------------------------------------- /** * Determine if a particular field exists * * @param string * @param string * @return bool */ public function field_exists($field_name, $table_name) { return in_array($field_name, $this->list_fields($table_name)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table the table name * @return array */ public function field_data($table) { $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE))); return ($query) ? $query->field_data() : FALSE; } // -------------------------------------------------------------------- /** * Escape the SQL Identifiers * * This function escapes column and table names * * @param mixed * @return mixed */ public function escape_identifiers($item) { if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers)) { return $item; } elseif (is_array($item)) { foreach ($item as $key => $value) { $item[$key] = $this->escape_identifiers($value); } return $item; } // Avoid breaking functions and literal values inside queries elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE) { return $item; } static $preg_ec = array(); if (empty($preg_ec)) { if (is_array($this->_escape_char)) { $preg_ec = array( preg_quote($this->_escape_char[0], '/'), preg_quote($this->_escape_char[1], '/'), $this->_escape_char[0], $this->_escape_char[1] ); } else { $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/'); $preg_ec[2] = $preg_ec[3] = $this->_escape_char; } } foreach ($this->_reserved_identifiers as $id) { if (strpos($item, '.'.$id) !== FALSE) { return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item); } } return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item); } // -------------------------------------------------------------------- /** * Generate an insert string * * @param string the table upon which the query will be performed * @param array an associative array data of key/values * @return string */ public function insert_string($table, $data) { $fields = $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); } // -------------------------------------------------------------------- /** * Insert statement * * Generates a platform-specific insert string from the supplied data * * @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).')'; } // -------------------------------------------------------------------- /** * Generate an update string * * @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 */ public function update_string($table, $data, $where) { if (empty($where)) { return FALSE; } $this->where($where); $fields = array(); foreach ($data as $key => $val) { $fields[$this->protect_identifiers($key)] = $this->escape($val); } $sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields); $this->_reset_write(); return $sql; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string the table name * @param array the update data * @return string */ protected function _update($table, $values) { foreach ($values as $key => $val) { $valstr[] = $key.' = '.$val; } return 'UPDATE '.$table.' SET '.implode(', ', $valstr) .$this->_compile_wh('qb_where') .$this->_compile_order_by() .($this->qb_limit !== FALSE ? ' LIMIT '.$this->qb_limit : ''); } // -------------------------------------------------------------------- /** * Tests whether the string has an SQL operator * * @param string * @return bool */ protected function _has_operator($str) { return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str)); } // -------------------------------------------------------------------- /** * Returns the SQL string operator * * @param string * @return string */ protected function _get_operator($str) { static $_operators; if (empty($_operators)) { $_les = ($this->_like_escape_str !== '') ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/') : ''; $_operators = array( '\s*(?:<|>|!)?=\s*', // =, <=, >=, != '\s*<>?\s*', // <, <> '\s*>\s*', // > '\s+IS NULL', // IS NULL '\s+IS NOT NULL', // IS NOT NULL '\s+EXISTS\s*\(.*\)', // EXISTS(sql) '\s+NOT EXISTS\s*\(.*\)', // NOT EXISTS(sql) '\s+BETWEEN\s+', // BETWEEN value AND value '\s+NOT BETWEEN\s+', // NOT BETWEEN value AND value '\s+IN\s*\(.*\)', // IN(list) '\s+NOT IN\s*\(.*\)', // NOT IN (list) '\s+LIKE\s+\S.*('.$_les.')?', // LIKE 'expr'[ ESCAPE '%s'] '\s+NOT LIKE\s+\S.*('.$_les.')?' // NOT LIKE 'expr'[ ESCAPE '%s'] ); } return preg_match('/'.implode('|', $_operators).'/i', $str, $match) ? $match[0] : FALSE; } // -------------------------------------------------------------------- /** * Enables a native PHP function to be run, using a platform agnostic wrapper. * * @param string $function Function name * @return mixed */ public function call_function($function) { $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_'; if (FALSE === strpos($driver, $function)) { $function = $driver.$function; } if ( ! function_exists($function)) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } return (func_num_args() > 1) ? call_user_func_array($function, array_slice(func_get_args(), 1)) : call_user_func($function); } // -------------------------------------------------------------------- /** * Set Cache Directory Path * * @param string the path to the cache directory * @return void */ public function cache_set_path($path = '') { $this->cachedir = $path; } // -------------------------------------------------------------------- /** * Enable Query Caching * * @return bool cache_on value */ public function cache_on() { return $this->cache_on = TRUE; } // -------------------------------------------------------------------- /** * Disable Query Caching * * @return bool cache_on value */ public function cache_off() { return $this->cache_on = FALSE; } // -------------------------------------------------------------------- /** * Delete the cache files associated with a particular URI * * @param string $segment_one = '' * @param string $segment_two = '' * @return bool */ public function cache_delete($segment_one = '', $segment_two = '') { return $this->_cache_init() ? $this->CACHE->delete($segment_one, $segment_two) : FALSE; } // -------------------------------------------------------------------- /** * Delete All cache files * * @return bool */ public function cache_delete_all() { return $this->_cache_init() ? $this->CACHE->delete_all() : FALSE; } // -------------------------------------------------------------------- /** * Initialize the Cache Class * * @return bool */ protected function _cache_init() { if ( ! class_exists('CI_DB_Cache', FALSE)) { require_once(BASEPATH.'database/DB_cache.php'); } elseif (is_object($this->CACHE)) { return TRUE; } $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects return TRUE; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ public function close() { if ($this->conn_id) { $this->_close(); $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Close DB Connection * * This method would be overridden by most of the drivers. * * @return void */ protected function _close() { $this->conn_id = FALSE; } // -------------------------------------------------------------------- /** * Display an error message * * @param string the error message * @param string any "swap" values * @param bool whether to localize the message * @return string sends the application/views/errors/error_db.php template */ public 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 = (array) $error; } else { $message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($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'], $call['class'])) { // We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes if (DIRECTORY_SEPARATOR !== '/') { $call['file'] = str_replace('\\', '/', $call['file']); } if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE) { // Found it - use a relative path for safety $message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']); $message[] = 'Line Number: '.$call['line']; break; } } } $error =& load_class('Exceptions', 'core'); echo $error->show_error($heading, $message, 'error_db'); exit(8); // EXIT_DATABASE } // -------------------------------------------------------------------- /** * Protect Identifiers * * This function is used extensively by the Query Builder 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 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. * * @param string * @param bool * @param mixed * @param bool * @return string */ public 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, $prefix_single, $protect_identifiers, $field_exists); } return $escaped_array; } // 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 // // Added exception for single quotes as well, we don't want to alter // literal strings. -- Narf if (strcspn($item, "()'") !== strlen($item)) { return $item; } // Convert tabs or multiple spaces into single spaces $item = preg_replace('/\s+/', ' ', trim($item)); // If the item has an alias declaration we remove it and set it aside. // Note: strripos() is used in order to support spaces in table names if ($offset = strripos($item, ' AS ')) { $alias = ($protect_identifiers) ? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4)) : substr($item, $offset); $item = substr($item, 0, $offset); } elseif ($offset = strrpos($item, ' ')) { $alias = ($protect_identifiers) ? ' '.$this->escape_identifiers(substr($item, $offset + 1)) : substr($item, $offset); $item = substr($item, 0, $offset); } else { $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 // // NOTE: The ! empty() condition prevents this method // from breaking when QB isn't enabled. if ( ! empty($this->qb_aliased_tables) && in_array($parts[0], $this->qb_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++; } // dbprefix may've already been applied, with or without the identifier escaped $ec = '(?'.preg_quote(is_array($this->_escape_char) ? $this->_escape_char[0] : $this->_escape_char).')?'; isset($ec[0]) && $ec .= '?'; // Just in case someone has disabled escaping by forcing an empty escape character // Verify table prefix and replace if necessary if ($this->swap_pre !== '' && preg_match('#^'.$ec.preg_quote($this->swap_pre).'#', $parts[$i])) { $parts[$i] = preg_replace('#^'.$ec.preg_quote($this->swap_pre).'(\S+?)#', '\\1'.$this->dbprefix.'\\2', $parts[$i]); } // We only add the table prefix if it does not already exist else { preg_match('#^'.$ec.preg_quote($this->dbprefix).'#', $parts[$i]) OR $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 !== '' && strpos($item, $this->swap_pre) === 0) { $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item); } // Do we prefix an item with no segments? elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0) { $item = $this->dbprefix.$item; } } if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers)) { $item = $this->escape_identifiers($item); } return $item.$alias; } // -------------------------------------------------------------------- /** * Dummy method that allows Query Builder class to be disabled * and keep count_all() working. * * @return void */ protected function _reset_select() { } } database/DB_query_builder.php000064400000174551152270514220012256 0ustar00_protect_identifiers; foreach ($select as $val) { $val = trim($val); if ($val !== '') { $this->qb_select[] = $val; $this->qb_no_escape[] = $escape; if ($this->qb_caching === TRUE) { $this->qb_cache_select[] = $val; $this->qb_cache_exists[] = 'select'; $this->qb_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 CI_DB_query_builder */ 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 CI_DB_query_builder */ 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 CI_DB_query_builder */ 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 CI_DB_query_builder */ public function select_sum($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'SUM'); } // -------------------------------------------------------------------- /** * SELECT [MAX|MIN|AVG|SUM]() * * @used-by select_max() * @used-by select_min() * @used-by select_avg() * @used-by select_sum() * * @param string $select Field name * @param string $alias * @param string $type * @return CI_DB_query_builder */ 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 '.$this->escape_identifiers(trim($alias)); $this->qb_select[] = $sql; $this->qb_no_escape[] = NULL; if ($this->qb_caching === TRUE) { $this->qb_cache_select[] = $sql; $this->qb_cache_exists[] = 'select'; } return $this; } // -------------------------------------------------------------------- /** * Determines the alias name based on the table * * @param string $item * @return string */ protected function _create_alias_from_table($item) { if (strpos($item, '.') !== FALSE) { $item = explode('.', $item); return end($item); } return $item; } // -------------------------------------------------------------------- /** * DISTINCT * * Sets a flag which tells the query string compiler to add DISTINCT * * @param bool $val * @return CI_DB_query_builder */ public function distinct($val = TRUE) { $this->qb_distinct = is_bool($val) ? $val : TRUE; return $this; } // -------------------------------------------------------------------- /** * From * * Generates the FROM portion of the query * * @param mixed $from can be a string or array * @return CI_DB_query_builder */ 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->qb_from[] = $v = $this->protect_identifiers($v, TRUE, NULL, FALSE); if ($this->qb_caching === TRUE) { $this->qb_cache_from[] = $v; $this->qb_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->qb_from[] = $val = $this->protect_identifiers($val, TRUE, NULL, FALSE); if ($this->qb_caching === TRUE) { $this->qb_cache_from[] = $val; $this->qb_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 * @param string whether not to try to escape identifiers * @return CI_DB_query_builder */ public function join($table, $cond, $type = '', $escape = NULL) { if ($type !== '') { $type = strtoupper(trim($type ?? '')); if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER', 'FULL OUTER', 'FULL'), TRUE)) { $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); is_bool($escape) OR $escape = $this->_protect_identifiers; if ( ! $this->_has_operator($cond)) { $cond = ' USING ('.($escape ? $this->escape_identifiers($cond) : $cond).')'; } elseif ($escape === FALSE) { $cond = ' ON '.$cond; } else { // Split multiple conditions if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE)) { $conditions = array(); $joints = $joints[0]; array_unshift($joints, array('', 0)); for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i--) { $joints[$i][1] += strlen($joints[$i][0]); // offset $conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]); $pos = $joints[$i][1] - strlen($joints[$i][0]); $joints[$i] = $joints[$i][0]; } } else { $conditions = array($cond); $joints = array(''); } $cond = ' ON '; for ($i = 0, $c = count($conditions); $i < $c; $i++) { $operator = $this->_get_operator($conditions[$i]); $cond .= $joints[$i]; $cond .= preg_match("/(\(*)?([\[\]\w\.'-]+)".preg_quote($operator)."(.*)/i", $conditions[$i], $match) ? $match[1].$this->protect_identifiers($match[2]).$operator.$this->protect_identifiers($match[3]) : $conditions[$i]; } } // Do we want to escape the table name? if ($escape === TRUE) { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } // Assemble the JOIN statement $this->qb_join[] = $join = $type.'JOIN '.$table.$cond; if ($this->qb_caching === TRUE) { $this->qb_cache_join[] = $join; $this->qb_cache_exists[] = 'join'; } return $this; } // -------------------------------------------------------------------- /** * WHERE * * Generates the WHERE portion of the query. * Separates multiple calls with 'AND'. * * @param mixed * @param mixed * @param bool * @return CI_DB_query_builder */ public function where($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_where', $key, $value, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR WHERE * * Generates the WHERE portion of the query. * Separates multiple calls with 'OR'. * * @param mixed * @param mixed * @param bool * @return CI_DB_query_builder */ public function or_where($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_where', $key, $value, 'OR ', $escape); } // -------------------------------------------------------------------- /** * WHERE, HAVING * * @used-by where() * @used-by or_where() * @used-by having() * @used-by or_having() * * @param string $qb_key 'qb_where' or 'qb_having' * @param mixed $key * @param mixed $value * @param string $type * @param bool $escape * @return CI_DB_query_builder */ protected function _wh($qb_key, $key, $value = NULL, $type = 'AND ', $escape = NULL) { $qb_cache_key = ($qb_key === 'qb_having') ? 'qb_cache_having' : 'qb_cache_where'; if ( ! is_array($key)) { $key = array($key => $value); } // If the escape value was not set will base it on the global setting is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($key as $k => $v) { $prefix = (count($this->$qb_key) === 0 && count($this->$qb_cache_key) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); if ($v !== NULL) { if ($escape === TRUE) { $v = $this->escape($v); } if ( ! $this->_has_operator($k)) { $k .= ' = '; } } elseif ( ! $this->_has_operator($k)) { // value appears not to have been set, assign the test to IS NULL $k .= ' IS NULL'; } elseif (preg_match('/\s*(!?=|<>|\sIS(?:\s+NOT)?\s)\s*$/i', $k, $match, PREG_OFFSET_CAPTURE)) { $k = substr($k, 0, $match[0][1]).($match[1][0] === '=' ? ' IS NULL' : ' IS NOT NULL'); } ${$qb_key} = array('condition' => $prefix.$k, 'value' => $v, 'escape' => $escape); $this->{$qb_key}[] = ${$qb_key}; if ($this->qb_caching === TRUE) { $this->{$qb_cache_key}[] = ${$qb_key}; $this->qb_cache_exists[] = substr($qb_key, 3); } } return $this; } // -------------------------------------------------------------------- /** * WHERE IN * * Generates a WHERE field IN('item', 'item') SQL query, * joined with 'AND' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function where_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, FALSE, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR WHERE IN * * Generates a WHERE field IN('item', 'item') SQL query, * joined with 'OR' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function or_where_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, FALSE, 'OR ', $escape); } // -------------------------------------------------------------------- /** * WHERE NOT IN * * Generates a WHERE field NOT IN('item', 'item') SQL query, * joined with 'AND' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function where_not_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, TRUE, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR WHERE NOT IN * * Generates a WHERE field NOT IN('item', 'item') SQL query, * joined with 'OR' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function or_where_not_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, TRUE, 'OR ', $escape); } // -------------------------------------------------------------------- /** * Internal WHERE IN * * @used-by where_in() * @used-by or_where_in() * @used-by where_not_in() * @used-by or_where_not_in() * * @param string $key The field to search * @param array $values The values searched on * @param bool $not If the statement would be IN or NOT IN * @param string $type * @param bool $escape * @return CI_DB_query_builder */ protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ', $escape = NULL) { if ($key === NULL OR $values === NULL) { return $this; } if ( ! is_array($values)) { $values = array($values); } is_bool($escape) OR $escape = $this->_protect_identifiers; $not = ($not) ? ' NOT' : ''; if ($escape === TRUE) { $where_in = array(); foreach ($values as $value) { $where_in[] = $this->escape($value); } } else { $where_in = array_values($values); } $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); $where_in = array( 'condition' => $prefix.$key.$not.' IN('.implode(', ', $where_in).')', 'value' => NULL, 'escape' => $escape ); $this->qb_where[] = $where_in; if ($this->qb_caching === TRUE) { $this->qb_cache_where[] = $where_in; $this->qb_cache_exists[] = 'where'; } return $this; } // -------------------------------------------------------------------- /** * LIKE * * Generates a %LIKE% portion of the query. * Separates multiple calls with 'AND'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'AND ', $side, '', $escape); } // -------------------------------------------------------------------- /** * NOT LIKE * * Generates a NOT LIKE portion of the query. * Separates multiple calls with 'AND'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function not_like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape); } // -------------------------------------------------------------------- /** * OR LIKE * * Generates a %LIKE% portion of the query. * Separates multiple calls with 'OR'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function or_like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'OR ', $side, '', $escape); } // -------------------------------------------------------------------- /** * OR NOT LIKE * * Generates a NOT LIKE portion of the query. * Separates multiple calls with 'OR'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function or_not_like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape); } // -------------------------------------------------------------------- /** * Internal LIKE * * @used-by like() * @used-by or_like() * @used-by not_like() * @used-by or_not_like() * * @param mixed $field * @param string $match * @param string $type * @param string $side * @param string $not * @param bool $escape * @return CI_DB_query_builder */ protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $escape = NULL) { if ( ! is_array($field)) { $field = array($field => $match); } is_bool($escape) OR $escape = $this->_protect_identifiers; // lowercase $side in case somebody writes e.g. 'BEFORE' instead of 'before' (doh) $side = strtolower($side); foreach ($field as $k => $v) { $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); if ($escape === TRUE) { $v = $this->escape_like_str($v); } switch ($side) { case 'none': $v = "'{$v}'"; break; case 'before': $v = "'%{$v}'"; break; case 'after': $v = "'{$v}%'"; break; case 'both': default: $v = "'%{$v}%'"; break; } // some platforms require an escape sequence definition for LIKE wildcards if ($escape === TRUE && $this->_like_escape_str !== '') { $v .= sprintf($this->_like_escape_str, $this->_like_escape_chr); } $qb_where = array('condition' => "{$prefix} {$k} {$not} LIKE {$v}", 'value' => NULL, 'escape' => $escape); $this->qb_where[] = $qb_where; if ($this->qb_caching === TRUE) { $this->qb_cache_where[] = $qb_where; $this->qb_cache_exists[] = 'where'; } } return $this; } // -------------------------------------------------------------------- /** * Starts a query group. * * @param string $not (Internal use only) * @param string $type (Internal use only) * @return CI_DB_query_builder */ public function group_start($not = '', $type = 'AND ') { $type = $this->_group_get_type($type); $this->qb_where_group_started = TRUE; $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type; $where = array( 'condition' => $prefix.$not.str_repeat(' ', ++$this->qb_where_group_count).' (', 'value' => NULL, 'escape' => FALSE ); $this->qb_where[] = $where; if ($this->qb_caching) { $this->qb_cache_where[] = $where; } return $this; } // -------------------------------------------------------------------- /** * Starts a query group, but ORs the group * * @return CI_DB_query_builder */ public function or_group_start() { return $this->group_start('', 'OR '); } // -------------------------------------------------------------------- /** * Starts a query group, but NOTs the group * * @return CI_DB_query_builder */ public function not_group_start() { return $this->group_start('NOT ', 'AND '); } // -------------------------------------------------------------------- /** * Starts a query group, but OR NOTs the group * * @return CI_DB_query_builder */ public function or_not_group_start() { return $this->group_start('NOT ', 'OR '); } // -------------------------------------------------------------------- /** * Ends a query group * * @return CI_DB_query_builder */ public function group_end() { $this->qb_where_group_started = FALSE; $where = array( 'condition' => str_repeat(' ', $this->qb_where_group_count--).')', 'value' => NULL, 'escape' => FALSE ); $this->qb_where[] = $where; if ($this->qb_caching) { $this->qb_cache_where[] = $where; } return $this; } // -------------------------------------------------------------------- /** * Group_get_type * * @used-by group_start() * @used-by _like() * @used-by _wh() * @used-by _where_in() * * @param string $type * @return string */ protected function _group_get_type($type) { if ($this->qb_where_group_started) { $type = ''; $this->qb_where_group_started = FALSE; } return $type; } // -------------------------------------------------------------------- /** * GROUP BY * * @param mixed $by * @param bool $escape * @return CI_DB_query_builder */ public function group_by($by, $escape = NULL) { is_bool($escape) OR $escape = $this->_protect_identifiers; if (is_string($by)) { $by = ($escape === TRUE) ? explode(',', $by) : array($by); } foreach ($by as $val) { $val = trim($val); if ($val !== '') { $val = array('field' => $val, 'escape' => $escape); $this->qb_groupby[] = $val; if ($this->qb_caching === TRUE) { $this->qb_cache_groupby[] = $val; $this->qb_cache_exists[] = 'groupby'; } } } return $this; } // -------------------------------------------------------------------- /** * HAVING * * Separates multiple calls with 'AND'. * * @param string $key * @param string $value * @param bool $escape * @return CI_DB_query_builder */ public function having($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_having', $key, $value, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR HAVING * * Separates multiple calls with 'OR'. * * @param string $key * @param string $value * @param bool $escape * @return CI_DB_query_builder */ public function or_having($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_having', $key, $value, 'OR ', $escape); } // -------------------------------------------------------------------- /** * ORDER BY * * @param string $orderby * @param string $direction ASC, DESC or RANDOM * @param bool $escape * @return CI_DB_query_builder */ public function order_by($orderby, $direction = '', $escape = NULL) { $direction = strtoupper(trim($direction)); if ($direction === 'RANDOM') { $direction = ''; // Do we have a seed value? $orderby = ctype_digit((string) $orderby) ? sprintf($this->_random_keyword[1], $orderby) : $this->_random_keyword[0]; } elseif (empty($orderby)) { return $this; } elseif ($direction !== '') { $direction = in_array($direction, array('ASC', 'DESC'), TRUE) ? ' '.$direction : ''; } is_bool($escape) OR $escape = $this->_protect_identifiers; if ($escape === FALSE) { $qb_orderby[] = array('field' => $orderby, 'direction' => $direction, 'escape' => FALSE); } else { $qb_orderby = array(); foreach (explode(',', $orderby) as $field) { $qb_orderby[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE)) ? array('field' => ltrim(substr($field, 0, $match[0][1])), 'direction' => ' '.$match[1][0], 'escape' => TRUE) : array('field' => trim($field), 'direction' => $direction, 'escape' => TRUE); } } $this->qb_orderby = array_merge($this->qb_orderby, $qb_orderby); if ($this->qb_caching === TRUE) { $this->qb_cache_orderby = array_merge($this->qb_cache_orderby, $qb_orderby); $this->qb_cache_exists[] = 'orderby'; } return $this; } // -------------------------------------------------------------------- /** * LIMIT * * @param int $value LIMIT value * @param int $offset OFFSET value * @return CI_DB_query_builder */ public function limit($value, $offset = 0) { is_null($value) OR $this->qb_limit = (int) $value; empty($offset) OR $this->qb_offset = (int) $offset; return $this; } // -------------------------------------------------------------------- /** * Sets the OFFSET value * * @param int $offset OFFSET value * @return CI_DB_query_builder */ public function offset($offset) { empty($offset) OR $this->qb_offset = (int) $offset; return $this; } // -------------------------------------------------------------------- /** * LIMIT string * * Generates a platform-specific LIMIT clause. * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').(int) $this->qb_limit; } // -------------------------------------------------------------------- /** * The "set" function. * * Allows key/value pairs to be set for inserting or updating * * @param mixed * @param string * @param bool * @return CI_DB_query_builder */ public function set($key, $value = '', $escape = NULL) { $key = $this->_object_to_array($key); if ( ! is_array($key)) { $key = array($key => $value); } is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($key as $k => $v) { $this->qb_set[$this->protect_identifiers($k, FALSE, $escape)] = ($escape) ? $this->escape($v) : $v; } return $this; } // -------------------------------------------------------------------- /** * Get SELECT query string * * Compiles a SELECT query string and returns the sql. * * @param string the table name to select from (optional) * @param bool TRUE: resets QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_select($table = '', $reset = TRUE) { if ($table !== '') { $this->_track_aliases($table); $this->from($table); } $select = $this->_compile_select(); if ($reset === TRUE) { $this->_reset_select(); } return $select; } // -------------------------------------------------------------------- /** * 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 CI_DB_result */ public function get($table = '', $limit = NULL, $offset = NULL) { if ($table !== '') { $this->_track_aliases($table); $this->from($table); } if ( ! empty($limit)) { $this->limit($limit, $offset); } $result = $this->query($this->_compile_select()); $this->_reset_select(); return $result; } // -------------------------------------------------------------------- /** * "Count All Results" query * * Generates a platform-specific query string that counts all records * returned by an Query Builder query. * * @param string * @param bool the reset clause * @return int */ public function count_all_results($table = '', $reset = TRUE) { if ($table !== '') { $this->_track_aliases($table); $this->from($table); } // ORDER BY usage is often problematic here (most notably // on Microsoft SQL Server) and ultimately unnecessary // for selecting COUNT(*) ... $qb_orderby = $this->qb_orderby; $qb_cache_orderby = $this->qb_cache_orderby; $this->qb_orderby = $this->qb_cache_orderby = array(); $result = ($this->qb_distinct === TRUE OR ! empty($this->qb_groupby) OR ! empty($this->qb_cache_groupby) OR ! empty($this->qb_having) OR $this->qb_limit OR $this->qb_offset) ? $this->query($this->_count_string.$this->protect_identifiers('numrows')."\nFROM (\n".$this->_compile_select()."\n) CI_count_all_results") : $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows'))); if ($reset === TRUE) { $this->_reset_select(); } else { $this->qb_orderby = $qb_orderby; $this->qb_cache_orderby = $qb_cache_orderby; } if ($result->num_rows() === 0) { return 0; } $row = $result->row(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * get_where() * * Allows the where clause, limit and offset to be added directly * * @param string $table * @param string $where * @param int $limit * @param int $offset * @return CI_DB_result */ public function get_where($table = '', $where = NULL, $limit = NULL, $offset = NULL) { if ($table !== '') { $this->from($table); } if ($where !== NULL) { $this->where($where); } if ( ! empty($limit)) { $this->limit($limit, $offset); } $result = $this->query($this->_compile_select()); $this->_reset_select(); return $result; } // -------------------------------------------------------------------- /** * Insert_Batch * * Compiles batch insert strings and runs the queries * * @param string $table Table to insert into * @param array $set An associative array of insert values * @param bool $escape Whether to escape values and identifiers * @return int Number of rows inserted or FALSE on failure */ public function insert_batch($table, $set = NULL, $escape = NULL, $batch_size = 100) { if ($set === NULL) { if (empty($this->qb_set)) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } } else { if (empty($set)) { return ($this->db_debug) ? $this->display_error('insert_batch() called with no data') : FALSE; } $this->set_insert_batch($set, '', $escape); } if (strlen($table) === 0) { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } // Batch this baby $affected_rows = 0; for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size) { if ($this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, $batch_size)))) { $affected_rows += $this->affected_rows(); } } $this->_reset_write(); return $affected_rows; } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string */ protected function _insert_batch($table, $keys, $values) { return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values); } // -------------------------------------------------------------------- /** * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts * * @param mixed * @param string * @param bool * @return CI_DB_query_builder */ public function set_insert_batch($key, $value = '', $escape = NULL) { $key = $this->_object_to_array_batch($key); if ( ! is_array($key)) { $key = array($key => $value); } is_bool($escape) OR $escape = $this->_protect_identifiers; $keys = array_keys($this->_object_to_array(reset($key))); sort($keys); foreach ($key as $row) { $row = $this->_object_to_array($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->qb_set[] = array(); return; } ksort($row); // puts $row in the same order as our keys if ($escape !== FALSE) { $clean = array(); foreach ($row as $value) { $clean[] = $this->escape($value); } $row = $clean; } $this->qb_set[] = '('.implode(',', $row).')'; } foreach ($keys as $k) { $this->qb_keys[] = $this->protect_identifiers($k, FALSE, $escape); } return $this; } // -------------------------------------------------------------------- /** * Get INSERT query string * * Compiles an insert query and returns the sql * * @param string the table to insert into * @param bool TRUE: reset QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_insert($table = '', $reset = TRUE) { if ($this->_validate_insert($table) === FALSE) { return FALSE; } $sql = $this->_insert( $this->protect_identifiers( $this->qb_from[0], TRUE, NULL, FALSE ), array_keys($this->qb_set), array_values($this->qb_set) ); if ($reset === TRUE) { $this->_reset_write(); } return $sql; } // -------------------------------------------------------------------- /** * 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 * @param bool $escape Whether to escape values and identifiers * @return bool TRUE on success, FALSE on failure */ public function insert($table = '', $set = NULL, $escape = NULL) { if ($set !== NULL) { $this->set($set, '', $escape); } if ($this->_validate_insert($table) === FALSE) { return FALSE; } $sql = $this->_insert( $this->protect_identifiers( $this->qb_from[0], TRUE, $escape, FALSE ), array_keys($this->qb_set), array_values($this->qb_set) ); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Validate Insert * * This method is used by both insert() and get_compiled_insert() to * validate that the there data is actually being set and that table * has been chosen to be inserted into. * * @param string the table to insert data into * @return string */ protected function _validate_insert($table = '') { if (count($this->qb_set) === 0) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } if ($table !== '') { $this->qb_from[0] = $table; } elseif ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * 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 bool TRUE on success, FALSE on failure */ public function replace($table = '', $set = NULL) { if ($set !== NULL) { $this->set($set); } if (count($this->qb_set) === 0) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->qb_set), array_values($this->qb_set)); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ protected function _replace($table, $keys, $values) { return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * Note: This is only used (and overridden) by MySQL and CUBRID. * * @return string */ protected function _from_tables() { return implode(', ', $this->qb_from); } // -------------------------------------------------------------------- /** * Get UPDATE query string * * Compiles an update query and returns the sql * * @param string the table to update * @param bool TRUE: reset QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_update($table = '', $reset = TRUE) { // Combine any cached components with the current statements $this->_merge_cache(); if ($this->_validate_update($table) === FALSE) { return FALSE; } $sql = $this->_update($this->qb_from[0], $this->qb_set); if ($reset === TRUE) { $this->_reset_write(); } return $sql; } // -------------------------------------------------------------------- /** * UPDATE * * Compiles an update string and runs the query. * * @param string $table * @param array $set An associative array of update values * @param mixed $where * @param int $limit * @return bool TRUE on success, FALSE on failure */ public function update($table = '', $set = NULL, $where = NULL, $limit = NULL) { // Combine any cached components with the current statements $this->_merge_cache(); if ($set !== NULL) { $this->set($set); } if ($this->_validate_update($table) === FALSE) { return FALSE; } if ($where !== NULL) { $this->where($where); } if ( ! empty($limit)) { $this->limit($limit); } $sql = $this->_update($this->qb_from[0], $this->qb_set); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Validate Update * * This method is used by both update() and get_compiled_update() to * validate that data is actually being set and that a table has been * chosen to be update. * * @param string the table to update data on * @return bool */ protected function _validate_update($table) { if (count($this->qb_set) === 0) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } if ($table !== '') { $this->qb_from = array($this->protect_identifiers($table, TRUE, NULL, FALSE)); } elseif ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * 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 int number of rows affected or FALSE on failure */ public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100) { // Combine any cached components with the current statements $this->_merge_cache(); if ($index === NULL) { return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE; } if ($set === NULL) { if (empty($this->qb_set_ub)) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } } else { if (empty($set)) { return ($this->db_debug) ? $this->display_error('update_batch() called with no data') : FALSE; } $this->set_update_batch($set, $index); } if (strlen($table) === 0) { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } // Batch this baby $affected_rows = 0; for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size) { if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index))) { $affected_rows += $this->affected_rows(); } $this->qb_where = array(); } $this->_reset_write(); return $affected_rows; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @param string $table Table name * @param array $values Update data * @param string $index WHERE key * @return string */ protected function _update_batch($table, $values, $index) { $ids = array(); foreach ($values as $key => $val) { $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['field'].' = '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } $cases = ''; foreach ($final as $k => $v) { $cases .= $k." = CASE \n" .implode("\n", $v)."\n" .'ELSE '.$k.' END, '; } $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } // -------------------------------------------------------------------- /** * The "set_update_batch" function. Allows key/value pairs to be set for batch updating * * @param array * @param string * @param bool * @return CI_DB_query_builder */ public function set_update_batch($key, $index = '', $escape = NULL) { $key = $this->_object_to_array_batch($key); if ( ! is_array($key)) { // @todo error } is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($key as $k => $v) { $index_set = FALSE; $clean = array(); foreach ($v as $k2 => $v2) { if ($k2 === $index) { $index_set = TRUE; } $clean[$k2] = array( 'field' => $this->protect_identifiers($k2, FALSE, $escape), 'value' => ($escape === FALSE ? $v2 : $this->escape($v2)) ); } if ($index_set === FALSE) { return $this->display_error('db_batch_missing_index'); } $this->qb_set_ub[] = $clean; } return $this; } // -------------------------------------------------------------------- /** * Empty Table * * Compiles a delete string and runs "DELETE FROM table" * * @param string the table to empty * @return bool TRUE on success, FALSE on failure */ public function empty_table($table = '') { if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_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 bool TRUE on success, FALSE on failure */ public function truncate($table = '') { if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } else { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } $sql = $this->_truncate($table); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the truncate() command, * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { return 'TRUNCATE '.$table; } // -------------------------------------------------------------------- /** * Get DELETE query string * * Compiles a delete query string and returns the sql * * @param string the table to delete from * @param bool TRUE: reset QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_delete($table = '', $reset = TRUE) { $this->return_delete_sql = TRUE; $sql = $this->delete($table, '', NULL, $reset); $this->return_delete_sql = FALSE; return $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 bool * @return mixed */ 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->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } elseif (is_array($table)) { empty($where) && $reset_data = FALSE; foreach ($table as $single_table) { $this->delete($single_table, $where, $limit, $reset_data); } return; } else { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } if ($where !== '') { $this->where($where); } if ( ! empty($limit)) { $this->limit($limit); } if (count($this->qb_where) === 0) { return ($this->db_debug) ? $this->display_error('db_del_must_use_where') : FALSE; } $sql = $this->_delete($table); if ($reset_data) { $this->_reset_write(); } return ($this->return_delete_sql === TRUE) ? $sql : $this->query($sql); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string the table name * @return string */ protected function _delete($table) { return 'DELETE FROM '.$table.$this->_compile_wh('qb_where') .($this->qb_limit !== FALSE ? ' LIMIT '.$this->qb_limit : ''); } // -------------------------------------------------------------------- /** * 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->qb_aliased_tables, TRUE)) { $this->qb_aliased_tables[] = $table; if ($this->qb_caching === TRUE && ! in_array($table, $this->qb_cache_aliased_tables, TRUE)) { $this->qb_cache_aliased_tables[] = $table; $this->qb_cache_exists[] = 'aliased_tables'; } } } } // -------------------------------------------------------------------- /** * Compile the SELECT statement * * Generates a query string based on which functions were used. * Should not be called directly. * * @param bool $select_override * @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->qb_distinct) ? 'SELECT ' : 'SELECT DISTINCT '; if (count($this->qb_select) === 0) { $sql .= '*'; } else { // Cycle through the "select" portion of the query and prep each column name. // The reason we protect identifiers here rather than in the select() function // is because until the user calls the from() function we don't know if there are aliases foreach ($this->qb_select as $key => $val) { $no_escape = isset($this->qb_no_escape[$key]) ? $this->qb_no_escape[$key] : NULL; $this->qb_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape); } $sql .= implode(', ', $this->qb_select); } } // Write the "FROM" portion of the query if (count($this->qb_from) > 0) { $sql .= "\nFROM ".$this->_from_tables(); } // Write the "JOIN" portion of the query if (count($this->qb_join) > 0) { $sql .= "\n".implode("\n", $this->qb_join); } $sql .= $this->_compile_wh('qb_where') .$this->_compile_group_by() .$this->_compile_wh('qb_having') .$this->_compile_order_by(); // ORDER BY // LIMIT if ($this->qb_limit !== FALSE OR $this->qb_offset) { return $this->_limit($sql."\n"); } return $sql; } // -------------------------------------------------------------------- /** * Compile WHERE, HAVING statements * * Escapes identifiers in WHERE and HAVING statements at execution time. * * Required so that aliases are tracked properly, regardless of whether * where(), or_where(), having(), or_having are called prior to from(), * join() and dbprefix is added only if needed. * * @param string $qb_key 'qb_where' or 'qb_having' * @return string SQL statement */ protected function _compile_wh($qb_key) { if (count($this->$qb_key) > 0) { for ($i = 0, $c = count($this->$qb_key); $i < $c; $i++) { // Is this condition already compiled? if (is_string($this->{$qb_key}[$i])) { continue; } elseif ($this->{$qb_key}[$i]['escape'] === FALSE) { $this->{$qb_key}[$i] = $this->{$qb_key}[$i]['condition'].(isset($this->{$qb_key}[$i]['value']) ? ' '.$this->{$qb_key}[$i]['value'] : ''); continue; } // Split multiple conditions $conditions = preg_split( '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i', $this->{$qb_key}[$i]['condition'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci++) { if (($op = $this->_get_operator($conditions[$ci])) === FALSE OR ! preg_match('/^(\(?)(.*)('.preg_quote($op, '/').')\s*(.*(? '(test <= foo)', /* the whole thing */ // 1 => '(', /* optional */ // 2 => 'test', /* the field name */ // 3 => ' <= ', /* $op */ // 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */ // 5 => ')' /* optional */ // ); if ( ! empty($matches[4])) { $this->_is_literal($matches[4]) OR $matches[4] = $this->protect_identifiers(trim($matches[4])); $matches[4] = ' '.$matches[4]; } $conditions[$ci] = $matches[1].$this->protect_identifiers(trim($matches[2])) .' '.trim($matches[3]).$matches[4].$matches[5]; } $this->{$qb_key}[$i] = implode('', $conditions).(isset($this->{$qb_key}[$i]['value']) ? ' '.$this->{$qb_key}[$i]['value'] : ''); } return ($qb_key === 'qb_having' ? "\nHAVING " : "\nWHERE ") .implode("\n", $this->$qb_key); } return ''; } // -------------------------------------------------------------------- /** * Compile GROUP BY * * Escapes identifiers in GROUP BY statements at execution time. * * Required so that aliases are tracked properly, regardless of whether * group_by() is called prior to from(), join() and dbprefix is added * only if needed. * * @return string SQL statement */ protected function _compile_group_by() { if (count($this->qb_groupby) > 0) { for ($i = 0, $c = count($this->qb_groupby); $i < $c; $i++) { // Is it already compiled? if (is_string($this->qb_groupby[$i])) { continue; } $this->qb_groupby[$i] = ($this->qb_groupby[$i]['escape'] === FALSE OR $this->_is_literal($this->qb_groupby[$i]['field'])) ? $this->qb_groupby[$i]['field'] : $this->protect_identifiers($this->qb_groupby[$i]['field']); } return "\nGROUP BY ".implode(', ', $this->qb_groupby); } return ''; } // -------------------------------------------------------------------- /** * Compile ORDER BY * * Escapes identifiers in ORDER BY statements at execution time. * * Required so that aliases are tracked properly, regardless of whether * order_by() is called prior to from(), join() and dbprefix is added * only if needed. * * @return string SQL statement */ protected function _compile_order_by() { if (empty($this->qb_orderby)) { return ''; } for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++) { if (is_string($this->qb_orderby[$i])) { continue; } if ($this->qb_orderby[$i]['escape'] !== FALSE && ! $this->_is_literal($this->qb_orderby[$i]['field'])) { $this->qb_orderby[$i]['field'] = $this->protect_identifiers($this->qb_orderby[$i]['field']); } $this->qb_orderby[$i] = $this->qb_orderby[$i]['field'].$this->qb_orderby[$i]['direction']; } return "\nORDER BY ".implode(', ', $this->qb_orderby); } // -------------------------------------------------------------------- /** * Object to Array * * Takes an object as input and converts the class variables to array key/vals * * @param object * @return array */ protected 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 */ protected 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; } } } return $array; } // -------------------------------------------------------------------- /** * Start Cache * * Starts QB caching * * @return CI_DB_query_builder */ public function start_cache() { $this->qb_caching = TRUE; return $this; } // -------------------------------------------------------------------- /** * Stop Cache * * Stops QB caching * * @return CI_DB_query_builder */ public function stop_cache() { $this->qb_caching = FALSE; return $this; } // -------------------------------------------------------------------- /** * Flush Cache * * Empties the QB cache * * @return CI_DB_query_builder */ public function flush_cache() { $this->_reset_run(array( 'qb_cache_select' => array(), 'qb_cache_from' => array(), 'qb_cache_join' => array(), 'qb_cache_where' => array(), 'qb_cache_groupby' => array(), 'qb_cache_having' => array(), 'qb_cache_orderby' => array(), 'qb_cache_set' => array(), 'qb_cache_exists' => array(), 'qb_cache_no_escape' => array(), 'qb_cache_aliased_tables' => array() )); return $this; } // -------------------------------------------------------------------- /** * Merge Cache * * When called, this function merges any cached QB arrays with * locally called ones. * * @return void */ protected function _merge_cache() { if (count($this->qb_cache_exists) === 0) { return; } elseif (in_array('select', $this->qb_cache_exists, TRUE)) { $qb_no_escape = $this->qb_cache_no_escape; } foreach (array_unique($this->qb_cache_exists) as $val) // select, from, etc. { $qb_variable = 'qb_'.$val; $qb_cache_var = 'qb_cache_'.$val; $qb_new = $this->$qb_cache_var; for ($i = 0, $c = count($this->$qb_variable); $i < $c; $i++) { if ( ! in_array($this->{$qb_variable}[$i], $qb_new, TRUE)) { $qb_new[] = $this->{$qb_variable}[$i]; if ($val === 'select') { $qb_no_escape[] = $this->qb_no_escape[$i]; } } } $this->$qb_variable = $qb_new; if ($val === 'select') { $this->qb_no_escape = $qb_no_escape; } } } // -------------------------------------------------------------------- /** * Is literal * * Determines if a string represents a literal value or a field name * * @param string $str * @return bool */ protected function _is_literal($str) { $str = trim($str); if (empty($str) OR ctype_digit($str) OR (string) (float) $str === $str OR in_array(strtoupper($str), array('TRUE', 'FALSE'), TRUE)) { return TRUE; } static $_str; if (empty($_str)) { $_str = ($this->_escape_char !== '"') ? array('"', "'") : array("'"); } return in_array($str[0], $_str, TRUE); } // -------------------------------------------------------------------- /** * Reset Query Builder values. * * Publicly-visible method to reset the QB values. * * @return CI_DB_query_builder */ public function reset_query() { $this->_reset_select(); $this->_reset_write(); return $this; } // -------------------------------------------------------------------- /** * Resets the query builder values. Called by the get() function * * @param array An array of fields to reset * @return void */ protected function _reset_run($qb_reset_items) { foreach ($qb_reset_items as $item => $default_value) { $this->$item = $default_value; } } // -------------------------------------------------------------------- /** * Resets the query builder values. Called by the get() function * * @return void */ protected function _reset_select() { $this->_reset_run(array( 'qb_select' => array(), 'qb_from' => array(), 'qb_join' => array(), 'qb_where' => array(), 'qb_groupby' => array(), 'qb_having' => array(), 'qb_orderby' => array(), 'qb_aliased_tables' => array(), 'qb_no_escape' => array(), 'qb_distinct' => FALSE, 'qb_limit' => FALSE, 'qb_offset' => FALSE )); } // -------------------------------------------------------------------- /** * Resets the query builder "write" values. * * Called by the insert() update() insert_batch() update_batch() and delete() functions * * @return void */ protected function _reset_write() { $this->_reset_run(array( 'qb_set' => array(), 'qb_set_ub' => array(), 'qb_from' => array(), 'qb_join' => array(), 'qb_where' => array(), 'qb_orderby' => array(), 'qb_keys' => array(), 'qb_limit' => FALSE )); } } database/index.html000064400000000203152270514220010300 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/ibase/ibase_driver.php000064400000024421152270514220014223 0ustar00hostname.':'.$this->database, $this->username, $this->password, $this->char_set) : ibase_connect($this->hostname.':'.$this->database, $this->username, $this->password, $this->char_set); } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if (($service = ibase_service_attach($this->hostname, $this->username, $this->password))) { $this->data_cache['version'] = ibase_server_info($service, IBASE_SVC_SERVER_VERSION); // Don't keep the service open ibase_service_detach($service); return $this->data_cache['version']; } return FALSE; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return resource */ protected function _execute($sql) { return ibase_query(isset($this->_ibase_trans) ? $this->_ibase_trans : $this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { if (($trans_handle = ibase_trans($this->conn_id)) === FALSE) { return FALSE; } $this->_ibase_trans = $trans_handle; return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { if (ibase_commit($this->_ibase_trans)) { $this->_ibase_trans = NULL; return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { if (ibase_rollback($this->_ibase_trans)) { $this->_ibase_trans = NULL; return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return ibase_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @param string $generator_name * @param int $inc_by * @return int */ public function insert_id($generator_name, $inc_by = 0) { //If a generator hasn't been used before it will return 0 return ibase_gen_id('"'.$generator_name.'"', $inc_by); } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT TRIM("RDB$RELATION_NAME") AS TABLE_NAME FROM "RDB$RELATIONS" WHERE "RDB$RELATION_NAME" NOT LIKE \'RDB$%\' AND "RDB$RELATION_NAME" NOT LIKE \'MON$%\''; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $sql.' AND TRIM("RDB$RELATION_NAME") AS 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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT TRIM("RDB$FIELD_NAME") AS COLUMN_NAME FROM "RDB$RELATION_FIELDS" WHERE "RDB$RELATION_NAME" = '.$this->escape($table); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT "rfields"."RDB$FIELD_NAME" AS "name", CASE "fields"."RDB$FIELD_TYPE" WHEN 7 THEN \'SMALLINT\' WHEN 8 THEN \'INTEGER\' WHEN 9 THEN \'QUAD\' WHEN 10 THEN \'FLOAT\' WHEN 11 THEN \'DFLOAT\' WHEN 12 THEN \'DATE\' WHEN 13 THEN \'TIME\' WHEN 14 THEN \'CHAR\' WHEN 16 THEN \'INT64\' WHEN 27 THEN \'DOUBLE\' WHEN 35 THEN \'TIMESTAMP\' WHEN 37 THEN \'VARCHAR\' WHEN 40 THEN \'CSTRING\' WHEN 261 THEN \'BLOB\' ELSE NULL END AS "type", "fields"."RDB$FIELD_LENGTH" AS "max_length", "rfields"."RDB$DEFAULT_VALUE" AS "default" FROM "RDB$RELATION_FIELDS" "rfields" JOIN "RDB$FIELDS" "fields" ON "rfields"."RDB$FIELD_SOURCE" = "fields"."RDB$FIELD_NAME" WHERE "rfields"."RDB$RELATION_NAME" = '.$this->escape($table).' ORDER BY "rfields"."RDB$FIELD_POSITION"'; return (($query = $this->query($sql)) !== FALSE) ? $query->result_object() : FALSE; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { return array('code' => ibase_errcode(), 'message' => ibase_errmsg()); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { // Limit clause depends on if Interbase or Firebird if (stripos($this->version(), 'firebird') !== FALSE) { $select = 'FIRST '.$this->qb_limit .($this->qb_offset ? ' SKIP '.$this->qb_offset : ''); } else { $select = 'ROWS ' .($this->qb_offset ? $this->qb_offset.' TO '.($this->qb_limit + $this->qb_offset) : $this->qb_limit); } return preg_replace('`SELECT`i', 'SELECT '.$select, $sql, 1); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string|bool */ protected function _insert_batch($table, $keys, $values) { return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { ibase_close($this->conn_id); } } database/drivers/ibase/ibase_utility.php000064400000004562152270514220014437 0ustar00db->hostname, $this->db->username, $this->db->password)) { $res = ibase_backup($service, $this->db->database, $filename.'.fbk'); // Close the service connection ibase_service_detach($service); return $res; } return FALSE; } } database/drivers/ibase/ibase_forge.php000064400000014614152270514220014035 0ustar00 'INTEGER', 'INTEGER' => 'INT64', 'FLOAT' => 'DOUBLE PRECISION' ); /** * NULL value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_null = 'NULL'; // -------------------------------------------------------------------- /** * Create database * * @param string $db_name * @return bool */ public function create_database($db_name) { // Firebird databases are flat files, so a path is required // Hostname is needed for remote access empty($this->db->hostname) OR $db_name = $this->hostname.':'.$db_name; return parent::create_database('"'.$db_name.'"'); } // -------------------------------------------------------------------- /** * Drop database * * @param string $db_name (ignored) * @return bool */ public function drop_database($db_name) { if ( ! ibase_drop_db($this->conn_id)) { return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE; } elseif ( ! empty($this->db->data_cache['db_names'])) { $key = array_search(strtolower($this->db->database), array_map('strtolower', $this->db->data_cache['db_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['db_names'][$key]); } } return TRUE; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('DROP', 'ADD'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { return FALSE; } if (isset($field[$i]['type'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identififers($field[$i]['name']) .' TYPE '.$field[$i]['type'].$field[$i]['length']; } if ( ! empty($field[$i]['default'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' SET DEFAULT '.$field[$i]['default']; } if (isset($field[$i]['null'])) { $sqls[] = 'UPDATE "RDB$RELATION_FIELDS" SET "RDB$NULL_FLAG" = ' .($field[$i]['null'] === TRUE ? 'NULL' : '1') .' WHERE "RDB$FIELD_NAME" = '.$this->db->escape($field[$i]['name']) .' AND "RDB$RELATION_NAME" = '.$this->db->escape($table); } if ( ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } } return $sqls; } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['null'] .$field['unique'] .$field['default']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INT': $attributes['TYPE'] = 'INTEGER'; return; case 'BIGINT': $attributes['TYPE'] = 'INT64'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { // Not supported } } database/drivers/ibase/index.html000064400000000203152270514220013041 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/ibase/ibase_result.php000064400000010170152270514220014242 0ustar00result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); for ($i = 0, $num_fields = $this->num_fields(); $i < $num_fields; $i++) { $info = ibase_field_info($this->result_id, $i); $field_names[] = $info['name']; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $info = ibase_field_info($this->result_id, $i); $retval[$i] = new stdClass(); $retval[$i]->name = $info['name']; $retval[$i]->type = $info['type']; $retval[$i]->max_length = $info['length']; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { ibase_free_result($this->result_id); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return ibase_fetch_assoc($this->result_id, IBASE_FETCH_BLOBS); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { $row = ibase_fetch_object($this->result_id, IBASE_FETCH_BLOBS); if ($class_name === 'stdClass' OR ! $row) { return $row; } $class_name = new $class_name(); foreach ($row as $key => $value) { $class_name->$key = $value; } return $class_name; } } database/drivers/mysqli/mysqli_utility.php000064400000012773152270514220015130 0ustar00db->query('SHOW CREATE TABLE '.$this->db->escape_identifiers($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 '.$this->db->protect_identifiers($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 '.$this->db->protect_identifiers($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 = $query->result_id->fetch_field()) { // Most versions of MySQL store timestamp as a string $is_int[$i] = in_array($field->type, array(MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24, MYSQLI_TYPE_LONG), TRUE); // Create a string of field names $field_str .= $this->db->escape_identifiers($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 $val_str .= ($is_int[$i] === FALSE) ? $this->db->escape($v) : $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 '.$this->db->protect_identifiers($table).' ('.$field_str.') VALUES ('.$val_str.');'.$newline; } $output .= $newline.$newline; } // Do we need to include a statement to re-enable foreign key checks? if ($foreign_key_checks === FALSE) { $output .= 'SET foreign_key_checks = 1;'.$newline; } return $output; } } database/drivers/mysqli/mysqli_driver.php000064400000032406152270514220014713 0ustar00report_mode = MYSQLI_REPORT_OFF; } // Do we have a socket path? if ($this->hostname[0] === '/') { $hostname = NULL; $port = NULL; $socket = $this->hostname; } else { $hostname = ($persistent === TRUE) ? 'p:'.$this->hostname : $this->hostname; $port = empty($this->port) ? NULL : $this->port; $socket = NULL; } $client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0; $this->_mysqli = mysqli_init(); $this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); if (isset($this->stricton)) { if ($this->stricton) { $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'); } else { $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @@sql_mode, "STRICT_ALL_TABLES,", ""), ",STRICT_ALL_TABLES", ""), "STRICT_ALL_TABLES", ""), "STRICT_TRANS_TABLES,", ""), ",STRICT_TRANS_TABLES", ""), "STRICT_TRANS_TABLES", "")' ); } } if (is_array($this->encrypt)) { $ssl = array(); empty($this->encrypt['ssl_key']) OR $ssl['key'] = $this->encrypt['ssl_key']; empty($this->encrypt['ssl_cert']) OR $ssl['cert'] = $this->encrypt['ssl_cert']; empty($this->encrypt['ssl_ca']) OR $ssl['ca'] = $this->encrypt['ssl_ca']; empty($this->encrypt['ssl_capath']) OR $ssl['capath'] = $this->encrypt['ssl_capath']; empty($this->encrypt['ssl_cipher']) OR $ssl['cipher'] = $this->encrypt['ssl_cipher']; if (isset($this->encrypt['ssl_verify'])) { $client_flags |= MYSQLI_CLIENT_SSL; if ($this->encrypt['ssl_verify']) { defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->_mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, TRUE); } // Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT // to FALSE didn't do anything, so PHP 5.6.16 introduced yet another // constant ... // // https://secure.php.net/ChangeLog-5.php#5.6.16 // https://bugs.php.net/bug.php?id=68344 elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) { $client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT; } } if ( ! empty($ssl)) { $client_flags |= MYSQLI_CLIENT_SSL; $this->_mysqli->ssl_set( isset($ssl['key']) ? $ssl['key'] : NULL, isset($ssl['cert']) ? $ssl['cert'] : NULL, isset($ssl['ca']) ? $ssl['ca'] : NULL, isset($ssl['capath']) ? $ssl['capath'] : NULL, isset($ssl['cipher']) ? $ssl['cipher'] : NULL ); } } if ($this->_mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags)) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails if ( ($client_flags & MYSQLI_CLIENT_SSL) && version_compare($this->_mysqli->client_info, '5.7.3', '<=') && empty($this->_mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value) ) { $this->_mysqli->close(); $message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!'; log_message('error', $message); return ($this->db_debug) ? $this->display_error($message, '', TRUE) : FALSE; } return $this->_mysqli; } return FALSE; } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @return void */ public function reconnect() { if ($this->conn_id !== FALSE && $this->conn_id->ping() === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @param string $database * @return bool */ public function db_select($database = '') { if ($database === '') { $database = $this->database; } if ($this->conn_id->select_db($database)) { $this->database = $database; $this->data_cache = array(); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Set client character set * * @param string $charset * @return bool */ protected function _db_set_charset($charset) { return $this->conn_id->set_charset($charset); } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } return $this->data_cache['version'] = $this->conn_id->server_info; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return mixed */ protected function _execute($sql) { return $this->conn_id->query($this->_prep_query($sql)); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @param string $sql an SQL query * @return string */ protected function _prep_query($sql) { // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack // modifies the query so that it a proper number of affected rows is returned. if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { return trim($sql).' WHERE 1=1'; } return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { $this->conn_id->autocommit(FALSE); return is_php('5.5') ? $this->conn_id->begin_transaction() : $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { if ($this->conn_id->commit()) { $this->conn_id->autocommit(TRUE); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { if ($this->conn_id->rollback()) { $this->conn_id->autocommit(TRUE); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { return $this->conn_id->real_escape_string($str); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return $this->conn_id->affected_rows; } // -------------------------------------------------------------------- /** * Insert ID * * @return int */ public function insert_id() { return $this->conn_id->insert_id; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SHOW TABLES FROM '.$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length ); $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { if ( ! empty($this->_mysqli->connect_errno)) { return array( 'code' => $this->_mysqli->connect_errno, 'message' => $this->_mysqli->connect_error ); } return array('code' => $this->conn_id->errno, 'message' => $this->conn_id->error); } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * @return string */ protected function _from_tables() { if ( ! empty($this->qb_join) && count($this->qb_from) > 1) { return '('.implode(', ', $this->qb_from).')'; } return implode(', ', $this->qb_from); } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { $this->conn_id->close(); } } database/drivers/mysqli/index.html000064400000000203152270514220013274 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/mysqli/mysqli_forge.php000064400000014157152270514220014525 0ustar00db->char_set) && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) { $sql .= ' DEFAULT CHARACTER SET = '.$this->db->char_set; } if ( ! empty($this->db->dbcollat) && ! strpos($sql, 'COLLATE')) { $sql .= ' COLLATE = '.$this->db->dbcollat; } return $sql; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP') { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $field[$i] = ($alter_type === 'ADD') ? "\n\tADD ".$field[$i]['_literal'] : "\n\tMODIFY ".$field[$i]['_literal']; } else { if ($alter_type === 'ADD') { $field[$i]['_literal'] = "\n\tADD "; } else { $field[$i]['_literal'] = empty($field[$i]['new_name']) ? "\n\tMODIFY " : "\n\tCHANGE "; } $field[$i] = $field[$i]['_literal'].$this->_process_column($field[$i]); } } return array($sql.implode(',', $field)); } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { $extra_clause = isset($field['after']) ? ' AFTER '.$this->db->escape_identifiers($field['after']) : ''; if (empty($extra_clause) && isset($field['first']) && $field['first'] === TRUE) { $extra_clause = ' FIRST'; } return $this->db->escape_identifiers($field['name']) .(empty($field['new_name']) ? '' : ' '.$this->db->escape_identifiers($field['new_name'])) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['null'] .$field['default'] .$field['auto_increment'] .$field['unique'] .(empty($field['comment']) ? '' : ' COMMENT '.$field['comment']) .$extra_clause; } // -------------------------------------------------------------------- /** * Process indexes * * @param string $table (ignored) * @return string */ protected function _process_indexes($table) { $sql = ''; for ($i = 0, $c = count($this->keys); $i < $c; $i++) { if (is_array($this->keys[$i])) { for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++) { if ( ! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } elseif ( ! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; } is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]); $sql .= ",\n\tKEY ".$this->db->escape_identifiers(implode('_', $this->keys[$i])) .' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).')'; } $this->keys = array(); return $sql; } } database/drivers/mysqli/mysqli_result.php000064400000014265152270514220014741 0ustar00num_rows) ? $this->num_rows : $this->num_rows = $this->result_id->num_rows; } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return $this->result_id->field_count; } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); $this->result_id->field_seek(0); while ($field = $this->result_id->fetch_field()) { $field_names[] = $field->name; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { $retval = array(); $field_data = $this->result_id->fetch_fields(); for ($i = 0, $c = count($field_data); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $field_data[$i]->name; $retval[$i]->type = static::_get_field_type($field_data[$i]->type); $retval[$i]->max_length = $field_data[$i]->max_length; $retval[$i]->primary_key = (int) ($field_data[$i]->flags & MYSQLI_PRI_KEY_FLAG); $retval[$i]->default = $field_data[$i]->def; } return $retval; } // -------------------------------------------------------------------- /** * Get field type * * Extracts field type info from the bitflags returned by * mysqli_result::fetch_fields() * * @used-by CI_DB_mysqli_result::field_data() * @param int $type * @return string */ private static function _get_field_type($type) { static $map; isset($map) OR $map = array( MYSQLI_TYPE_DECIMAL => 'decimal', MYSQLI_TYPE_BIT => 'bit', MYSQLI_TYPE_TINY => 'tinyint', MYSQLI_TYPE_SHORT => 'smallint', MYSQLI_TYPE_INT24 => 'mediumint', MYSQLI_TYPE_LONG => 'int', MYSQLI_TYPE_LONGLONG => 'bigint', MYSQLI_TYPE_FLOAT => 'float', MYSQLI_TYPE_DOUBLE => 'double', MYSQLI_TYPE_TIMESTAMP => 'timestamp', MYSQLI_TYPE_DATE => 'date', MYSQLI_TYPE_TIME => 'time', MYSQLI_TYPE_DATETIME => 'datetime', MYSQLI_TYPE_YEAR => 'year', MYSQLI_TYPE_NEWDATE => 'date', MYSQLI_TYPE_INTERVAL => 'interval', MYSQLI_TYPE_ENUM => 'enum', MYSQLI_TYPE_SET => 'set', MYSQLI_TYPE_TINY_BLOB => 'tinyblob', MYSQLI_TYPE_MEDIUM_BLOB => 'mediumblob', MYSQLI_TYPE_BLOB => 'blob', MYSQLI_TYPE_LONG_BLOB => 'longblob', MYSQLI_TYPE_STRING => 'char', MYSQLI_TYPE_VAR_STRING => 'varchar', MYSQLI_TYPE_GEOMETRY => 'geometry' ); return isset($map[$type]) ? $map[$type] : $type; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if (is_object($this->result_id)) { $this->result_id->free(); $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. * * @param int $n * @return bool */ public function data_seek($n = 0) { return $this->result_id->data_seek($n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return $this->result_id->fetch_assoc(); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return $this->result_id->fetch_object($class_name); } } database/drivers/sqlsrv/sqlsrv_driver.php000064400000034071152270514220014743 0ustar00scrollable === NULL) { $this->scrollable = defined('SQLSRV_CURSOR_CLIENT_BUFFERED') ? SQLSRV_CURSOR_CLIENT_BUFFERED : FALSE; } } // -------------------------------------------------------------------- /** * Database connection * * @param bool $pooling * @return resource */ public function db_connect($pooling = FALSE) { $charset = in_array(strtolower($this->char_set), array('utf-8', 'utf8'), TRUE) ? 'UTF-8' : SQLSRV_ENC_CHAR; $connection = array( 'UID' => empty($this->username) ? '' : $this->username, 'PWD' => empty($this->password) ? '' : $this->password, 'Database' => $this->database, 'ConnectionPooling' => ($pooling === TRUE) ? 1 : 0, 'CharacterSet' => $charset, 'Encrypt' => ($this->encrypt === TRUE) ? 1 : 0, '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']); } if (FALSE !== ($this->conn_id = sqlsrv_connect($this->hostname, $connection))) { // Determine how identifiers are escaped $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi'); $query = $query->row_array(); $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi']; $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']'); } return $this->conn_id; } // -------------------------------------------------------------------- /** * Select the database * * @param string $database * @return bool */ public function db_select($database = '') { if ($database === '') { $database = $this->database; } if ($this->_execute('USE '.$this->escape_identifiers($database))) { $this->database = $database; $this->data_cache = array(); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return resource */ protected function _execute($sql) { return ($this->scrollable === FALSE OR $this->is_write_type($sql)) ? sqlsrv_query($this->conn_id, $sql) : sqlsrv_query($this->conn_id, $sql, NULL, array('Scrollable' => $this->scrollable)); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return sqlsrv_begin_transaction($this->conn_id); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { return sqlsrv_commit($this->conn_id); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { return sqlsrv_rollback($this->conn_id); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return sqlsrv_rows_affected($this->result_id); } // -------------------------------------------------------------------- /** * Insert ID * * Returns the last id created in the Identity column. * * @return string */ public function insert_id() { return $this->query('SELECT SCOPE_IDENTITY() AS insert_id')->row()->insert_id; } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if ( ! $this->conn_id OR ($info = sqlsrv_server_info($this->conn_id)) === FALSE) { return FALSE; } return $this->data_cache['version'] = $info['SQLServerVersion']; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool * @return string $prefix_limit */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_escape_like_str, $this->_escape_like_chr); } return $sql.' ORDER BY '.$this->escape_identifiers('name'); } // -------------------------------------------------------------------- /** * List column query * * Generates a platform-specific query string so that the column names can be fetched * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION; $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { $error = array('code' => '00000', 'message' => ''); $sqlsrv_errors = sqlsrv_errors(SQLSRV_ERR_ERRORS); if ( ! is_array($sqlsrv_errors)) { return $error; } $sqlsrv_error = array_shift($sqlsrv_errors); if (isset($sqlsrv_error['SQLSTATE'])) { $error['code'] = isset($sqlsrv_error['code']) ? $sqlsrv_error['SQLSTATE'].'/'.$sqlsrv_error['code'] : $sqlsrv_error['SQLSTATE']; } elseif (isset($sqlsrv_error['code'])) { $error['code'] = $sqlsrv_error['code']; } if (isset($sqlsrv_error['message'])) { $error['message'] = $sqlsrv_error['message']; } return $error; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { if ($this->qb_limit) { return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete'; } return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { // As of SQL Server 2012 (11.0.*) OFFSET is supported if (version_compare($this->version(), '11', '>=')) { // SQL Server OFFSET-FETCH can be used only with the ORDER BY clause empty($this->qb_orderby) && $sql .= ' ORDER BY 1'; return $sql.' OFFSET '.(int) $this->qb_offset.' ROWS FETCH NEXT '.$this->qb_limit.' ROWS ONLY'; } $limit = $this->qb_offset + $this->qb_limit; // An ORDER BY clause is required for ROW_NUMBER() to work if ($this->qb_offset && ! empty($this->qb_orderby)) { $orderby = $this->_compile_order_by(); // We have to strip the ORDER BY clause $sql = trim(substr($sql, 0, strrpos($sql, $orderby))); // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } else { // Use only field names and their aliases, everything else is out of our scope. $select = array(); $field_regexp = ($this->_quoted_identifier) ? '("[^\"]+")' : '(\[[^\]]+\])'; for ($i = 0, $c = count($this->qb_select); $i < $c; $i++) { $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m) ? $m[1] : $this->qb_select[$i]; } $select = implode(', ', $select); } return 'SELECT '.$select." FROM (\n\n" .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql) ."\n\n) ".$this->escape_identifiers('CI_subquery') ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit; } return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string|bool */ protected function _insert_batch($table, $keys, $values) { // Multiple-value inserts are only supported as of SQL Server 2008 if (version_compare($this->version(), '10', '>=')) { return parent::_insert_batch($table, $keys, $values); } return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { sqlsrv_close($this->conn_id); } } database/drivers/sqlsrv/sqlsrv_utility.php000064400000005006152270514220015147 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/sqlsrv/sqlsrv_result.php000064400000011537152270514220014770 0ustar00scrollable = $driver_object->scrollable; } // -------------------------------------------------------------------- /** * Number of rows in the result set * * @return int */ public function num_rows() { // sqlsrv_num_rows() doesn't work with the FORWARD and DYNAMIC cursors (FALSE is the same as FORWARD) if ( ! in_array($this->scrollable, array(FALSE, SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_DYNAMIC), TRUE)) { return parent::num_rows(); } return is_int($this->num_rows) ? $this->num_rows : $this->num_rows = sqlsrv_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return @sqlsrv_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public 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 * * @return array */ public function field_data() { $retval = array(); foreach (sqlsrv_field_metadata($this->result_id) as $i => $field) { $retval[$i] = new stdClass(); $retval[$i]->name = $field['Name']; $retval[$i]->type = $field['Type']; $retval[$i]->max_length = $field['Size']; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if (is_resource($this->result_id)) { sqlsrv_free_stmt($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return sqlsrv_fetch_array($this->result_id, SQLSRV_FETCH_ASSOC); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return sqlsrv_fetch_object($this->result_id, $class_name); } } database/drivers/sqlsrv/sqlsrv_forge.php000064400000010453152270514220014550 0ustar00 'SMALLINT', 'SMALLINT' => 'INT', 'INT' => 'BIGINT', 'REAL' => 'FLOAT' ); // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ALTER COLUMN '; $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql.$this->_process_column($field[$i]); } return $sqls; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) { unset($attributes['CONSTRAINT']); } switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INTEGER': $attributes['TYPE'] = 'INT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' IDENTITY(1,1)'; } } } database/drivers/sqlsrv/index.html000064400000000203152270514220013310 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/sqlite/sqlite_forge.php000064400000012636152270514220014473 0ustar00db->database) OR ! @unlink($this->db->database)) { return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE; } elseif ( ! empty($this->db->data_cache['db_names'])) { $key = array_search(strtolower($this->db->database), array_map('strtolower', $this->db->data_cache['db_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['db_names'][$key]); } } return TRUE; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @todo implement drop_column(), modify_column() * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP' OR $alter_type === 'CHANGE') { // drop_column(): // BEGIN TRANSACTION; // CREATE TEMPORARY TABLE t1_backup(a,b); // INSERT INTO t1_backup SELECT a,b FROM t1; // DROP TABLE t1; // CREATE TABLE t1(a,b); // INSERT INTO t1 SELECT a,b FROM t1_backup; // DROP TABLE t1_backup; // COMMIT; return FALSE; } return parent::_alter_table($alter_type, $table, $field); } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'] .$field['auto_increment'] .$field['null'] .$field['unique'] .$field['default']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'ENUM': case 'SET': $attributes['TYPE'] = 'TEXT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['type'] = 'INTEGER PRIMARY KEY'; $field['default'] = ''; $field['null'] = ''; $field['unique'] = ''; $field['auto_increment'] = ' AUTOINCREMENT'; $this->primary_keys = array(); } } } database/drivers/sqlite/sqlite_driver.php000064400000017606152270514220014666 0ustar00database, 0666, $error) : sqlite_open($this->database, 0666, $error); isset($error) && log_message('error', $error); return $conn_id; } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { return isset($this->data_cache['version']) ? $this->data_cache['version'] : $this->data_cache['version'] = sqlite_libversion(); } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return resource */ protected function _execute($sql) { return $this->is_write_type($sql) ? sqlite_exec($this->conn_id, $sql) : sqlite_query($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return $this->simple_query('BEGIN TRANSACTION'); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { return $this->simple_query('COMMIT'); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { return $this->simple_query('ROLLBACK'); } // -------------------------------------------------------------------- /** * Platform-dependant string escape * * @param string * @return string */ protected function _escape_str($str) { return sqlite_escape_string($str); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return sqlite_changes($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @return int */ public function insert_id() { return sqlite_last_insert_rowid($this->conn_id); } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = "SELECT name FROM sqlite_master WHERE type='table'"; if ($prefix_limit !== FALSE && $this->dbprefix != '') { return $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 * * @param string $table * @return bool */ protected function _list_columns($table = '') { // Not supported return FALSE; } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; } $query = $query->result_array(); if (empty($query)) { return FALSE; } $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]['name']; $retval[$i]->type = $query[$i]['type']; $retval[$i]->max_length = NULL; $retval[$i]->default = $query[$i]['dflt_value']; $retval[$i]->primary_key = isset($query[$i]['pk']) ? (int) $query[$i]['pk'] : 0; } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occured. * * @return array */ public function error() { $error = array('code' => sqlite_last_error($this->conn_id)); $error['message'] = sqlite_error_string($error['code']); return $error; } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string */ protected function _replace($table, $keys, $values) { return 'INSERT OR '.parent::_replace($table, $keys, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this function maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { sqlite_close($this->conn_id); } } database/drivers/sqlite/sqlite_utility.php000064400000004261152270514220015067 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/sqlite/sqlite_result.php000064400000010413152270514220014676 0ustar00num_rows) ? $this->num_rows : $this->num_rows = @sqlite_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return @sqlite_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[$i] = sqlite_field_name($this->result_id, $i); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = sqlite_field_name($this->result_id, $i); $retval[$i]->type = NULL; $retval[$i]->max_length = NULL; } return $retval; } // -------------------------------------------------------------------- /** * 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. * * @param int $n * @return bool */ public function data_seek($n = 0) { return sqlite_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return sqlite_fetch_array($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return sqlite_fetch_object($this->result_id, $class_name); } } database/drivers/sqlite/index.html000064400000000203152270514220013257 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/sqlite3/sqlite3_forge.php000064400000013626152270514220014641 0ustar00db->version(), '3.3', '<')) { $this->_create_table_if = FALSE; $this->_drop_table_if = FALSE; } } // -------------------------------------------------------------------- /** * Create database * * @param string $db_name * @return bool */ public function create_database($db_name) { // In SQLite, a database is created when you connect to the database. // We'll return TRUE so that an error isn't generated return TRUE; } // -------------------------------------------------------------------- /** * Drop database * * @param string $db_name (ignored) * @return bool */ public function drop_database($db_name) { // In SQLite, a database is dropped when we delete a file if (file_exists($this->db->database)) { // We need to close the pseudo-connection first $this->db->close(); if ( ! @unlink($this->db->database)) { return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE; } elseif ( ! empty($this->db->data_cache['db_names'])) { $key = array_search(strtolower($this->db->database), array_map('strtolower', $this->db->data_cache['db_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['db_names'][$key]); } } return TRUE; } return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @todo implement drop_column(), modify_column() * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP' OR $alter_type === 'CHANGE') { // drop_column(): // BEGIN TRANSACTION; // CREATE TEMPORARY TABLE t1_backup(a,b); // INSERT INTO t1_backup SELECT a,b FROM t1; // DROP TABLE t1; // CREATE TABLE t1(a,b); // INSERT INTO t1 SELECT a,b FROM t1_backup; // DROP TABLE t1_backup; // COMMIT; return FALSE; } return parent::_alter_table($alter_type, $table, $field); } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'] .$field['auto_increment'] .$field['null'] .$field['unique'] .$field['default']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'ENUM': case 'SET': $attributes['TYPE'] = 'TEXT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['type'] = 'INTEGER PRIMARY KEY'; $field['default'] = ''; $field['null'] = ''; $field['unique'] = ''; $field['auto_increment'] = ' AUTOINCREMENT'; $this->primary_keys = array(); } } } database/drivers/sqlite3/sqlite3_utility.php000064400000004246152270514220015240 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/sqlite3/sqlite3_driver.php000064400000020312152270514220015020 0ustar00password) ? new SQLite3($this->database) : new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password); } catch (Exception $e) { return FALSE; } } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } $version = SQLite3::version(); return $this->data_cache['version'] = $version['versionString']; } // -------------------------------------------------------------------- /** * Execute the query * * @todo Implement use of SQLite3::querySingle(), if needed * @param string $sql * @return mixed SQLite3Result object or bool */ protected function _execute($sql) { return $this->is_write_type($sql) ? $this->conn_id->exec($sql) : $this->conn_id->query($sql); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return $this->conn_id->exec('BEGIN TRANSACTION'); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { return $this->conn_id->exec('END TRANSACTION'); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { return $this->conn_id->exec('ROLLBACK'); } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { return $this->conn_id->escapeString($str); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return $this->conn_id->changes(); } // -------------------------------------------------------------------- /** * Insert ID * * @return int */ public function insert_id() { return $this->conn_id->lastInsertRowID(); } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\'' .(($prefix_limit !== FALSE && $this->dbprefix != '') ? ' AND "NAME" LIKE \''.$this->escape_like_str($this->dbprefix).'%\' '.sprintf($this->_like_escape_str, $this->_like_escape_chr) : ''); } // -------------------------------------------------------------------- /** * Fetch Field Names * * @param string $table Table name * @return array */ public function list_fields($table) { if (($result = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; } $fields = array(); foreach ($result->result_array() as $row) { $fields[] = $row['name']; } return $fields; } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; } $query = $query->result_array(); if (empty($query)) { return FALSE; } $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]['name']; $retval[$i]->type = $query[$i]['type']; $retval[$i]->max_length = NULL; $retval[$i]->default = $query[$i]['dflt_value']; $retval[$i]->primary_key = isset($query[$i]['pk']) ? (int) $query[$i]['pk'] : 0; } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { return array('code' => $this->conn_id->lastErrorCode(), 'message' => $this->conn_id->lastErrorMsg()); } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string */ protected function _replace($table, $keys, $values) { return 'INSERT OR '.parent::_replace($table, $keys, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { $this->conn_id->close(); } } database/drivers/sqlite3/index.html000064400000000203152270514220013342 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/sqlite3/sqlite3_result.php000064400000011566152270514220015056 0ustar00result_id->numColumns(); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[] = $this->result_id->columnName($i); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { static $data_types = array( SQLITE3_INTEGER => 'integer', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', SQLITE3_BLOB => 'blob', SQLITE3_NULL => 'null' ); $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $this->result_id->columnName($i); $type = $this->result_id->columnType($i); $retval[$i]->type = isset($data_types[$type]) ? $data_types[$type] : $type; $retval[$i]->max_length = NULL; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if (is_object($this->result_id)) { $this->result_id->finalize(); $this->result_id = NULL; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return $this->result_id->fetchArray(SQLITE3_ASSOC); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { // No native support for fetching rows as objects if (($row = $this->result_id->fetchArray(SQLITE3_ASSOC)) === FALSE) { return FALSE; } elseif ($class_name === 'stdClass') { return (object) $row; } $class_name = new $class_name(); foreach (array_keys($row) as $key) { $class_name->$key = $row[$key]; } return $class_name; } // -------------------------------------------------------------------- /** * 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. * * @param int $n (ignored) * @return array */ public function data_seek($n = 0) { // Only resetting to the start of the result set is supported return ($n > 0) ? FALSE : $this->result_id->reset(); } } database/drivers/mssql/mssql_result.php000064400000011501152270514220014371 0ustar00num_rows) ? $this->num_rows : $this->num_rows = mssql_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return mssql_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); mssql_field_seek($this->result_id, 0); 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 * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field = mssql_fetch_field($this->result_id, $i); $retval[$i] = new stdClass(); $retval[$i]->name = $field->name; $retval[$i]->type = $field->type; $retval[$i]->max_length = $field->max_length; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public 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. * * @param int $n * @return bool */ public function data_seek($n = 0) { return mssql_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return mssql_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { $row = mssql_fetch_object($this->result_id); if ($class_name === 'stdClass' OR ! $row) { return $row; } $class_name = new $class_name(); foreach ($row as $key => $value) { $class_name->$key = $value; } return $class_name; } } database/drivers/mssql/mssql_driver.php000064400000032665152270514220014364 0ustar00port)) { $this->hostname .= (DIRECTORY_SEPARATOR === '\\' ? ',' : ':').$this->port; } } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @param bool $persistent * @return resource */ public function db_connect($persistent = FALSE) { $this->conn_id = ($persistent) ? mssql_pconnect($this->hostname, $this->username, $this->password) : mssql_connect($this->hostname, $this->username, $this->password); if ( ! $this->conn_id) { return FALSE; } // ---------------------------------------------------------------- // Select the DB... assuming a database name is specified in the config file if ($this->database !== '' && ! $this->db_select()) { log_message('error', 'Unable to select database: '.$this->database); return ($this->db_debug === TRUE) ? $this->display_error('db_unable_to_select', $this->database) : FALSE; } // Determine how identifiers are escaped $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi'); $query = $query->row_array(); $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi']; $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']'); return $this->conn_id; } // -------------------------------------------------------------------- /** * Select the database * * @param string $database * @return bool */ public function db_select($database = '') { if ($database === '') { $database = $this->database; } // Note: Escaping is required in the event that the DB name // contains reserved characters. if (mssql_select_db('['.$database.']', $this->conn_id)) { $this->database = $database; $this->data_cache = array(); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return mixed resource if rows are returned, bool otherwise */ protected function _execute($sql) { return mssql_query($sql, $this->conn_id); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return $this->simple_query('BEGIN TRAN'); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { return $this->simple_query('COMMIT TRAN'); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { return $this->simple_query('ROLLBACK TRAN'); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return mssql_rows_affected($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * Returns the last id created in the Identity column. * * @return string */ public function insert_id() { $query = version_compare($this->version(), '8', '>=') ? 'SELECT SCOPE_IDENTITY() AS last_id' : 'SELECT @@IDENTITY AS last_id'; $query = $this->query($query); $query = $query->row(); return $query->last_id; } // -------------------------------------------------------------------- /** * Set client character set * * @param string $charset * @return bool */ protected function _db_set_charset($charset) { return (ini_set('mssql.charset', $charset) !== FALSE); } // -------------------------------------------------------------------- /** * Version number query string * * @return string */ protected function _version() { return "SELECT SERVERPROPERTY('ProductVersion') AS ver"; } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql.' ORDER BY '.$this->escape_identifiers('name'); } // -------------------------------------------------------------------- /** * List column query * * Generates a platform-specific query string so that the column names can be fetched * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION; $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { // We need this because the error info is discarded by the // server the first time you request it, and query() already // calls error() once for logging purposes when a query fails. static $error = array('code' => 0, 'message' => NULL); $message = mssql_get_last_message(); if ( ! empty($message)) { $error['code'] = $this->query('SELECT @@ERROR AS code')->row()->code; $error['message'] = $message; } return $error; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { if ($this->qb_limit) { return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete'; } return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { $limit = $this->qb_offset + $this->qb_limit; // As of SQL Server 2005 (9.0.*) ROW_NUMBER() is supported, // however an ORDER BY clause is required for it to work if (version_compare($this->version(), '9', '>=') && $this->qb_offset && ! empty($this->qb_orderby)) { $orderby = $this->_compile_order_by(); // We have to strip the ORDER BY clause $sql = trim(substr($sql, 0, strrpos($sql, $orderby))); // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } else { // Use only field names and their aliases, everything else is out of our scope. $select = array(); $field_regexp = ($this->_quoted_identifier) ? '("[^\"]+")' : '(\[[^\]]+\])'; for ($i = 0, $c = count($this->qb_select); $i < $c; $i++) { $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m) ? $m[1] : $this->qb_select[$i]; } $select = implode(', ', $select); } return 'SELECT '.$select." FROM (\n\n" .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql) ."\n\n) ".$this->escape_identifiers('CI_subquery') ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit; } return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string|bool */ protected function _insert_batch($table, $keys, $values) { // Multiple-value inserts are only supported as of SQL Server 2008 if (version_compare($this->version(), '10', '>=')) { return parent::_insert_batch($table, $keys, $values); } return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { mssql_close($this->conn_id); } } database/drivers/mssql/mssql_utility.php000064400000004753152270514220014571 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/mssql/index.html000064400000000203152270514220013115 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/mssql/mssql_forge.php000064400000010532152270514220014160 0ustar00 'SMALLINT', 'SMALLINT' => 'INT', 'INT' => 'BIGINT', 'REAL' => 'FLOAT' ); // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ALTER COLUMN '; $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql.$this->_process_column($field[$i]); } return $sqls; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) { unset($attributes['CONSTRAINT']); } switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INTEGER': $attributes['TYPE'] = 'INT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' IDENTITY(1,1)'; } } } database/drivers/odbc/odbc_utility.php000064400000004322152270514220014101 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/odbc/odbc_driver.php000064400000023214152270514220013672 0ustar00dsn)) { $this->dsn = $this->hostname; } } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @param bool $persistent * @return resource */ public function db_connect($persistent = FALSE) { return ($persistent === TRUE) ? odbc_pconnect($this->dsn, $this->username, $this->password) : odbc_connect($this->dsn, $this->username, $this->password); } // -------------------------------------------------------------------- /** * Compile Bindings * * @param string $sql SQL statement * @param array $binds An array of values to bind * @return string */ public function compile_binds($sql, $binds) { if (empty($binds) OR empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE) { return $sql; } elseif ( ! is_array($binds)) { $binds = array($binds); $bind_count = 1; } else { // Make sure we're using numeric keys $binds = array_values($binds); $bind_count = count($binds); } // We'll need the marker length later $ml = strlen($this->bind_marker); // Make sure not to replace a chunk inside a string that happens to match the bind marker if ($c = preg_match_all("/'[^']*'|\"[^\"]*\"/i", $sql, $matches)) { $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', str_replace($matches[0], str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]), $sql, $c), $matches, PREG_OFFSET_CAPTURE); // Bind values' count must match the count of markers in the query if ($bind_count !== $c) { return $sql; } } elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count) { return $sql; } if ($this->bind_marker !== '?') { do { $c--; $sql = substr_replace($sql, '?', $matches[0][$c][1], $ml); } while ($c !== 0); } if (FALSE !== ($this->odbc_result = odbc_prepare($this->conn_id, $sql))) { $this->binds = array_values($binds); } return $sql; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return resource */ protected function _execute($sql) { if ( ! isset($this->odbc_result)) { return odbc_exec($this->conn_id, $sql); } elseif ($this->odbc_result === FALSE) { return FALSE; } if (TRUE === ($success = odbc_execute($this->odbc_result, $this->binds))) { // For queries that return result sets, return the result_id resource on success $this->is_write_type($sql) OR $success = $this->odbc_result; } $this->odbc_result = NULL; $this->binds = array(); return $success; } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return odbc_autocommit($this->conn_id, FALSE); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { if (odbc_commit($this->conn_id)) { odbc_autocommit($this->conn_id, TRUE); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { if (odbc_rollback($this->conn_id)) { odbc_autocommit($this->conn_id, TRUE); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Determines if a query is a "write" type. * * @param string An SQL query string * @return bool */ public function is_write_type($sql) { if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql)) { return FALSE; } return parent::is_write_type($sql); } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { $this->display_error('db_unsupported_feature'); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return odbc_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Insert ID * * @return bool */ public function insert_id() { return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '".$this->schema."'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected 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 * * @param string $table * @return string */ protected function _field_data($table) { return 'SELECT TOP 1 FROM '.$table; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { return array('code' => odbc_error($this->conn_id), 'message' => odbc_errormsg($this->conn_id)); } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { odbc_close($this->conn_id); } } database/drivers/odbc/odbc_result.php000064400000014442152270514220013720 0ustar00num_rows)) { return $this->num_rows; } elseif (($this->num_rows = odbc_num_rows($this->result_id)) !== -1) { return $this->num_rows; } // Work-around for ODBC subdrivers that don't support num_rows() if (count($this->result_array) > 0) { return $this->num_rows = count($this->result_array); } elseif (count($this->result_object) > 0) { return $this->num_rows = count($this->result_object); } return $this->num_rows = count($this->result_array()); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return odbc_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); $num_fields = $this->num_fields(); if ($num_fields > 0) { for ($i = 1; $i <= $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 * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $odbc_index = 1, $c = $this->num_fields(); $i < $c; $i++, $odbc_index++) { $retval[$i] = new stdClass(); $retval[$i]->name = odbc_field_name($this->result_id, $odbc_index); $retval[$i]->type = odbc_field_type($this->result_id, $odbc_index); $retval[$i]->max_length = odbc_field_len($this->result_id, $odbc_index); $retval[$i]->primary_key = 0; $retval[$i]->default = ''; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if (is_resource($this->result_id)) { odbc_free_result($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return odbc_fetch_array($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { $row = odbc_fetch_object($this->result_id); if ($class_name === 'stdClass' OR ! $row) { return $row; } $class_name = new $class_name(); foreach ($row as $key => $value) { $class_name->$key = $value; } return $class_name; } } // -------------------------------------------------------------------- if ( ! function_exists('odbc_fetch_array')) { /** * ODBC Fetch array * * Emulates the native odbc_fetch_array() function when * it is not available (odbc_fetch_array() requires unixODBC) * * @param resource &$result * @param int $rownumber * @return array */ function odbc_fetch_array(&$result, $rownumber = 1) { $rs = array(); if ( ! odbc_fetch_into($result, $rs, $rownumber)) { return FALSE; } $rs_assoc = array(); foreach ($rs as $k => $v) { $field_name = odbc_field_name($result, $k+1); $rs_assoc[$field_name] = $v; } return $rs_assoc; } } // -------------------------------------------------------------------- if ( ! function_exists('odbc_fetch_object')) { /** * ODBC Fetch object * * Emulates the native odbc_fetch_object() function when * it is not available. * * @param resource &$result * @param int $rownumber * @return object */ function odbc_fetch_object(&$result, $rownumber = 1) { $rs = array(); if ( ! odbc_fetch_into($result, $rs, $rownumber)) { return FALSE; } $rs_object = new stdClass(); foreach ($rs as $k => $v) { $field_name = odbc_field_name($result, $k+1); $rs_object->$field_name = $v; } return $rs_object; } } database/drivers/odbc/index.html000064400000000203152270514220012665 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/odbc/odbc_forge.php000064400000005102152270514220013475 0ustar00 '/^\(DESCRIPTION=(\(.+\)){2,}\)$/', // TNS // Easy Connect string (Oracle 10g+) 'ec' => '/^(\/\/)?[a-z0-9.:_-]+(:[1-9][0-9]{0,4})?(\/[a-z0-9$_]+)?(:[^\/])?(\/[a-z0-9$_]+)?$/i', 'in' => '/^[a-z0-9$_]+$/i' // Instance name (defined in tnsnames.ora) ); /* Space characters don't have any effect when actually * connecting, but can be a hassle while validating the DSN. */ $this->dsn = str_replace(array("\n", "\r", "\t", ' '), '', $this->dsn); if ($this->dsn !== '') { foreach ($valid_dsns as $regexp) { if (preg_match($regexp, $this->dsn)) { return; } } } // Legacy support for TNS in the hostname configuration field $this->hostname = str_replace(array("\n", "\r", "\t", ' '), '', $this->hostname); if (preg_match($valid_dsns['tns'], $this->hostname)) { $this->dsn = $this->hostname; return; } elseif ($this->hostname !== '' && strpos($this->hostname, '/') === FALSE && strpos($this->hostname, ':') === FALSE && (( ! empty($this->port) && ctype_digit($this->port)) OR $this->database !== '')) { /* If the hostname field isn't empty, doesn't contain * ':' and/or '/' and if port and/or database aren't * empty, then the hostname field is most likely indeed * just a hostname. Therefore we'll try and build an * Easy Connect string from these 3 settings, assuming * that the database field is a service name. */ $this->dsn = $this->hostname .(( ! empty($this->port) && ctype_digit($this->port)) ? ':'.$this->port : '') .($this->database !== '' ? '/'.ltrim($this->database, '/') : ''); if (preg_match($valid_dsns['ec'], $this->dsn)) { return; } } /* At this point, we can only try and validate the hostname and * database fields separately as DSNs. */ if (preg_match($valid_dsns['ec'], $this->hostname) OR preg_match($valid_dsns['in'], $this->hostname)) { $this->dsn = $this->hostname; return; } $this->database = str_replace(array("\n", "\r", "\t", ' '), '', $this->database); foreach ($valid_dsns as $regexp) { if (preg_match($regexp, $this->database)) { return; } } /* Well - OK, an empty string should work as well. * PHP will try to use environment variables to * determine which Oracle instance to connect to. */ $this->dsn = ''; } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @param bool $persistent * @return resource */ public function db_connect($persistent = FALSE) { $func = ($persistent === TRUE) ? 'oci_pconnect' : 'oci_connect'; return empty($this->char_set) ? $func($this->username, $this->password, $this->dsn) : $func($this->username, $this->password, $this->dsn, $this->char_set); } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if ( ! $this->conn_id OR ($version_string = oci_server_version($this->conn_id)) === FALSE) { return FALSE; } elseif (preg_match('#Release\s(\d+(?:\.\d+)+)#', $version_string, $match)) { return $this->data_cache['version'] = $match[1]; } return FALSE; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql 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 oci_parse(). */ if ($this->_reset_stmt_id === TRUE) { $this->stmt_id = oci_parse($this->conn_id, $sql); } oci_set_prefetch($this->stmt_id, 1000); return oci_execute($this->stmt_id, $this->commit_mode); } // -------------------------------------------------------------------- /** * Get cursor. Returns a cursor from the database * * @return resource */ public function get_cursor() { return $this->curs_id = oci_new_cursor($this->conn_id); } // -------------------------------------------------------------------- /** * Stored Procedure. Executes a stored procedure * * @param string package name in which the stored procedure is in * @param string stored procedure name to execute * @param array parameters * @return mixed * * 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, array $params) { if ($package === '' OR $procedure === '') { log_message('error', 'Invalid query: '.$package.'.'.$procedure); return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE; } // Build the query string $sql = 'BEGIN '.$package.'.'.$procedure.'('; $have_cursor = FALSE; foreach ($params as $param) { $sql .= $param['name'].','; if (isset($param['type']) && $param['type'] === OCI_B_CURSOR) { $have_cursor = TRUE; } } $sql = trim($sql, ',').'); END;'; $this->_reset_stmt_id = FALSE; $this->stmt_id = oci_parse($this->conn_id, $sql); $this->_bind_params($params); $result = $this->query($sql, FALSE, $have_cursor); $this->_reset_stmt_id = TRUE; return $result; } // -------------------------------------------------------------------- /** * Bind parameters * * @param array $params * @return void */ protected 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 * * @return bool */ protected function _trans_begin() { $this->commit_mode = OCI_NO_AUTO_COMMIT; return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { $this->commit_mode = OCI_COMMIT_ON_SUCCESS; return oci_commit($this->conn_id); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { $this->commit_mode = OCI_COMMIT_ON_SUCCESS; return oci_rollback($this->conn_id); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return oci_num_rows($this->stmt_id); } // -------------------------------------------------------------------- /** * Insert ID * * @return int */ public function insert_id() { // not supported in oracle return $this->display_error('db_unsupported_function'); } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "TABLE_NAME" FROM "ALL_TABLES"'; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } else { $owner = $this->username; } return 'SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE UPPER(OWNER) = '.$this->escape(strtoupper($owner)).' AND UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } else { $owner = $this->username; } $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHAR_LENGTH, DATA_PRECISION, DATA_LENGTH, DATA_DEFAULT, NULLABLE FROM ALL_TAB_COLUMNS WHERE UPPER(OWNER) = '.$this->escape(strtoupper($owner)).' AND UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $length = ($query[$i]->CHAR_LENGTH > 0) ? $query[$i]->CHAR_LENGTH : $query[$i]->DATA_PRECISION; if ($length === NULL) { $length = $query[$i]->DATA_LENGTH; } $retval[$i]->max_length = $length; $default = $query[$i]->DATA_DEFAULT; if ($default === NULL && $query[$i]->NULLABLE === 'N') { $default = ''; } $retval[$i]->default = $default; } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { // oci_error() returns an array that already contains // 'code' and 'message' keys, but it can return false // if there was no error .... if (is_resource($this->curs_id)) { $error = oci_error($this->curs_id); } elseif (is_resource($this->stmt_id)) { $error = oci_error($this->stmt_id); } elseif (is_resource($this->conn_id)) { $error = oci_error($this->conn_id); } else { $error = oci_error(); } return is_array($error) ? $error : array('code' => '', 'message' => ''); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data * * @param string $table Table name * @param array $keys INSERT keys * @param array $values 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"; } return $sql.'SELECT * FROM dual'; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { if ($this->qb_limit) { $this->where('rownum <= ',$this->qb_limit, FALSE); $this->qb_limit = FALSE; } return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { if (version_compare($this->version(), '12.1', '>=')) { // OFFSET-FETCH can be used only with the ORDER BY clause empty($this->qb_orderby) && $sql .= ' ORDER BY 1'; return $sql.' OFFSET '.(int) $this->qb_offset.' ROWS FETCH NEXT '.$this->qb_limit.' ROWS ONLY'; } $this->limit_used = TRUE; return 'SELECT * FROM (SELECT inner_query.*, rownum rnum FROM ('.$sql.') inner_query WHERE rownum < '.($this->qb_offset + $this->qb_limit + 1).')' .($this->qb_offset ? ' WHERE rnum >= '.($this->qb_offset + 1) : ''); } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { if (is_resource($this->curs_id)) { oci_free_statement($this->curs_id); } if (is_resource($this->stmt_id)) { oci_free_statement($this->stmt_id); } oci_close($this->conn_id); } // -------------------------------------------------------------------- /** * We need to reset our $limit_used hack flag, so it doesn't propagate * to subsequent queries. * * @return void */ protected function _reset_select() { $this->limit_used = FALSE; parent::_reset_select(); } } database/drivers/oci8/oci8_result.php000064400000012454152270514220013607 0ustar00stmt_id = $driver_object->stmt_id; $this->curs_id = $driver_object->curs_id; $this->limit_used = $driver_object->limit_used; $this->commit_mode =& $driver_object->commit_mode; $driver_object->stmt_id = FALSE; } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { $count = oci_num_fields($this->stmt_id); // if we used a limit we subtract it return ($this->limit_used) ? $count - 1 : $count; } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @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 * * @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 void */ public function free_result() { if (is_resource($this->result_id)) { oci_free_statement($this->result_id); $this->result_id = FALSE; } if (is_resource($this->stmt_id)) { oci_free_statement($this->stmt_id); } if (is_resource($this->curs_id)) { oci_cancel($this->curs_id); $this->curs_id = NULL; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @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 * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { $row = ($this->curs_id) ? oci_fetch_object($this->curs_id) : oci_fetch_object($this->stmt_id); if ($class_name === 'stdClass' OR ! $row) { return $row; } $class_name = new $class_name(); foreach ($row as $key => $value) { $class_name->$key = $value; } return $class_name; } } database/drivers/oci8/oci8_utility.php000064400000004513152270514220013771 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/oci8/index.html000064400000000203152270514220012620 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/oci8/oci8_forge.php000064400000013076152270514220013374 0ustar00db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $field[$i] = "\n\t".$field[$i]['_literal']; } else { $field[$i]['_literal'] = "\n\t".$this->_process_column($field[$i]); if ( ! empty($field[$i]['comment'])) { $sqls[] = 'COMMENT ON COLUMN ' .$this->db->escape_identifiers($table).'.'.$this->db->escape_identifiers($field[$i]['name']) .' IS '.$field[$i]['comment']; } if ($alter_type === 'MODIFY' && ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' RENAME COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } $field[$i] = "\n\t".$field[$i]['_literal']; } } $sql .= ' '.$alter_type.' '; $sql .= (count($field) === 1) ? $field[0] : '('.implode(',', $field).')'; // RENAME COLUMN must be executed after MODIFY array_unshift($sqls, $sql); return $sqls; } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'number') !== FALSE && version_compare($this->db->version(), '12.1', '>=')) { $field['auto_increment'] = ' GENERATED ALWAYS AS IDENTITY'; } } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['default'] .$field['auto_increment'] .$field['null'] .$field['unique']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'NUMBER'; return; case 'MEDIUMINT': $attributes['TYPE'] = 'NUMBER'; return; case 'INT': $attributes['TYPE'] = 'NUMBER'; return; case 'BIGINT': $attributes['TYPE'] = 'NUMBER'; return; default: return; } } } database/drivers/cubrid/cubrid_result.php000064400000011314152270514220014615 0ustar00num_rows) ? $this->num_rows : $this->num_rows = cubrid_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return cubrid_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { return cubrid_column_names($this->result_id); } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = cubrid_field_name($this->result_id, $i); $retval[$i]->type = cubrid_field_type($this->result_id, $i); $retval[$i]->max_length = cubrid_field_len($this->result_id, $i); $retval[$i]->primary_key = (int) (strpos(cubrid_field_flags($this->result_id, $i), 'primary_key') !== FALSE); } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if (is_resource($this->result_id) OR (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. * * @param int $n * @return bool */ public function data_seek($n = 0) { return cubrid_data_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return cubrid_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return cubrid_fetch_object($this->result_id, $class_name); } } database/drivers/cubrid/cubrid_forge.php000064400000013403152270514220014402 0ustar00 'INTEGER', 'SMALLINT' => 'INTEGER', 'INT' => 'BIGINT', 'INTEGER' => 'BIGINT', 'BIGINT' => 'NUMERIC', 'FLOAT' => 'DOUBLE', 'REAL' => 'DOUBLE' ); // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('DROP', 'ADD'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $sqls[] = $sql.' CHANGE '.$field[$i]['_literal']; } else { $alter_type = empty($field[$i]['new_name']) ? ' MODIFY ' : ' CHANGE '; $sqls[] = $sql.$alter_type.$this->_process_column($field[$i]); } } return $sqls; } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { $extra_clause = isset($field['after']) ? ' AFTER '.$this->db->escape_identifiers($field['after']) : ''; if (empty($extra_clause) && isset($field['first']) && $field['first'] === TRUE) { $extra_clause = ' FIRST'; } return $this->db->escape_identifiers($field['name']) .(empty($field['new_name']) ? '' : ' '.$this->db->escape_identifiers($field['new_name'])) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['null'] .$field['default'] .$field['auto_increment'] .$field['unique'] .$extra_clause; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'LONGTEXT': $attributes['TYPE'] = 'STRING'; return; default: return; } } // -------------------------------------------------------------------- /** * Process indexes * * @param string $table (ignored) * @return string */ protected function _process_indexes($table) { $sql = ''; for ($i = 0, $c = count($this->keys); $i < $c; $i++) { if (is_array($this->keys[$i])) { for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++) { if ( ! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } elseif ( ! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; } is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]); $sql .= ",\n\tKEY ".$this->db->escape_identifiers(implode('_', $this->keys[$i])) .' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).')'; } $this->keys = array(); return $sql; } } database/drivers/cubrid/cubrid_driver.php000064400000022625152270514220014601 0ustar00dsn, $matches)) { if (stripos($matches[2], 'autocommit=off') !== FALSE) { $this->auto_commit = FALSE; } } else { // If no port is defined by the user, use the default value empty($this->port) OR $this->port = 33000; } } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @param bool $persistent * @return resource */ public function db_connect($persistent = FALSE) { if (preg_match('/^CUBRID:[^:]+(:[0-9][1-9]{0,4})?:[^:]+:([^:]*):([^:]*):(\?.+)?$/', $this->dsn, $matches)) { $func = ($persistent !== TRUE) ? 'cubrid_connect_with_url' : 'cubrid_pconnect_with_url'; return ($matches[2] === '' && $matches[3] === '' && $this->username !== '' && $this->password !== '') ? $func($this->dsn, $this->username, $this->password) : $func($this->dsn); } $func = ($persistent !== TRUE) ? 'cubrid_connect' : 'cubrid_pconnect'; return ($this->username !== '') ? $func($this->hostname, $this->port, $this->database, $this->username, $this->password) : $func($this->hostname, $this->port, $this->database); } // -------------------------------------------------------------------- /** * Reconnect * * Keep / reestablish the db connection if no queries have been * sent for a length of time exceeding the server's idle timeout * * @return void */ public function reconnect() { if (cubrid_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } return ( ! $this->conn_id OR ($version = cubrid_get_server_info($this->conn_id)) === FALSE) ? FALSE : $this->data_cache['version'] = $version; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return resource */ protected function _execute($sql) { return cubrid_query($sql, $this->conn_id); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { if (($autocommit = cubrid_get_autocommit($this->conn_id)) === NULL) { return FALSE; } elseif ($autocommit === TRUE) { return cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_FALSE); } return TRUE; } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { if ( ! cubrid_commit($this->conn_id)) { return FALSE; } if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) { return cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); } return TRUE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { if ( ! cubrid_rollback($this->conn_id)) { return FALSE; } if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) { cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); } return TRUE; } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { return cubrid_real_escape_string($str, $this->conn_id); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return cubrid_affected_rows(); } // -------------------------------------------------------------------- /** * Insert ID * * @return int */ public function insert_id() { return cubrid_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SHOW TABLES'; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length ); $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { return array('code' => cubrid_errno($this->conn_id), 'message' => cubrid_error($this->conn_id)); } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * @return string */ protected function _from_tables() { if ( ! empty($this->qb_join) && count($this->qb_from) > 1) { return '('.implode(', ', $this->qb_from).')'; } return implode(', ', $this->qb_from); } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { cubrid_close($this->conn_id); } } database/drivers/cubrid/index.html000064400000000203152270514220013226 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/cubrid/cubrid_utility.php000064400000005215152270514220015005 0ustar00db->data_cache['db_names'])) { return $this->db->data_cache['db_names']; } return $this->db->data_cache['db_names'] = cubrid_list_dbs($this->db->conn_id); } // -------------------------------------------------------------------- /** * CUBRID Export * * @param array Preferences * @return mixed */ protected 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_unsupported_feature'); } } database/drivers/mysql/mysql_utility.php000064400000012777152270514220014612 0ustar00db->query('SHOW CREATE TABLE '.$this->db->escape_identifiers($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 '.$this->db->protect_identifiers($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 '.$this->db->protect_identifiers($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); // Create a string of field names $field_str .= $this->db->escape_identifiers($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 $val_str .= ($is_int[$i] === FALSE) ? $this->db->escape($v) : $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 '.$this->db->protect_identifiers($table).' ('.$field_str.') VALUES ('.$val_str.');'.$newline; } $output .= $newline.$newline; } // Do we need to include a statement to re-enable foreign key checks? if ($foreign_key_checks === FALSE) { $output .= 'SET foreign_key_checks = 1;'.$newline; } return $output; } } database/drivers/mysql/mysql_driver.php000064400000026544152270514220014377 0ustar00port)) { $this->hostname .= ':'.$this->port; } } // -------------------------------------------------------------------- /** * Non-persistent database connection * * @param bool $persistent * @return resource */ public function db_connect($persistent = FALSE) { $client_flags = ($this->compress === FALSE) ? 0 : MYSQL_CLIENT_COMPRESS; if ($this->encrypt === TRUE) { $client_flags = $client_flags | MYSQL_CLIENT_SSL; } // Error suppression is necessary mostly due to PHP 5.5+ issuing E_DEPRECATED messages $this->conn_id = ($persistent === TRUE) ? mysql_pconnect($this->hostname, $this->username, $this->password, $client_flags) : mysql_connect($this->hostname, $this->username, $this->password, TRUE, $client_flags); // ---------------------------------------------------------------- // Select the DB... assuming a database name is specified in the config file if ($this->database !== '' && ! $this->db_select()) { log_message('error', 'Unable to select database: '.$this->database); return ($this->db_debug === TRUE) ? $this->display_error('db_unable_to_select', $this->database) : FALSE; } if (isset($this->stricton) && is_resource($this->conn_id)) { if ($this->stricton) { $this->simple_query('SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'); } else { $this->simple_query( 'SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @@sql_mode, "STRICT_ALL_TABLES,", ""), ",STRICT_ALL_TABLES", ""), "STRICT_ALL_TABLES", ""), "STRICT_TRANS_TABLES,", ""), ",STRICT_TRANS_TABLES", ""), "STRICT_TRANS_TABLES", "")' ); } } return $this->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 * * @return void */ public function reconnect() { if (mysql_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Select the database * * @param string $database * @return bool */ public function db_select($database = '') { if ($database === '') { $database = $this->database; } if (mysql_select_db($database, $this->conn_id)) { $this->database = $database; $this->data_cache = array(); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Set client character set * * @param string $charset * @return bool */ protected function _db_set_charset($charset) { return mysql_set_charset($charset, $this->conn_id); } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if ( ! $this->conn_id OR ($version = mysql_get_server_info($this->conn_id)) === FALSE) { return FALSE; } return $this->data_cache['version'] = $version; } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return mixed */ protected function _execute($sql) { return mysql_query($this->_prep_query($sql), $this->conn_id); } // -------------------------------------------------------------------- /** * Prep the query * * If needed, each database adapter can prep the query string * * @param string $sql an SQL query * @return string */ protected function _prep_query($sql) { // mysql_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack // modifies the query so that it a proper number of affected rows is returned. if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) { return trim($sql).' WHERE 1=1'; } return $sql; } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { $this->simple_query('SET AUTOCOMMIT=0'); return $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { if ($this->simple_query('COMMIT')) { $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { if ($this->simple_query('ROLLBACK')) { $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { return mysql_real_escape_string($str, $this->conn_id); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return mysql_affected_rows($this->conn_id); } // -------------------------------------------------------------------- /** * Insert ID * * @return int */ public function insert_id() { return mysql_insert_id($this->conn_id); } // -------------------------------------------------------------------- /** * List table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SHOW TABLES FROM '.$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length ); $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { return array('code' => mysql_errno($this->conn_id), 'message' => mysql_error($this->conn_id)); } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * @return string */ protected function _from_tables() { if ( ! empty($this->qb_join) && count($this->qb_from) > 1) { return '('.implode(', ', $this->qb_from).')'; } return implode(', ', $this->qb_from); } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { // Error suppression to avoid annoying E_WARNINGs in cases // where the connection has already been closed for some reason. @mysql_close($this->conn_id); } } database/drivers/mysql/mysql_result.php000064400000012057152270514220014414 0ustar00num_rows = mysql_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of rows in the result set * * @return int */ public function num_rows() { return $this->num_rows; } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return mysql_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); mysql_field_seek($this->result_id, 0); 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 * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = mysql_field_name($this->result_id, $i); $retval[$i]->type = mysql_field_type($this->result_id, $i); $retval[$i]->max_length = mysql_field_len($this->result_id, $i); $retval[$i]->primary_key = (int) (strpos(mysql_field_flags($this->result_id, $i), 'primary_key') !== FALSE); } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public 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. * * @param int $n * @return bool */ public function data_seek($n = 0) { return $this->num_rows ? mysql_data_seek($this->result_id, $n) : FALSE; } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return mysql_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return mysql_fetch_object($this->result_id, $class_name); } } database/drivers/mysql/index.html000064400000000203152270514220013123 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/mysql/mysql_forge.php000064400000014075152270514220014202 0ustar00db->char_set) && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) { $sql .= ' DEFAULT CHARACTER SET = '.$this->db->char_set; } if ( ! empty($this->db->dbcollat) && ! strpos($sql, 'COLLATE')) { $sql .= ' COLLATE = '.$this->db->dbcollat; } return $sql; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP') { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $field[$i] = ($alter_type === 'ADD') ? "\n\tADD ".$field[$i]['_literal'] : "\n\tMODIFY ".$field[$i]['_literal']; } else { if ($alter_type === 'ADD') { $field[$i]['_literal'] = "\n\tADD "; } else { $field[$i]['_literal'] = empty($field[$i]['new_name']) ? "\n\tMODIFY " : "\n\tCHANGE "; } $field[$i] = $field[$i]['_literal'].$this->_process_column($field[$i]); } } return array($sql.implode(',', $field)); } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { $extra_clause = isset($field['after']) ? ' AFTER '.$this->db->escape_identifiers($field['after']) : ''; if (empty($extra_clause) && isset($field['first']) && $field['first'] === TRUE) { $extra_clause = ' FIRST'; } return $this->db->escape_identifiers($field['name']) .(empty($field['new_name']) ? '' : ' '.$this->db->escape_identifiers($field['new_name'])) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['null'] .$field['default'] .$field['auto_increment'] .$field['unique'] .(empty($field['comment']) ? '' : ' COMMENT '.$field['comment']) .$extra_clause; } // -------------------------------------------------------------------- /** * Process indexes * * @param string $table (ignored) * @return string */ protected function _process_indexes($table) { $sql = ''; for ($i = 0, $c = count($this->keys); $i < $c; $i++) { if (is_array($this->keys[$i])) { for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++) { if ( ! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } elseif ( ! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; } is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]); $sql .= ",\n\tKEY ".$this->db->escape_identifiers(implode('_', $this->keys[$i])) .' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).')'; } $this->keys = array(); return $sql; } } database/drivers/index.html000064400000000203152270514220011756 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/postgre/postgre_driver.php000064400000034625152270514220015232 0ustar00dsn === '' OR $this->dsn = ''; if (strpos($this->hostname, '/') !== FALSE) { // If UNIX sockets are used, we shouldn't set a port $this->port = ''; } $this->hostname === '' OR $this->dsn = 'host='.$this->hostname.' '; if ( ! empty($this->port) && ctype_digit($this->port)) { $this->dsn .= 'port='.$this->port.' '; } if ($this->username !== '') { $this->dsn .= 'user='.$this->username.' '; /* An empty password is valid! * * $db['password'] = NULL must be done in order to ignore it. */ $this->password === NULL OR $this->dsn .= "password='".$this->password."' "; } $this->database === '' OR $this->dsn .= 'dbname='.$this->database.' '; /* We don't have these options as elements in our standard configuration * array, but they might be set by parse_url() if the configuration was * provided via string. Example: * * postgre://username:password@localhost:5432/database?connect_timeout=5&sslmode=1 */ foreach (array('connect_timeout', 'options', 'sslmode', 'service') as $key) { if (isset($this->$key) && is_string($this->$key) && $this->$key !== '') { $this->dsn .= $key."='".$this->$key."' "; } } $this->dsn = rtrim($this->dsn); } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return resource|object */ public function db_connect($persistent = FALSE) { empty($this->dsn) && $this->_build_dsn(); $this->conn_id = ($persistent === TRUE) ? pg_pconnect($this->dsn) : pg_connect($this->dsn); if ($this->conn_id !== FALSE) { if ($persistent === TRUE && pg_connection_status($this->conn_id) === PGSQL_CONNECTION_BAD && pg_ping($this->conn_id) === FALSE ) { return FALSE; } empty($this->schema) OR $this->simple_query('SET search_path TO '.$this->schema.',public'); } return $this->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 * * @return void */ public function reconnect() { if (pg_ping($this->conn_id) === FALSE) { $this->conn_id = FALSE; } } // -------------------------------------------------------------------- /** * Set client character set * * @param string $charset * @return bool */ protected function _db_set_charset($charset) { return (pg_set_client_encoding($this->conn_id, $charset) === 0); } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } if ( ! $this->conn_id OR ($pg_version = pg_version($this->conn_id)) === FALSE) { return FALSE; } /* If PHP was compiled with PostgreSQL lib versions earlier * than 7.4, pg_version() won't return the server version * and so we'll have to fall back to running a query in * order to get it. */ return (isset($pg_version['server']) && preg_match('#^(\d+\.\d+)#', $pg_version['server'], $match)) ? $this->data_cache['version'] = $match[1] : parent::version(); } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql an SQL query * @return resource|object */ protected function _execute($sql) { return pg_query($this->conn_id, $sql); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return (bool) pg_query($this->conn_id, 'BEGIN'); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { return (bool) pg_query($this->conn_id, 'COMMIT'); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { return (bool) pg_query($this->conn_id, 'ROLLBACK'); } // -------------------------------------------------------------------- /** * Determines if a query is a "write" type. * * @param string An SQL query string * @return bool */ public function is_write_type($sql) { if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql)) { return FALSE; } return parent::is_write_type($sql); } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { return pg_escape_string($this->conn_id, $str); } // -------------------------------------------------------------------- /** * "Smart" Escape String * * Escapes data based on type * * @param string $str * @return mixed */ public function escape($str) { if (is_php('5.4.4') && (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))) { return pg_escape_literal($this->conn_id, $str); } elseif (is_bool($str)) { return ($str) ? 'TRUE' : 'FALSE'; } return parent::escape($str); } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return pg_affected_rows($this->result_id); } // -------------------------------------------------------------------- /** * Insert ID * * @return string */ public function insert_id() { $v = $this->version(); $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) { if ($column !== NULL && $v >= '8.0') { $sql = 'SELECT pg_get_serial_sequence(\''.$table."', '".$column."') AS seq"; $query = $this->query($sql); $query = $query->row(); $seq = $query->seq; } else { // seq_name passed in table parameter $seq = $table; } $sql = 'SELECT CURRVAL(\''.$seq."') AS ins_id"; } else { return pg_last_oid($this->result_id); } $query = $this->query($sql); $query = $query->row(); return (int) $query->ins_id; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \''.$this->schema."'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $sql.' AND "table_name" LIKE \'' .$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * List column query * * Generates a platform-specific query string so that the column names can be fetched * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT "column_name" FROM "information_schema"."columns" WHERE "table_schema" = \''.$this->schema.'\' AND LOWER("table_name") = '.$this->escape(strtolower($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT "column_name", "data_type", "character_maximum_length", "numeric_precision", "column_default" FROM "information_schema"."columns" WHERE "table_schema" = \''.$this->schema.'\' AND LOWER("table_name") = '.$this->escape(strtolower($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->column_name; $retval[$i]->type = $query[$i]->data_type; $retval[$i]->max_length = ($query[$i]->character_maximum_length > 0) ? $query[$i]->character_maximum_length : $query[$i]->numeric_precision; $retval[$i]->default = $query[$i]->column_default; } return $retval; } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { return array('code' => '', 'message' => pg_last_error($this->conn_id)); } // -------------------------------------------------------------------- /** * ORDER BY * * @param string $orderby * @param string $direction ASC, DESC or RANDOM * @param bool $escape * @return object */ public function order_by($orderby, $direction = '', $escape = NULL) { $direction = strtoupper(trim($direction)); if ($direction === 'RANDOM') { if ( ! is_float($orderby) && ctype_digit((string) $orderby)) { $orderby = ($orderby > 1) ? (float) '0.'.$orderby : (float) $orderby; } if (is_float($orderby)) { $this->simple_query('SET SEED '.$orderby); } $orderby = $this->_random_keyword[0]; $direction = ''; $escape = FALSE; } return parent::order_by($orderby, $direction, $escape); } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @param string $table Table name * @param array $values Update data * @param string $index WHERE key * @return string */ protected function _update_batch($table, $values, $index) { $ids = array(); foreach ($values as $key => $val) { $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = (CASE '.$val[$index]['field']."\n" .implode("\n", $v)."\n" .'ELSE '.$k.' END), '; } $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { return $sql.' LIMIT '.$this->qb_limit.($this->qb_offset ? ' OFFSET '.$this->qb_offset : ''); } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { pg_close($this->conn_id); } } database/drivers/postgre/postgre_result.php000064400000011170152270514220015243 0ustar00num_rows) ? $this->num_rows : $this->num_rows = pg_num_rows($this->result_id); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return pg_num_fields($this->result_id); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return array */ public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[] = pg_field_name($this->result_id, $i); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = pg_field_name($this->result_id, $i); $retval[$i]->type = pg_field_type($this->result_id, $i); $retval[$i]->max_length = pg_field_size($this->result_id, $i); } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if ($this->result_id !== FALSE) { 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. * * @param int $n * @return bool */ public function data_seek($n = 0) { return pg_result_seek($this->result_id, $n); } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return pg_fetch_assoc($this->result_id); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return pg_fetch_object($this->result_id, NULL, $class_name); } } database/drivers/postgre/index.html000064400000000203152270514220013441 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/postgre/postgre_forge.php000064400000013241152270514220015030 0ustar00 'INTEGER', 'SMALLINT' => 'INTEGER', 'INT' => 'BIGINT', 'INT4' => 'BIGINT', 'INTEGER' => 'BIGINT', 'INT8' => 'NUMERIC', 'BIGINT' => 'NUMERIC', 'REAL' => 'DOUBLE PRECISION', 'FLOAT' => 'DOUBLE PRECISION' ); /** * NULL value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_null = 'NULL'; // -------------------------------------------------------------------- /** * Class constructor * * @param object &$db Database object * @return void */ public function __construct(&$db) { parent::__construct($db); if (version_compare($this->db->version(), '9.0', '>')) { $this->create_table_if = 'CREATE TABLE IF NOT EXISTS'; } } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('DROP', 'ADD'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { return FALSE; } if (version_compare($this->db->version(), '8', '>=') && isset($field[$i]['type'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TYPE '.$field[$i]['type'].$field[$i]['length']; } if ( ! empty($field[$i]['default'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' SET '.$field[$i]['default']; } if (isset($field[$i]['null'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .(trim($field[$i]['null']) === $this->_null ? ' DROP NOT NULL' : ' SET NOT NULL'); } if ( ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' RENAME COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } if ( ! empty($field[$i]['comment'])) { $sqls[] = 'COMMENT ON COLUMN ' .$this->db->escape_identifiers($table).'.'.$this->db->escape_identifiers($field[$i]['name']) .' IS '.$field[$i]['comment']; } } return $sqls; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { // Reset field lengths for data types that don't support it if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== FALSE) { $attributes['CONSTRAINT'] = NULL; } switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) { $field['type'] = ($field['type'] === 'NUMERIC') ? 'BIGSERIAL' : 'SERIAL'; } } } database/drivers/postgre/postgre_utility.php000064400000005027152270514220015434 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/pdo/pdo_utility.php000064400000004320152270514220013625 0ustar00db->display_error('db_unsupported_feature'); } } database/drivers/pdo/pdo_result.php000064400000012006152270514220013440 0ustar00num_rows)) { return $this->num_rows; } elseif (count($this->result_array) > 0) { return $this->num_rows = count($this->result_array); } elseif (count($this->result_object) > 0) { return $this->num_rows = count($this->result_object); } elseif (($num_rows = $this->result_id->rowCount()) > 0) { return $this->num_rows = $num_rows; } return $this->num_rows = count($this->result_array()); } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @return int */ public function num_fields() { return $this->result_id->columnCount(); } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @return bool */ public function list_fields() { $field_names = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { // Might trigger an E_WARNING due to not all subdrivers // supporting getColumnMeta() $field_names[$i] = @$this->result_id->getColumnMeta($i); $field_names[$i] = $field_names[$i]['name']; } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @return array */ public function field_data() { try { $retval = array(); for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field = $this->result_id->getColumnMeta($i); $retval[$i] = new stdClass(); $retval[$i]->name = $field['name']; $retval[$i]->type = isset($field['native_type']) ? $field['native_type'] : null; $retval[$i]->max_length = ($field['len'] > 0) ? $field['len'] : NULL; $retval[$i]->primary_key = (int) ( ! empty($field['flags']) && in_array('primary_key', $field['flags'], TRUE)); } return $retval; } catch (Exception $e) { if ($this->db->db_debug) { return $this->db->display_error('db_unsupported_feature'); } return FALSE; } } // -------------------------------------------------------------------- /** * Free the result * * @return void */ public function free_result() { if (is_object($this->result_id)) { $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @return array */ protected function _fetch_assoc() { return $this->result_id->fetch(PDO::FETCH_ASSOC); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { return $this->result_id->fetchObject($class_name); } } database/drivers/pdo/pdo_forge.php000064400000004256152270514220013234 0ustar00dsn, $match) && count($match) === 2) { // If there is a minimum valid dsn string pattern found, we're done // This is for general PDO users, who tend to have a full DSN string. $this->subdriver = $match[1]; return; } // Legacy support for DSN specified in the hostname field elseif (preg_match('/([^:]+):/', $this->hostname, $match) && count($match) === 2) { $this->dsn = $this->hostname; $this->hostname = NULL; $this->subdriver = $match[1]; return; } elseif (in_array($this->subdriver, array('mssql', 'sybase'), TRUE)) { $this->subdriver = 'dblib'; } elseif ($this->subdriver === '4D') { $this->subdriver = '4d'; } elseif ( ! in_array($this->subdriver, array('4d', 'cubrid', 'dblib', 'firebird', 'ibm', 'informix', 'mysql', 'oci', 'odbc', 'pgsql', 'sqlite', 'sqlsrv'), TRUE)) { log_message('error', 'PDO: Invalid or non-existent subdriver'); if ($this->db_debug) { show_error('Invalid or non-existent PDO subdriver'); } } $this->dsn = NULL; } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { if ($persistent === TRUE) { $this->options[PDO::ATTR_PERSISTENT] = TRUE; } // From PHP8.0, default PDO::ATTR_ERRMODE is changed // from PDO::ERRMODE_SILENT to PDO::ERRMODE_EXCEPTION // as https://wiki.php.net/rfc/pdo_default_errmode if ( ! isset($this->options[PDO::ATTR_ERRMODE])) { $this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT; } try { return new PDO($this->dsn, $this->username, $this->password, $this->options); } catch (PDOException $e) { if ($this->db_debug && empty($this->failover)) { $this->display_error($e->getMessage(), '', TRUE); } return FALSE; } } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } // Not all subdrivers support the getAttribute() method try { return $this->data_cache['version'] = $this->conn_id->getAttribute(PDO::ATTR_SERVER_VERSION); } catch (PDOException $e) { return parent::version(); } } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql SQL query * @return mixed */ protected function _execute($sql) { return $this->conn_id->query($sql); } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { return $this->conn_id->beginTransaction(); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { return $this->conn_id->commit(); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { return $this->conn_id->rollBack(); } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { // Escape the string $str = $this->conn_id->quote($str); // If there are duplicated quotes, trim them away return ($str[0] === "'") ? substr($str, 1, -1) : $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return is_object($this->result_id) ? $this->result_id->rowCount() : 0; } // -------------------------------------------------------------------- /** * Insert ID * * @param string $name * @return int */ public function insert_id($name = NULL) { return $this->conn_id->lastInsertId($name); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @param string $table * @return string */ protected function _field_data($table) { return 'SELECT TOP 1 * FROM '.$this->protect_identifiers($table); } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occurred. * * @return array */ public function error() { $error = array('code' => '00000', 'message' => ''); $pdo_error = $this->conn_id->errorInfo(); if (empty($pdo_error[0])) { return $error; } $error['code'] = isset($pdo_error[1]) ? $pdo_error[0].'/'.$pdo_error[1] : $pdo_error[0]; if (isset($pdo_error[2])) { $error['message'] = $pdo_error[2]; } return $error; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- /** * Close DB Connection * * @return void */ protected function _close() { $this->result_id = FALSE; $this->conn_id = FALSE; } } database/drivers/pdo/index.html000064400000000203152270514220012540 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/pdo/subdrivers/pdo_dblib_forge.php000064400000010465152270514220016557 0ustar00 'SMALLINT', 'SMALLINT' => 'INT', 'INT' => 'BIGINT', 'REAL' => 'FLOAT' ); // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ALTER COLUMN '; $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql.$this->_process_column($field[$i]); } return $sqls; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) { unset($attributes['CONSTRAINT']); } switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INTEGER': $attributes['TYPE'] = 'INT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' IDENTITY(1,1)'; } } } database/drivers/pdo/subdrivers/pdo_informix_forge.php000064400000010457152270514220017337 0ustar00 'INTEGER', 'INT' => 'BIGINT', 'INTEGER' => 'BIGINT', 'REAL' => 'DOUBLE PRECISION', 'SMALLFLOAT' => 'DOUBLE PRECISION' ); /** * DEFAULT value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_default = ', '; // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'CHANGE') { $alter_type = 'MODIFY'; } return parent::_alter_table($alter_type, $table, $field); } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'BYTE': case 'TEXT': case 'BLOB': case 'CLOB': $attributes['UNIQUE'] = FALSE; if (isset($attributes['DEFAULT'])) { unset($attributes['DEFAULT']); } return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute UNIQUE * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_unique(&$attributes, &$field) { if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE) { $field['unique'] = ' UNIQUE CONSTRAINT '.$this->db->escape_identifiers($field['name']); } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { // Not supported } } database/drivers/pdo/subdrivers/pdo_firebird_driver.php000064400000017231152270514220017460 0ustar00dsn)) { $this->dsn = 'firebird:'; if ( ! empty($this->database)) { $this->dsn .= 'dbname='.$this->database; } elseif ( ! empty($this->hostname)) { $this->dsn .= 'dbname='.$this->hostname; } empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set; empty($this->role) OR $this->dsn .= ';role='.$this->role; } elseif ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 9) === FALSE) { $this->dsn .= ';charset='.$this->char_set; } } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "RDB$RELATION_NAME" FROM "RDB$RELATIONS" WHERE "RDB$RELATION_NAME" NOT LIKE \'RDB$%\' AND "RDB$RELATION_NAME" NOT LIKE \'MON$%\''; if ($prefix_limit === TRUE && $this->dbprefix !== '') { return $sql.' AND "RDB$RELATION_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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT "RDB$FIELD_NAME" FROM "RDB$RELATION_FIELDS" WHERE "RDB$RELATION_NAME" = '.$this->escape($table); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT "rfields"."RDB$FIELD_NAME" AS "name", CASE "fields"."RDB$FIELD_TYPE" WHEN 7 THEN \'SMALLINT\' WHEN 8 THEN \'INTEGER\' WHEN 9 THEN \'QUAD\' WHEN 10 THEN \'FLOAT\' WHEN 11 THEN \'DFLOAT\' WHEN 12 THEN \'DATE\' WHEN 13 THEN \'TIME\' WHEN 14 THEN \'CHAR\' WHEN 16 THEN \'INT64\' WHEN 27 THEN \'DOUBLE\' WHEN 35 THEN \'TIMESTAMP\' WHEN 37 THEN \'VARCHAR\' WHEN 40 THEN \'CSTRING\' WHEN 261 THEN \'BLOB\' ELSE NULL END AS "type", "fields"."RDB$FIELD_LENGTH" AS "max_length", "rfields"."RDB$DEFAULT_VALUE" AS "default" FROM "RDB$RELATION_FIELDS" "rfields" JOIN "RDB$FIELDS" "fields" ON "rfields"."RDB$FIELD_SOURCE" = "fields"."RDB$FIELD_NAME" WHERE "rfields"."RDB$RELATION_NAME" = '.$this->escape($table).' ORDER BY "rfields"."RDB$FIELD_POSITION"'; return (($query = $this->query($sql)) !== FALSE) ? $query->result_object() : FALSE; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { // Limit clause depends on if Interbase or Firebird if (stripos($this->version(), 'firebird') !== FALSE) { $select = 'FIRST '.$this->qb_limit .($this->qb_offset > 0 ? ' SKIP '.$this->qb_offset : ''); } else { $select = 'ROWS ' .($this->qb_offset > 0 ? $this->qb_offset.' TO '.($this->qb_limit + $this->qb_offset) : $this->qb_limit); } return preg_replace('`SELECT`i', 'SELECT '.$select, $sql); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string|bool */ protected function _insert_batch($table, $keys, $values) { return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } } database/drivers/pdo/subdrivers/pdo_firebird_forge.php000064400000014310152270514220017262 0ustar00 'INTEGER', 'INTEGER' => 'INT64', 'FLOAT' => 'DOUBLE PRECISION' ); /** * NULL value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_null = 'NULL'; // -------------------------------------------------------------------- /** * Create database * * @param string $db_name * @return string */ public function create_database($db_name) { // Firebird databases are flat files, so a path is required // Hostname is needed for remote access empty($this->db->hostname) OR $db_name = $this->hostname.':'.$db_name; return parent::create_database('"'.$db_name.'"'); } // -------------------------------------------------------------------- /** * Drop database * * @param string $db_name (ignored) * @return bool */ public function drop_database($db_name) { if ( ! ibase_drop_db($this->conn_id)) { return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE; } elseif ( ! empty($this->db->data_cache['db_names'])) { $key = array_search(strtolower($this->db->database), array_map('strtolower', $this->db->data_cache['db_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['db_names'][$key]); } } return TRUE; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('DROP', 'ADD'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { return FALSE; } if (isset($field[$i]['type'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TYPE '.$field[$i]['type'].$field[$i]['length']; } if ( ! empty($field[$i]['default'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' SET '.$field[$i]['default']; } if (isset($field[$i]['null'])) { $sqls[] = 'UPDATE "RDB$RELATION_FIELDS" SET "RDB$NULL_FLAG" = ' .($field[$i]['null'] === TRUE ? 'NULL' : '1') .' WHERE "RDB$FIELD_NAME" = '.$this->db->escape($field[$i]['name']) .' AND "RDB$RELATION_NAME" = '.$this->db->escape($table); } if ( ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } } return $sqls; } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['null'] .$field['unique'] .$field['default']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INT': $attributes['TYPE'] = 'INTEGER'; return; case 'BIGINT': $attributes['TYPE'] = 'INT64'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { // Not supported } } database/drivers/pdo/subdrivers/pdo_ibm_driver.php000064400000015057152270514220016445 0ustar00dsn)) { $this->dsn = 'ibm:'; // Pre-defined DSN if (empty($this->hostname) && empty($this->HOSTNAME) && empty($this->port) && empty($this->PORT)) { if (isset($this->DSN)) { $this->dsn .= 'DSN='.$this->DSN; } elseif ( ! empty($this->database)) { $this->dsn .= 'DSN='.$this->database; } return; } $this->dsn .= 'DRIVER='.(isset($this->DRIVER) ? '{'.$this->DRIVER.'}' : '{IBM DB2 ODBC DRIVER}').';'; if (isset($this->DATABASE)) { $this->dsn .= 'DATABASE='.$this->DATABASE.';'; } elseif ( ! empty($this->database)) { $this->dsn .= 'DATABASE='.$this->database.';'; } if (isset($this->HOSTNAME)) { $this->dsn .= 'HOSTNAME='.$this->HOSTNAME.';'; } else { $this->dsn .= 'HOSTNAME='.(empty($this->hostname) ? '127.0.0.1;' : $this->hostname.';'); } if (isset($this->PORT)) { $this->dsn .= 'PORT='.$this->port.';'; } elseif ( ! empty($this->port)) { $this->dsn .= ';PORT='.$this->port.';'; } $this->dsn .= 'PROTOCOL='.(isset($this->PROTOCOL) ? $this->PROTOCOL.';' : 'TCPIP;'); } } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "tabname" FROM "syscat"."tables" WHERE "type" = \'T\' AND LOWER("tabschema") = '.$this->escape(strtolower($this->database)); if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' AND "tabname" 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 * * @param string $table * @return array */ protected function _list_columns($table = '') { return 'SELECT "colname" FROM "syscat"."columns" WHERE LOWER("tabschema") = '.$this->escape(strtolower($this->database)).' AND LOWER("tabname") = '.$this->escape(strtolower($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT "colname" AS "name", "typename" AS "type", "default" AS "default", "length" AS "max_length", CASE "keyseq" WHEN NULL THEN 0 ELSE 1 END AS "primary_key" FROM "syscat"."columns" WHERE LOWER("tabschema") = '.$this->escape(strtolower($this->database)).' AND LOWER("tabname") = '.$this->escape(strtolower($table)).' ORDER BY "colno"'; return (($query = $this->query($sql)) !== FALSE) ? $query->result_object() : FALSE; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { $sql .= ' FETCH FIRST '.($this->qb_limit + $this->qb_offset).' ROWS ONLY'; return ($this->qb_offset) ? 'SELECT * FROM ('.$sql.') WHERE rownum > '.$this->qb_offset : $sql; } } database/drivers/pdo/subdrivers/pdo_mysql_forge.php000064400000014463152270514220016652 0ustar00db->char_set) && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) { $sql .= ' DEFAULT CHARACTER SET = '.$this->db->char_set; } if ( ! empty($this->db->dbcollat) && ! strpos($sql, 'COLLATE')) { $sql .= ' COLLATE = '.$this->db->dbcollat; } return $sql; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP') { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $field[$i] = ($alter_type === 'ADD') ? "\n\tADD ".$field[$i]['_literal'] : "\n\tMODIFY ".$field[$i]['_literal']; } else { if ($alter_type === 'ADD') { $field[$i]['_literal'] = "\n\tADD "; } else { $field[$i]['_literal'] = empty($field[$i]['new_name']) ? "\n\tMODIFY " : "\n\tCHANGE "; } $field[$i] = $field[$i]['_literal'].$this->_process_column($field[$i]); } } return array($sql.implode(',', $field)); } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { $extra_clause = isset($field['after']) ? ' AFTER '.$this->db->escape_identifiers($field['after']) : ''; if (empty($extra_clause) && isset($field['first']) && $field['first'] === TRUE) { $extra_clause = ' FIRST'; } return $this->db->escape_identifiers($field['name']) .(empty($field['new_name']) ? '' : ' '.$this->db->escape_identifiers($field['new_name'])) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['null'] .$field['default'] .$field['auto_increment'] .$field['unique'] .(empty($field['comment']) ? '' : ' COMMENT '.$field['comment']) .$extra_clause; } // -------------------------------------------------------------------- /** * Process indexes * * @param string $table (ignored) * @return string */ protected function _process_indexes($table) { $sql = ''; for ($i = 0, $c = count($this->keys); $i < $c; $i++) { if (is_array($this->keys[$i])) { for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++) { if ( ! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } elseif ( ! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; } is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]); $sql .= ",\n\tKEY ".$this->db->escape_identifiers(implode('_', $this->keys[$i])) .' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).')'; } $this->keys = array(); return $sql; } } database/drivers/pdo/subdrivers/pdo_mysql_driver.php000064400000023611152270514220017036 0ustar00dsn)) { $this->dsn = 'mysql:host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); empty($this->port) OR $this->dsn .= ';port='.$this->port; empty($this->database) OR $this->dsn .= ';dbname='.$this->database; empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set; } elseif ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 6) === FALSE) { $this->dsn .= ';charset='.$this->char_set; } } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { if (isset($this->stricton)) { if ($this->stricton) { $sql = 'CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'; } else { $sql = 'REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @@sql_mode, "STRICT_ALL_TABLES,", ""), ",STRICT_ALL_TABLES", ""), "STRICT_ALL_TABLES", ""), "STRICT_TRANS_TABLES,", ""), ",STRICT_TRANS_TABLES", ""), "STRICT_TRANS_TABLES", "")'; } if ( ! empty($sql)) { if (empty($this->options[PDO::MYSQL_ATTR_INIT_COMMAND])) { $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET SESSION sql_mode = '.$sql; } else { $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] .= ', @@session.sql_mode = '.$sql; } } } if ($this->compress === TRUE) { $this->options[PDO::MYSQL_ATTR_COMPRESS] = TRUE; } if (is_array($this->encrypt)) { $ssl = array(); empty($this->encrypt['ssl_key']) OR $ssl[PDO::MYSQL_ATTR_SSL_KEY] = $this->encrypt['ssl_key']; empty($this->encrypt['ssl_cert']) OR $ssl[PDO::MYSQL_ATTR_SSL_CERT] = $this->encrypt['ssl_cert']; empty($this->encrypt['ssl_ca']) OR $ssl[PDO::MYSQL_ATTR_SSL_CA] = $this->encrypt['ssl_ca']; empty($this->encrypt['ssl_capath']) OR $ssl[PDO::MYSQL_ATTR_SSL_CAPATH] = $this->encrypt['ssl_capath']; empty($this->encrypt['ssl_cipher']) OR $ssl[PDO::MYSQL_ATTR_SSL_CIPHER] = $this->encrypt['ssl_cipher']; if (defined('PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT') && isset($this->encrypt['ssl_verify'])) { $ssl[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = $this->encrypt['ssl_verify']; } // DO NOT use array_merge() here! // It re-indexes numeric keys and the PDO_MYSQL_ATTR_SSL_* constants are integers. empty($ssl) OR $this->options += $ssl; } // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails if ( ($pdo = parent::db_connect($persistent)) !== FALSE && ! empty($ssl) && version_compare($pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), '5.7.3', '<=') && empty($pdo->query("SHOW STATUS LIKE 'ssl_cipher'")->fetchObject()->Value) ) { $message = 'PDO_MYSQL was configured for an SSL connection, but got an unencrypted connection instead!'; log_message('error', $message); return ($this->db_debug) ? $this->display_error($message, '', TRUE) : FALSE; } return $pdo; } // -------------------------------------------------------------------- /** * Select the database * * @param string $database * @return bool */ public function db_select($database = '') { if ($database === '') { $database = $this->database; } if (FALSE !== $this->simple_query('USE '.$this->escape_identifiers($database))) { $this->database = $database; $this->data_cache = array(); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Begin Transaction * * @return bool */ protected function _trans_begin() { $this->conn_id->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE); return $this->conn_id->beginTransaction(); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ protected function _trans_commit() { if ($this->conn_id->commit()) { $this->conn_id->setAttribute(PDO::ATTR_AUTOCOMMIT, TRUE); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ protected function _trans_rollback() { if ($this->conn_id->rollBack()) { $this->conn_id->setAttribute(PDO::ATTR_AUTOCOMMIT, TRUE); return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SHOW TABLES FROM '.$this->_escape_char.$this->database.$this->_escape_char; if ($prefix_limit === TRUE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length ); $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } return $retval; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE '.$table; } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * @return string */ protected function _from_tables() { if ( ! empty($this->qb_join) && count($this->qb_from) > 1) { return '('.implode(', ', $this->qb_from).')'; } return implode(', ', $this->qb_from); } } database/drivers/pdo/subdrivers/pdo_ibm_forge.php000064400000010060152270514220016241 0ustar00 'INTEGER', 'INT' => 'BIGINT', 'INTEGER' => 'BIGINT' ); /** * DEFAULT value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_default = FALSE; // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'CHANGE') { $alter_type = 'MODIFY'; } return parent::_alter_table($alter_type, $table, $field); } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute UNIQUE * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_unique(&$attributes, &$field) { if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE) { $field['unique'] = ' UNIQUE'; // UNIQUE must be used with NOT NULL $field['null'] = ' NOT NULL'; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { // Not supported } } database/drivers/pdo/subdrivers/pdo_4d_driver.php000064400000013175152270514220016204 0ustar00dsn)) { $this->dsn = '4D:host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); empty($this->port) OR $this->dsn .= ';port='.$this->port; empty($this->database) OR $this->dsn .= ';dbname='.$this->database; empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set; } elseif ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 3) === FALSE) { $this->dsn .= ';charset='.$this->char_set; } } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT '.$this->escape_identifiers('TABLE_NAME').' FROM '.$this->escape_identifiers('_USER_TABLES'); if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' WHERE '.$this->escape_identifiers('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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT '.$this->escape_identifiers('COLUMN_NAME').' FROM '.$this->escape_identifiers('_USER_COLUMNS') .' WHERE '.$this->escape_identifiers('TABLE_NAME').' = '.$this->escape($table); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @param string $table * @return string */ protected function _field_data($table) { return 'SELECT * FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE).' LIMIT 1'; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { return $sql.' LIMIT '.$this->qb_limit.($this->qb_offset ? ' OFFSET '.$this->qb_offset : ''); } } database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php000064400000010467152270514220017037 0ustar00 'SMALLINT', 'SMALLINT' => 'INT', 'INT' => 'BIGINT', 'REAL' => 'FLOAT' ); // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ALTER COLUMN '; $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql.$this->_process_column($field[$i]); } return $sqls; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) { unset($attributes['CONSTRAINT']); } switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INTEGER': $attributes['TYPE'] = 'INT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' IDENTITY(1,1)'; } } } database/drivers/pdo/subdrivers/pdo_pgsql_driver.php000064400000023133152270514220017016 0ustar00dsn)) { $this->dsn = 'pgsql:host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); empty($this->port) OR $this->dsn .= ';port='.$this->port; empty($this->database) OR $this->dsn .= ';dbname='.$this->database; if ( ! empty($this->username)) { $this->dsn .= ';user='.$this->username; empty($this->password) OR $this->dsn .= ';password='.$this->password; } } } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { $this->conn_id = parent::db_connect($persistent); if (is_object($this->conn_id) && ! empty($this->schema)) { $this->simple_query('SET search_path TO '.$this->schema.',public'); } return $this->conn_id; } // -------------------------------------------------------------------- /** * Insert ID * * @param string $name * @return int */ public function insert_id($name = NULL) { if ($name === NULL && version_compare($this->version(), '8.1', '>=')) { $query = $this->query('SELECT LASTVAL() AS ins_id'); $query = $query->row(); return $query->ins_id; } return $this->conn_id->lastInsertId($name); } // -------------------------------------------------------------------- /** * Determines if a query is a "write" type. * * @param string An SQL query string * @return bool */ public function is_write_type($sql) { if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql)) { return FALSE; } return parent::is_write_type($sql); } // -------------------------------------------------------------------- /** * "Smart" Escape String * * Escapes data based on type * * @param string $str * @return mixed */ public function escape($str) { if (is_bool($str)) { return ($str) ? 'TRUE' : 'FALSE'; } return parent::escape($str); } // -------------------------------------------------------------------- /** * ORDER BY * * @param string $orderby * @param string $direction ASC, DESC or RANDOM * @param bool $escape * @return object */ public function order_by($orderby, $direction = '', $escape = NULL) { $direction = strtoupper(trim($direction)); if ($direction === 'RANDOM') { if ( ! is_float($orderby) && ctype_digit((string) $orderby)) { $orderby = ($orderby > 1) ? (float) '0.'.$orderby : (float) $orderby; } if (is_float($orderby)) { $this->simple_query('SET SEED '.$orderby); } $orderby = $this->_random_keyword[0]; $direction = ''; $escape = FALSE; } return parent::order_by($orderby, $direction, $escape); } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \''.$this->schema."'"; if ($prefix_limit === TRUE && $this->dbprefix !== '') { return $sql.' AND "table_name" LIKE \'' .$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * List column query * * Generates a platform-specific query string so that the column names can be fetched * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT "column_name" FROM "information_schema"."columns" WHERE "table_schema" = \''.$this->schema.'\' AND LOWER("table_name") = '.$this->escape(strtolower($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT "column_name", "data_type", "character_maximum_length", "numeric_precision", "column_default" FROM "information_schema"."columns" WHERE "table_schema" = \''.$this->schema.'\' AND LOWER("table_name") = '.$this->escape(strtolower($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->column_name; $retval[$i]->type = $query[$i]->data_type; $retval[$i]->max_length = ($query[$i]->character_maximum_length > 0) ? $query[$i]->character_maximum_length : $query[$i]->numeric_precision; $retval[$i]->default = $query[$i]->column_default; } return $retval; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @param string $table Table name * @param array $values Update data * @param string $index WHERE key * @return string */ protected function _update_batch($table, $values, $index) { $ids = array(); foreach ($values as $key => $val) { $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = (CASE '.$val[$index]['field']."\n" .implode("\n", $v)."\n" .'ELSE '.$k.' END), '; } $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { return $sql.' LIMIT '.$this->qb_limit.($this->qb_offset ? ' OFFSET '.$this->qb_offset : ''); } } database/drivers/pdo/subdrivers/pdo_odbc_driver.php000064400000013511152270514220016576 0ustar00dsn)) { $this->dsn = 'odbc:'; // Pre-defined DSN if (empty($this->hostname) && empty($this->HOSTNAME) && empty($this->port) && empty($this->PORT)) { if (isset($this->DSN)) { $this->dsn .= 'DSN='.$this->DSN; } elseif ( ! empty($this->database)) { $this->dsn .= 'DSN='.$this->database; } return; } // If the DSN is not pre-configured - try to build an IBM DB2 connection string $this->dsn .= 'DRIVER='.(isset($this->DRIVER) ? '{'.$this->DRIVER.'}' : '{IBM DB2 ODBC DRIVER}').';'; if (isset($this->DATABASE)) { $this->dsn .= 'DATABASE='.$this->DATABASE.';'; } elseif ( ! empty($this->database)) { $this->dsn .= 'DATABASE='.$this->database.';'; } if (isset($this->HOSTNAME)) { $this->dsn .= 'HOSTNAME='.$this->HOSTNAME.';'; } else { $this->dsn .= 'HOSTNAME='.(empty($this->hostname) ? '127.0.0.1;' : $this->hostname.';'); } if (isset($this->PORT)) { $this->dsn .= 'PORT='.$this->port.';'; } elseif ( ! empty($this->port)) { $this->dsn .= ';PORT='.$this->port.';'; } $this->dsn .= 'PROTOCOL='.(isset($this->PROTOCOL) ? $this->PROTOCOL.';' : 'TCPIP;'); } } // -------------------------------------------------------------------- /** * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { $this->display_error('db_unsupported_feature'); } // -------------------------------------------------------------------- /** * Determines if a query is a "write" type. * * @param string An SQL query string * @return bool */ public function is_write_type($sql) { if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql)) { return FALSE; } return parent::is_write_type($sql); } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '".$this->schema."'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT column_name FROM information_schema.columns WHERE table_name = '.$this->escape($table); } } database/drivers/pdo/subdrivers/pdo_4d_forge.php000064400000012501152270514220016003 0ustar00 'INT', 'SMALLINT' => 'INT', 'INT' => 'INT64', 'INT32' => 'INT64' ); /** * DEFAULT value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_default = FALSE; // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('ADD', 'DROP'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } // No method of modifying columns is supported return FALSE; } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['null'] .$field['unique'] .$field['auto_increment']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'INTEGER': $attributes['TYPE'] = 'INT'; return; case 'BIGINT': $attributes['TYPE'] = 'INT64'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute UNIQUE * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_unique(&$attributes, &$field) { if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE) { $field['unique'] = ' UNIQUE'; // UNIQUE must be used with NOT NULL $field['null'] = ' NOT NULL'; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) { if (stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' AUTO_INCREMENT'; } elseif (strcasecmp($field['type'], 'UUID') === 0) { $field['auto_increment'] = ' AUTO_GENERATE'; } } } } database/drivers/pdo/subdrivers/pdo_oci_driver.php000064400000020557152270514220016451 0ustar00dsn)) { $this->dsn = 'oci:dbname='; // Oracle has a slightly different PDO DSN format (Easy Connect), // which also supports pre-defined DSNs. if (empty($this->hostname) && empty($this->port)) { $this->dsn .= $this->database; } else { $this->dsn .= '//'.(empty($this->hostname) ? '127.0.0.1' : $this->hostname) .(empty($this->port) ? '' : ':'.$this->port).'/'; empty($this->database) OR $this->dsn .= $this->database; } empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set; } elseif ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 4) === FALSE) { $this->dsn .= ';charset='.$this->char_set; } } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } $version_string = parent::version(); if (preg_match('#(Release\s)?(?\d+(?:\.\d+)+)#', $version_string, $match)) { return $this->data_cache['version'] = $match['version']; } return FALSE; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "TABLE_NAME" FROM "ALL_TABLES"'; if ($prefix_limit === TRUE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } else { $owner = $this->username; } return 'SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE UPPER(OWNER) = '.$this->escape(strtoupper($owner)).' AND UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } else { $owner = $this->username; } $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHAR_LENGTH, DATA_PRECISION, DATA_LENGTH, DATA_DEFAULT, NULLABLE FROM ALL_TAB_COLUMNS WHERE UPPER(OWNER) = '.$this->escape(strtoupper($owner)).' AND UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $length = ($query[$i]->CHAR_LENGTH > 0) ? $query[$i]->CHAR_LENGTH : $query[$i]->DATA_PRECISION; if ($length === NULL) { $length = $query[$i]->DATA_LENGTH; } $retval[$i]->max_length = $length; $default = $query[$i]->DATA_DEFAULT; if ($default === NULL && $query[$i]->NULLABLE === 'N') { $default = ''; } $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; } return $retval; } // -------------------------------------------------------------------- /** * Insert batch statement * * @param string $table Table name * @param array $keys INSERT keys * @param array $values 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"; } return $sql.'SELECT * FROM dual'; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { if ($this->qb_limit) { $this->where('rownum <= ',$this->qb_limit, FALSE); $this->qb_limit = FALSE; } return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { if (version_compare($this->version(), '12.1', '>=')) { // OFFSET-FETCH can be used only with the ORDER BY clause empty($this->qb_orderby) && $sql .= ' ORDER BY 1'; return $sql.' OFFSET '.(int) $this->qb_offset.' ROWS FETCH NEXT '.$this->qb_limit.' ROWS ONLY'; } return 'SELECT * FROM (SELECT inner_query.*, rownum rnum FROM ('.$sql.') inner_query WHERE rownum < '.($this->qb_offset + $this->qb_limit + 1).')' .($this->qb_offset ? ' WHERE rnum >= '.($this->qb_offset + 1): ''); } } database/drivers/pdo/subdrivers/pdo_sqlite_forge.php000064400000014146152270514220017004 0ustar00db->version(), '3.3', '<')) { $this->_create_table_if = FALSE; $this->_drop_table_if = FALSE; } } // -------------------------------------------------------------------- /** * Create database * * @param string $db_name (ignored) * @return bool */ public function create_database($db_name) { // In SQLite, a database is created when you connect to the database. // We'll return TRUE so that an error isn't generated return TRUE; } // -------------------------------------------------------------------- /** * Drop database * * @param string $db_name (ignored) * @return bool */ public function drop_database($db_name) { // In SQLite, a database is dropped when we delete a file if (file_exists($this->db->database)) { // We need to close the pseudo-connection first $this->db->close(); if ( ! @unlink($this->db->database)) { return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE; } elseif ( ! empty($this->db->data_cache['db_names'])) { $key = array_search(strtolower($this->db->database), array_map('strtolower', $this->db->data_cache['db_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['db_names'][$key]); } } return TRUE; } return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if ($alter_type === 'DROP' OR $alter_type === 'CHANGE') { // drop_column(): // BEGIN TRANSACTION; // CREATE TEMPORARY TABLE t1_backup(a,b); // INSERT INTO t1_backup SELECT a,b FROM t1; // DROP TABLE t1; // CREATE TABLE t1(a,b); // INSERT INTO t1 SELECT a,b FROM t1_backup; // DROP TABLE t1_backup; // COMMIT; return FALSE; } return parent::_alter_table($alter_type, $table, $field); } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'] .$field['auto_increment'] .$field['null'] .$field['unique'] .$field['default']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'ENUM': case 'SET': $attributes['TYPE'] = 'TEXT'; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['type'] = 'INTEGER PRIMARY KEY'; $field['default'] = ''; $field['null'] = ''; $field['unique'] = ''; $field['auto_increment'] = ' AUTOINCREMENT'; $this->primary_keys = array(); } } } database/drivers/pdo/subdrivers/index.html000064400000000203152270514220014730 0ustar00 403 Forbidden

Directory access is forbidden.

database/drivers/pdo/subdrivers/pdo_pgsql_forge.php000064400000013550152270514220016627 0ustar00 'INTEGER', 'SMALLINT' => 'INTEGER', 'INT' => 'BIGINT', 'INT4' => 'BIGINT', 'INTEGER' => 'BIGINT', 'INT8' => 'NUMERIC', 'BIGINT' => 'NUMERIC', 'REAL' => 'DOUBLE PRECISION', 'FLOAT' => 'DOUBLE PRECISION' ); /** * NULL value representation in CREATE/ALTER TABLE statements * * @var string */ protected $_null = 'NULL'; // -------------------------------------------------------------------- /** * Class constructor * * @param object &$db Database object * @return void */ public function __construct(&$db) { parent::__construct($db); if (version_compare($this->db->version(), '9.0', '>')) { $this->create_table_if = 'CREATE TABLE IF NOT EXISTS'; } } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('DROP', 'ADD'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { return FALSE; } if (version_compare($this->db->version(), '8', '>=') && isset($field[$i]['type'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TYPE '.$field[$i]['type'].$field[$i]['length']; } if ( ! empty($field[$i]['default'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' SET '.$field[$i]['default']; } if (isset($field[$i]['null'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .(trim($field[$i]['null']) === $this->_null ? ' DROP NOT NULL' : ' SET NOT NULL'); } if ( ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' RENAME COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } if ( ! empty($field[$i]['comment'])) { $sqls[] = 'COMMENT ON COLUMN ' .$this->db->escape_identifiers($table).'.'.$this->db->escape_identifiers($field[$i]['name']) .' IS '.$field[$i]['comment']; } } return $sqls; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { // Reset field lengths for data types that don't support it if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== FALSE) { $attributes['CONSTRAINT'] = NULL; } switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; default: return; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) { $field['type'] = ($field['type'] === 'NUMERIC') ? 'BIGSERIAL' : 'SERIAL'; } } } database/drivers/pdo/subdrivers/pdo_dblib_driver.php000064400000024076152270514220016753 0ustar00dsn)) { $this->dsn = $params['subdriver'].':host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); if ( ! empty($this->port)) { $this->dsn .= (DIRECTORY_SEPARATOR === '\\' ? ',' : ':').$this->port; } empty($this->database) OR $this->dsn .= ';dbname='.$this->database; empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set; empty($this->appname) OR $this->dsn .= ';appname='.$this->appname; } else { if ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 6) === FALSE) { $this->dsn .= ';charset='.$this->char_set; } $this->subdriver = 'dblib'; } } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { if ($persistent === TRUE) { log_message('debug', "dblib driver doesn't support persistent connections"); } $this->conn_id = parent::db_connect(FALSE); if ( ! is_object($this->conn_id)) { return $this->conn_id; } // Determine how identifiers are escaped $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi'); $query = $query->row_array(); $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi']; $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']'); return $this->conn_id; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql.' ORDER BY '.$this->escape_identifiers('name'); } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION; $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; } return $retval; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { if ($this->qb_limit) { return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete'; } return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { $limit = $this->qb_offset + $this->qb_limit; // As of SQL Server 2005 (9.0.*) ROW_NUMBER() is supported, // however an ORDER BY clause is required for it to work if (version_compare($this->version(), '9', '>=') && $this->qb_offset && ! empty($this->qb_orderby)) { $orderby = $this->_compile_order_by(); // We have to strip the ORDER BY clause $sql = trim(substr($sql, 0, strrpos($sql, $orderby))); // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } else { // Use only field names and their aliases, everything else is out of our scope. $select = array(); $field_regexp = ($this->_quoted_identifier) ? '("[^\"]+")' : '(\[[^\]]+\])'; for ($i = 0, $c = count($this->qb_select); $i < $c; $i++) { $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m) ? $m[1] : $this->qb_select[$i]; } $select = implode(', ', $select); } return 'SELECT '.$select." FROM (\n\n" .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql) ."\n\n) ".$this->escape_identifiers('CI_subquery') ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit; } return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string|bool */ protected function _insert_batch($table, $keys, $values) { // Multiple-value inserts are only supported as of SQL Server 2008 if (version_compare($this->version(), '10', '>=')) { return parent::_insert_batch($table, $keys, $values); } return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } return $this->data_cache['version'] = $this->conn_id->query("SELECT SERVERPROPERTY('ProductVersion') AS ver")->fetchColumn(0); } } database/drivers/pdo/subdrivers/pdo_oci_forge.php000064400000012670152270514220016255 0ustar00db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $field[$i] = "\n\t".$field[$i]['_literal']; } else { $field[$i]['_literal'] = "\n\t".$this->_process_column($field[$i]); if ( ! empty($field[$i]['comment'])) { $sqls[] = 'COMMENT ON COLUMN ' .$this->db->escape_identifiers($table).'.'.$this->db->escape_identifiers($field[$i]['name']) .' IS '.$field[$i]['comment']; } if ($alter_type === 'MODIFY' && ! empty($field[$i]['new_name'])) { $sqls[] = $sql.' RENAME COLUMN '.$this->db->escape_identifiers($field[$i]['name']) .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } } } $sql .= ' '.$alter_type.' '; $sql .= (count($field) === 1) ? $field[0] : '('.implode(',', $field).')'; // RENAME COLUMN must be executed after MODIFY array_unshift($sqls, $sql); return $sql; } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'number') !== FALSE && version_compare($this->db->version(), '12.1', '>=')) { $field['auto_increment'] = ' GENERATED ALWAYS AS IDENTITY'; } } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['default'] .$field['auto_increment'] .$field['null'] .$field['unique']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'NUMBER'; return; case 'MEDIUMINT': $attributes['TYPE'] = 'NUMBER'; return; case 'INT': $attributes['TYPE'] = 'NUMBER'; return; case 'BIGINT': $attributes['TYPE'] = 'NUMBER'; return; default: return; } } } database/drivers/pdo/subdrivers/pdo_cubrid_forge.php000064400000013441152270514220016750 0ustar00 'INTEGER', 'SMALLINT' => 'INTEGER', 'INT' => 'BIGINT', 'INTEGER' => 'BIGINT', 'BIGINT' => 'NUMERIC', 'FLOAT' => 'DOUBLE', 'REAL' => 'DOUBLE' ); // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { if (in_array($alter_type, array('DROP', 'ADD'), TRUE)) { return parent::_alter_table($alter_type, $table, $field); } $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table); $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { if ($field[$i]['_literal'] !== FALSE) { $sqls[] = $sql.' CHANGE '.$field[$i]['_literal']; } else { $alter_type = empty($field[$i]['new_name']) ? ' MODIFY ' : ' CHANGE '; $sqls[] = $sql.$alter_type.$this->_process_column($field[$i]); } } return $sqls; } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { $extra_clause = isset($field['after']) ? ' AFTER '.$this->db->escape_identifiers($field['after']) : ''; if (empty($extra_clause) && isset($field['first']) && $field['first'] === TRUE) { $extra_clause = ' FIRST'; } return $this->db->escape_identifiers($field['name']) .(empty($field['new_name']) ? '' : ' '.$this->db->escape_identifiers($field['new_name'])) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['null'] .$field['default'] .$field['auto_increment'] .$field['unique'] .$extra_clause; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { switch (strtoupper($attributes['TYPE'])) { case 'TINYINT': $attributes['TYPE'] = 'SMALLINT'; $attributes['UNSIGNED'] = FALSE; return; case 'MEDIUMINT': $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; case 'LONGTEXT': $attributes['TYPE'] = 'STRING'; return; default: return; } } // -------------------------------------------------------------------- /** * Process indexes * * @param string $table (ignored) * @return string */ protected function _process_indexes($table) { $sql = ''; for ($i = 0, $c = count($this->keys); $i < $c; $i++) { if (is_array($this->keys[$i])) { for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++) { if ( ! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } elseif ( ! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; } is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]); $sql .= ",\n\tKEY ".$this->db->escape_identifiers(implode('_', $this->keys[$i])) .' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).')'; } $this->keys = array(); return $sql; } } database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php000064400000025412152270514220017224 0ustar00dsn)) { $this->dsn = 'sqlsrv:Server='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); empty($this->port) OR $this->dsn .= ','.$this->port; empty($this->database) OR $this->dsn .= ';Database='.$this->database; // Some custom options if (isset($this->QuotedId)) { $this->dsn .= ';QuotedId='.$this->QuotedId; $this->_quoted_identifier = (bool) $this->QuotedId; } if (isset($this->ConnectionPooling)) { $this->dsn .= ';ConnectionPooling='.$this->ConnectionPooling; } if ($this->encrypt === TRUE) { $this->dsn .= ';Encrypt=1'; } if (isset($this->TraceOn)) { $this->dsn .= ';TraceOn='.$this->TraceOn; } if (isset($this->TrustServerCertificate)) { $this->dsn .= ';TrustServerCertificate='.$this->TrustServerCertificate; } empty($this->APP) OR $this->dsn .= ';APP='.$this->APP; empty($this->Failover_Partner) OR $this->dsn .= ';Failover_Partner='.$this->Failover_Partner; empty($this->LoginTimeout) OR $this->dsn .= ';LoginTimeout='.$this->LoginTimeout; empty($this->MultipleActiveResultSets) OR $this->dsn .= ';MultipleActiveResultSets='.$this->MultipleActiveResultSets; empty($this->TraceFile) OR $this->dsn .= ';TraceFile='.$this->TraceFile; empty($this->WSID) OR $this->dsn .= ';WSID='.$this->WSID; } elseif (preg_match('/QuotedId=(0|1)/', $this->dsn, $match)) { $this->_quoted_identifier = (bool) $match[1]; } } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { if ( ! empty($this->char_set) && preg_match('/utf[^8]*8/i', $this->char_set)) { $this->options[PDO::SQLSRV_ENCODING_UTF8] = 1; } $this->conn_id = parent::db_connect($persistent); if ( ! is_object($this->conn_id) OR is_bool($this->_quoted_identifier)) { return $this->conn_id; } // Determine how identifiers are escaped $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi'); $query = $query->row_array(); $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi']; $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']'); return $this->conn_id; } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql.' ORDER BY '.$this->escape_identifiers('name'); } // -------------------------------------------------------------------- /** * Show column query * * Generates a platform-specific query string so that the column names can be fetched * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.Columns WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table)); if (($query = $this->query($sql)) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->COLUMN_NAME; $retval[$i]->type = $query[$i]->DATA_TYPE; $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION; $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; } return $retval; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { if ($this->qb_limit) { return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete'; } return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { // As of SQL Server 2012 (11.0.*) OFFSET is supported if (version_compare($this->version(), '11', '>=')) { // SQL Server OFFSET-FETCH can be used only with the ORDER BY clause empty($this->qb_orderby) && $sql .= ' ORDER BY 1'; return $sql.' OFFSET '.(int) $this->qb_offset.' ROWS FETCH NEXT '.$this->qb_limit.' ROWS ONLY'; } $limit = $this->qb_offset + $this->qb_limit; // An ORDER BY clause is required for ROW_NUMBER() to work if ($this->qb_offset && ! empty($this->qb_orderby)) { $orderby = $this->_compile_order_by(); // We have to strip the ORDER BY clause $sql = trim(substr($sql, 0, strrpos($sql, $orderby))); // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } else { // Use only field names and their aliases, everything else is out of our scope. $select = array(); $field_regexp = ($this->_quoted_identifier) ? '("[^\"]+")' : '(\[[^\]]+\])'; for ($i = 0, $c = count($this->qb_select); $i < $c; $i++) { $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m) ? $m[1] : $this->qb_select[$i]; } $select = implode(', ', $select); } return 'SELECT '.$select." FROM (\n\n" .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql) ."\n\n) ".$this->escape_identifiers('CI_subquery') ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit; } return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql); } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string|bool */ protected function _insert_batch($table, $keys, $values) { // Multiple-value inserts are only supported as of SQL Server 2008 if (version_compare($this->version(), '10', '>=')) { return parent::_insert_batch($table, $keys, $values); } return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } } database/drivers/pdo/subdrivers/pdo_informix_driver.php000064400000020616152270514220017526 0ustar00dsn)) { $this->dsn = 'informix:'; // Pre-defined DSN if (empty($this->hostname) && empty($this->host) && empty($this->port) && empty($this->service)) { if (isset($this->DSN)) { $this->dsn .= 'DSN='.$this->DSN; } elseif ( ! empty($this->database)) { $this->dsn .= 'DSN='.$this->database; } return; } if (isset($this->host)) { $this->dsn .= 'host='.$this->host; } else { $this->dsn .= 'host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); } if (isset($this->service)) { $this->dsn .= '; service='.$this->service; } elseif ( ! empty($this->port)) { $this->dsn .= '; service='.$this->port; } empty($this->database) OR $this->dsn .= '; database='.$this->database; empty($this->server) OR $this->dsn .= '; server='.$this->server; $this->dsn .= '; protocol='.(isset($this->protocol) ? $this->protocol : 'onsoctcp') .'; EnableScrollableCursors=1'; } } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "tabname" FROM "systables" WHERE "tabid" > 99 AND "tabtype" = \'T\' AND LOWER("owner") = '.$this->escape(strtolower($this->username)); if ($prefix_limit === TRUE && $this->dbprefix !== '') { $sql .= ' AND "tabname" 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 * * @param string $table * @return string */ protected function _list_columns($table = '') { if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } else { $owner = $this->username; } return 'SELECT "colname" FROM "systables", "syscolumns" WHERE "systables"."tabid" = "syscolumns"."tabid" AND "systables"."tabtype" = \'T\' AND LOWER("systables"."owner") = '.$this->escape(strtolower($owner)).' AND LOWER("systables"."tabname") = '.$this->escape(strtolower($table)); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { $sql = 'SELECT "syscolumns"."colname" AS "name", CASE "syscolumns"."coltype" WHEN 0 THEN \'CHAR\' WHEN 1 THEN \'SMALLINT\' WHEN 2 THEN \'INTEGER\' WHEN 3 THEN \'FLOAT\' WHEN 4 THEN \'SMALLFLOAT\' WHEN 5 THEN \'DECIMAL\' WHEN 6 THEN \'SERIAL\' WHEN 7 THEN \'DATE\' WHEN 8 THEN \'MONEY\' WHEN 9 THEN \'NULL\' WHEN 10 THEN \'DATETIME\' WHEN 11 THEN \'BYTE\' WHEN 12 THEN \'TEXT\' WHEN 13 THEN \'VARCHAR\' WHEN 14 THEN \'INTERVAL\' WHEN 15 THEN \'NCHAR\' WHEN 16 THEN \'NVARCHAR\' WHEN 17 THEN \'INT8\' WHEN 18 THEN \'SERIAL8\' WHEN 19 THEN \'SET\' WHEN 20 THEN \'MULTISET\' WHEN 21 THEN \'LIST\' WHEN 22 THEN \'Unnamed ROW\' WHEN 40 THEN \'LVARCHAR\' WHEN 41 THEN \'BLOB/CLOB/BOOLEAN\' WHEN 4118 THEN \'Named ROW\' ELSE "syscolumns"."coltype" END AS "type", "syscolumns"."collength" as "max_length", CASE "sysdefaults"."type" WHEN \'L\' THEN "sysdefaults"."default" ELSE NULL END AS "default" FROM "syscolumns", "systables", "sysdefaults" WHERE "syscolumns"."tabid" = "systables"."tabid" AND "systables"."tabid" = "sysdefaults"."tabid" AND "syscolumns"."colno" = "sysdefaults"."colno" AND "systables"."tabtype" = \'T\' AND LOWER("systables"."owner") = '.$this->escape(strtolower($this->username)).' AND LOWER("systables"."tabname") = '.$this->escape(strtolower($table)).' ORDER BY "syscolumns"."colno"'; return (($query = $this->query($sql)) !== FALSE) ? $query->result_object() : FALSE; } // -------------------------------------------------------------------- /** * Update statement * * Generates a platform-specific update string from the supplied data * * @param string $table * @param array $values * @return string */ protected function _update($table, $values) { $this->qb_limit = FALSE; $this->qb_orderby = array(); return parent::_update($table, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE TABLE ONLY '.$table; } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string $table * @return string */ protected function _delete($table) { $this->qb_limit = FALSE; return parent::_delete($table); } // -------------------------------------------------------------------- /** * LIMIT * * Generates a platform-specific LIMIT clause * * @param string $sql $SQL Query * @return string */ protected function _limit($sql) { $select = 'SELECT '.($this->qb_offset ? 'SKIP '.$this->qb_offset : '').'FIRST '.$this->qb_limit.' '; return preg_replace('/^(SELECT\s)/i', $select, $sql, 1); } } database/drivers/pdo/subdrivers/pdo_cubrid_driver.php000064400000012756152270514220017151 0ustar00dsn)) { $this->dsn = 'cubrid:host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname); empty($this->port) OR $this->dsn .= ';port='.$this->port; empty($this->database) OR $this->dsn .= ';dbname='.$this->database; empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set; } } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SHOW TABLES'; if ($prefix_limit === TRUE && $this->dbprefix !== '') { return $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 * * @param string $table * @return string */ protected function _list_columns($table = '') { return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE); } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; } $query = $query->result_object(); $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length ); $retval[$i]->default = $query[$i]->Default; $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); } return $retval; } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE '.$table; } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * @return string */ protected function _from_tables() { if ( ! empty($this->qb_join) && count($this->qb_from) > 1) { return '('.implode(', ', $this->qb_from).')'; } return implode(', ', $this->qb_from); } } database/drivers/pdo/subdrivers/pdo_sqlite_driver.php000064400000013125152270514220017171 0ustar00dsn)) { $this->dsn = 'sqlite:'; if (empty($this->database) && empty($this->hostname)) { $this->database = ':memory:'; } $this->database = empty($this->database) ? $this->hostname : $this->database; } } // -------------------------------------------------------------------- /** * Show table query * * Generates a platform-specific query string so that the table names can be fetched * * @param bool $prefix_limit * @return string */ protected function _list_tables($prefix_limit = FALSE) { $sql = 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''; if ($prefix_limit === TRUE && $this->dbprefix !== '') { return $sql.' AND "NAME" LIKE \''.$this->escape_like_str($this->dbprefix)."%' " .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; } // -------------------------------------------------------------------- /** * Fetch Field Names * * @param string $table Table name * @return array */ public function list_fields($table) { if (($result = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; } $fields = array(); foreach ($result->result_array() as $row) { $fields[] = $row['name']; } return $fields; } // -------------------------------------------------------------------- /** * Returns an object with field data * * @param string $table * @return array */ public function field_data($table) { if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; } $query = $query->result_array(); if (empty($query)) { return FALSE; } $retval = array(); for ($i = 0, $c = count($query); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $query[$i]['name']; $retval[$i]->type = $query[$i]['type']; $retval[$i]->max_length = NULL; $retval[$i]->default = $query[$i]['dflt_value']; $retval[$i]->primary_key = isset($query[$i]['pk']) ? (int) $query[$i]['pk'] : 0; } return $retval; } // -------------------------------------------------------------------- /** * Replace statement * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string */ protected function _replace($table, $keys, $values) { return 'INSERT OR '.parent::_replace($table, $keys, $values); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'DELETE FROM '.$table; } } database/drivers/pdo/subdrivers/pdo_odbc_forge.php000064400000004534152270514220016412 0ustar00db =& $db; log_message('info', 'Database Forge Class Initialized'); } // -------------------------------------------------------------------- /** * Create database * * @param string $db_name * @return bool */ public function create_database($db_name) { if ($this->_create_database === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } elseif ( ! $this->db->query(sprintf($this->_create_database, $this->db->escape_identifiers($db_name), $this->db->char_set, $this->db->dbcollat))) { return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE; } if ( ! empty($this->db->data_cache['db_names'])) { $this->db->data_cache['db_names'][] = $db_name; } return TRUE; } // -------------------------------------------------------------------- /** * Drop database * * @param string $db_name * @return bool */ public function drop_database($db_name) { if ($this->_drop_database === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } elseif ( ! $this->db->query(sprintf($this->_drop_database, $this->db->escape_identifiers($db_name)))) { return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE; } if ( ! empty($this->db->data_cache['db_names'])) { $key = array_search(strtolower($db_name), array_map('strtolower', $this->db->data_cache['db_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['db_names'][$key]); } } return TRUE; } // -------------------------------------------------------------------- /** * Add Key * * @param string $key * @param bool $primary * @return CI_DB_forge */ public function add_key($key, $primary = FALSE) { // DO NOT change this! This condition is only applicable // for PRIMARY keys because you can only have one such, // and therefore all fields you add to it will be included // in the same, composite PRIMARY KEY. // // It's not the same for regular indexes. if ($primary === TRUE && is_array($key)) { foreach ($key as $one) { $this->add_key($one, $primary); } return $this; } if ($primary === TRUE) { $this->primary_keys[] = $key; } else { $this->keys[] = $key; } return $this; } // -------------------------------------------------------------------- /** * Add Field * * @param array $field * @return CI_DB_forge */ public function add_field($field) { 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); } return $this; } // -------------------------------------------------------------------- /** * Create Table * * @param string $table Table name * @param bool $if_not_exists Whether to add IF NOT EXISTS condition * @param array $attributes Associative array of table attributes * @return bool */ public function create_table($table, $if_not_exists = FALSE, array $attributes = array()) { if ($table === '') { show_error('A table name is required for that operation.'); } else { $table = $this->db->dbprefix.$table; } if (count($this->fields) === 0) { show_error('Field information is required.'); } $sql = $this->_create_table($table, $if_not_exists, $attributes); if (is_bool($sql)) { $this->_reset(); if ($sql === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } } if (($result = $this->db->query($sql)) !== FALSE) { if (isset($this->db->data_cache['table_names'])) { $this->db->data_cache['table_names'][] = $table; } // Most databases don't support creating indexes from within the CREATE TABLE statement if ( ! empty($this->keys)) { for ($i = 0, $sqls = $this->_process_indexes($table), $c = count($sqls); $i < $c; $i++) { $this->db->query($sqls[$i]); } } } $this->_reset(); return $result; } // -------------------------------------------------------------------- /** * Create Table * * @param string $table Table name * @param bool $if_not_exists Whether to add 'IF NOT EXISTS' condition * @param array $attributes Associative array of table attributes * @return mixed */ protected function _create_table($table, $if_not_exists, $attributes) { if ($if_not_exists === TRUE && $this->_create_table_if === FALSE) { if ($this->db->table_exists($table)) { return TRUE; } $if_not_exists = FALSE; } $sql = ($if_not_exists) ? sprintf($this->_create_table_if, $this->db->escape_identifiers($table)) : 'CREATE TABLE'; $columns = $this->_process_fields(TRUE); for ($i = 0, $c = count($columns); $i < $c; $i++) { $columns[$i] = ($columns[$i]['_literal'] !== FALSE) ? "\n\t".$columns[$i]['_literal'] : "\n\t".$this->_process_column($columns[$i]); } $columns = implode(',', $columns) .$this->_process_primary_keys($table); // Are indexes created from within the CREATE TABLE statement? (e.g. in MySQL) if ($this->_create_table_keys === TRUE) { $columns .= $this->_process_indexes($table); } // _create_table will usually have the following format: "%s %s (%s\n)" $sql = sprintf($this->_create_table.'%s', $sql, $this->db->escape_identifiers($table), $columns, $this->_create_table_attr($attributes) ); return $sql; } // -------------------------------------------------------------------- /** * CREATE TABLE attributes * * @param array $attributes Associative array of table attributes * @return string */ protected function _create_table_attr($attributes) { $sql = ''; foreach (array_keys($attributes) as $key) { if (is_string($key)) { $sql .= ' '.strtoupper($key).' '.$attributes[$key]; } } return $sql; } // -------------------------------------------------------------------- /** * Drop Table * * @param string $table_name Table name * @param bool $if_exists Whether to add an IF EXISTS condition * @return bool */ public function drop_table($table_name, $if_exists = FALSE) { if ($table_name === '') { return ($this->db->db_debug) ? $this->db->display_error('db_table_name_required') : FALSE; } if (($query = $this->_drop_table($this->db->dbprefix.$table_name, $if_exists)) === TRUE) { return TRUE; } $query = $this->db->query($query); // Update table list cache if ($query && ! empty($this->db->data_cache['table_names'])) { $key = array_search(strtolower($this->db->dbprefix.$table_name), array_map('strtolower', $this->db->data_cache['table_names']), TRUE); if ($key !== FALSE) { unset($this->db->data_cache['table_names'][$key]); } } return $query; } // -------------------------------------------------------------------- /** * Drop Table * * Generates a platform-specific DROP TABLE string * * @param string $table Table name * @param bool $if_exists Whether to add an IF EXISTS condition * @return mixed (Returns a platform-specific DROP table string, or TRUE to indicate there's nothing to do) */ protected function _drop_table($table, $if_exists) { $sql = 'DROP TABLE'; if ($if_exists) { if ($this->_drop_table_if === FALSE) { if ( ! $this->db->table_exists($table)) { return TRUE; } } else { $sql = sprintf($this->_drop_table_if, $this->db->escape_identifiers($table)); } } return $sql.' '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- /** * Rename Table * * @param string $table_name Old table name * @param string $new_table_name New table name * @return bool */ public 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.'); return FALSE; } elseif ($this->_rename_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $result = $this->db->query(sprintf($this->_rename_table, $this->db->escape_identifiers($this->db->dbprefix.$table_name), $this->db->escape_identifiers($this->db->dbprefix.$new_table_name)) ); if ($result && ! empty($this->db->data_cache['table_names'])) { $key = array_search(strtolower($this->db->dbprefix.$table_name), array_map('strtolower', $this->db->data_cache['table_names']), TRUE); if ($key !== FALSE) { $this->db->data_cache['table_names'][$key] = $this->db->dbprefix.$new_table_name; } } return $result; } // -------------------------------------------------------------------- /** * Column Add * * @todo Remove deprecated $_after option in 3.1+ * @param string $table Table name * @param array $field Column definition * @param string $_after Column for AFTER clause (deprecated) * @return bool */ public function add_column($table, $field, $_after = NULL) { // Work-around for literal column definitions is_array($field) OR $field = array($field); foreach (array_keys($field) as $k) { // Backwards-compatibility work-around for MySQL/CUBRID AFTER clause (remove in 3.1+) if ($_after !== NULL && is_array($field[$k]) && ! isset($field[$k]['after'])) { $field[$k]['after'] = $_after; } $this->add_field(array($k => $field[$k])); } $sqls = $this->_alter_table('ADD', $this->db->dbprefix.$table, $this->_process_fields()); $this->_reset(); if ($sqls === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } for ($i = 0, $c = count($sqls); $i < $c; $i++) { if ($this->db->query($sqls[$i]) === FALSE) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Column Drop * * @param string $table Table name * @param string $column_name Column name * @return bool */ public function drop_column($table, $column_name) { $sql = $this->_alter_table('DROP', $this->db->dbprefix.$table, $column_name); if ($sql === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } return $this->db->query($sql); } // -------------------------------------------------------------------- /** * Column Modify * * @param string $table Table name * @param string $field Column definition * @return bool */ public function modify_column($table, $field) { // Work-around for literal column definitions is_array($field) OR $field = array($field); foreach (array_keys($field) as $k) { $this->add_field(array($k => $field[$k])); } if (count($this->fields) === 0) { show_error('Field information is required.'); } $sqls = $this->_alter_table('CHANGE', $this->db->dbprefix.$table, $this->_process_fields()); $this->_reset(); if ($sqls === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } for ($i = 0, $c = count($sqls); $i < $c; $i++) { if ($this->db->query($sqls[$i]) === FALSE) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * ALTER TABLE * * @param string $alter_type ALTER type * @param string $table Table name * @param mixed $field Column definition * @return string|string[] */ protected function _alter_table($alter_type, $table, $field) { $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '; // DROP has everything it needs now. if ($alter_type === 'DROP') { return $sql.'DROP COLUMN '.$this->db->escape_identifiers($field); } $sql .= ($alter_type === 'ADD') ? 'ADD ' : $alter_type.' COLUMN '; $sqls = array(); for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql .($field[$i]['_literal'] !== FALSE ? $field[$i]['_literal'] : $this->_process_column($field[$i])); } return $sqls; } // -------------------------------------------------------------------- /** * Process fields * * @param bool $create_table * @return array */ protected function _process_fields($create_table = FALSE) { $fields = array(); foreach ($this->fields as $key => $attributes) { if (is_int($key) && ! is_array($attributes)) { $fields[] = array('_literal' => $attributes); continue; } $attributes = array_change_key_case($attributes, CASE_UPPER); if ($create_table === TRUE && empty($attributes['TYPE'])) { continue; } isset($attributes['TYPE']) && $this->_attr_type($attributes); $field = array( 'name' => $key, 'new_name' => isset($attributes['NAME']) ? $attributes['NAME'] : NULL, 'type' => isset($attributes['TYPE']) ? $attributes['TYPE'] : NULL, 'length' => '', 'unsigned' => '', 'null' => NULL, 'unique' => '', 'default' => '', 'auto_increment' => '', '_literal' => FALSE ); isset($attributes['TYPE']) && $this->_attr_unsigned($attributes, $field); if ($create_table === FALSE) { if (isset($attributes['AFTER'])) { $field['after'] = $attributes['AFTER']; } elseif (isset($attributes['FIRST'])) { $field['first'] = (bool) $attributes['FIRST']; } } $this->_attr_default($attributes, $field); if (isset($attributes['NULL'])) { if ($attributes['NULL'] === TRUE) { $field['null'] = empty($this->_null) ? '' : ' '.$this->_null; } else { $field['null'] = ' NOT NULL'; } } elseif ($create_table === TRUE) { $field['null'] = ' NOT NULL'; } $this->_attr_auto_increment($attributes, $field); $this->_attr_unique($attributes, $field); if (isset($attributes['COMMENT'])) { $field['comment'] = $this->db->escape($attributes['COMMENT']); } if (isset($attributes['TYPE']) && ! empty($attributes['CONSTRAINT'])) { switch (strtoupper($attributes['TYPE'])) { case 'ENUM': case 'SET': $attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']); default: $field['length'] = is_array($attributes['CONSTRAINT']) ? '('.implode(',', $attributes['CONSTRAINT']).')' : '('.$attributes['CONSTRAINT'].')'; break; } } $fields[] = $field; } return $fields; } // -------------------------------------------------------------------- /** * Process column * * @param array $field * @return string */ protected function _process_column($field) { return $this->db->escape_identifiers($field['name']) .' '.$field['type'].$field['length'] .$field['unsigned'] .$field['default'] .$field['null'] .$field['auto_increment'] .$field['unique']; } // -------------------------------------------------------------------- /** * Field attribute TYPE * * Performs a data type mapping between different databases. * * @param array &$attributes * @return void */ protected function _attr_type(&$attributes) { // Usually overridden by drivers } // -------------------------------------------------------------------- /** * Field attribute UNSIGNED * * Depending on the _unsigned property value: * * - TRUE will always set $field['unsigned'] to 'UNSIGNED' * - FALSE will always set $field['unsigned'] to '' * - array(TYPE) will set $field['unsigned'] to 'UNSIGNED', * if $attributes['TYPE'] is found in the array * - array(TYPE => UTYPE) will change $field['type'], * from TYPE to UTYPE in case of a match * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_unsigned(&$attributes, &$field) { if (empty($attributes['UNSIGNED']) OR $attributes['UNSIGNED'] !== TRUE) { return; } // Reset the attribute in order to avoid issues if we do type conversion $attributes['UNSIGNED'] = FALSE; if (is_array($this->_unsigned)) { foreach (array_keys($this->_unsigned) as $key) { if (is_int($key) && strcasecmp($attributes['TYPE'], $this->_unsigned[$key]) === 0) { $field['unsigned'] = ' UNSIGNED'; return; } elseif (is_string($key) && strcasecmp($attributes['TYPE'], $key) === 0) { $field['type'] = $key; return; } } return; } $field['unsigned'] = ($this->_unsigned === TRUE) ? ' UNSIGNED' : ''; } // -------------------------------------------------------------------- /** * Field attribute DEFAULT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_default(&$attributes, &$field) { if ($this->_default === FALSE) { return; } if (array_key_exists('DEFAULT', $attributes)) { if ($attributes['DEFAULT'] === NULL) { $field['default'] = empty($this->_null) ? '' : $this->_default.$this->_null; // Override the NULL attribute if that's our default $attributes['NULL'] = TRUE; $field['null'] = empty($this->_null) ? '' : ' '.$this->_null; } else { $field['default'] = $this->_default.$this->db->escape($attributes['DEFAULT']); } } } // -------------------------------------------------------------------- /** * Field attribute UNIQUE * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_unique(&$attributes, &$field) { if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE) { $field['unique'] = ' UNIQUE'; } } // -------------------------------------------------------------------- /** * Field attribute AUTO_INCREMENT * * @param array &$attributes * @param array &$field * @return void */ protected function _attr_auto_increment(&$attributes, &$field) { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE) { $field['auto_increment'] = ' AUTO_INCREMENT'; } } // -------------------------------------------------------------------- /** * Process primary keys * * @param string $table Table name * @return string */ protected function _process_primary_keys($table) { $sql = ''; for ($i = 0, $c = count($this->primary_keys); $i < $c; $i++) { if ( ! isset($this->fields[$this->primary_keys[$i]])) { unset($this->primary_keys[$i]); } } if (count($this->primary_keys) > 0) { $sql .= ",\n\tCONSTRAINT ".$this->db->escape_identifiers('pk_'.$table) .' PRIMARY KEY('.implode(', ', $this->db->escape_identifiers($this->primary_keys)).')'; } return $sql; } // -------------------------------------------------------------------- /** * Process indexes * * @param string $table Table name * @return string[] list of SQL statements */ protected function _process_indexes($table) { $sqls = array(); for ($i = 0, $c = count($this->keys); $i < $c; $i++) { if (is_array($this->keys[$i])) { for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++) { if ( ! isset($this->fields[$this->keys[$i][$i2]])) { unset($this->keys[$i][$i2]); continue; } } } elseif ( ! isset($this->fields[$this->keys[$i]])) { unset($this->keys[$i]); continue; } is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]); $sqls[] = 'CREATE INDEX '.$this->db->escape_identifiers($table.'_'.implode('_', $this->keys[$i])) .' ON '.$this->db->escape_identifiers($table) .' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).');'; } return $sqls; } // -------------------------------------------------------------------- /** * Reset * * Resets table creation vars * * @return void */ protected function _reset() { $this->fields = $this->keys = $this->primary_keys = array(); } } database/DB.php000064400000015131152270514220007307 0ustar00load->get_package_paths() as $path) { if ($path !== APPPATH) { if (file_exists($file_path = $path.'config/'.ENVIRONMENT.'/database.php')) { include($file_path); } elseif (file_exists($file_path = $path.'config/database.php')) { include($file_path); } } } } if ( ! isset($db) OR count($db) === 0) { show_error('No database connection settings were found in the database config file.'); } if ($params !== '') { $active_group = $params; } if ( ! isset($active_group)) { show_error('You have not specified a database connection group via $active_group in your config/database.php file.'); } elseif ( ! isset($db[$active_group])) { show_error('You have specified an invalid database connection group ('.$active_group.') in your config/database.php file.'); } $params = $db[$active_group]; } elseif (is_string($params)) { /** * Parse the URL from the DSN string * Database settings can be passed as discreet * parameters or as a data source name in the first * parameter. DSNs must have this prototype: * $dsn = 'driver://username:password@hostname/database'; */ if (($dsn = @parse_url($params)) === FALSE) { show_error('Invalid DB Connection String'); } $params = array( 'dbdriver' => $dsn['scheme'], 'hostname' => isset($dsn['host']) ? rawurldecode($dsn['host']) : '', 'port' => isset($dsn['port']) ? rawurldecode($dsn['port']) : '', 'username' => isset($dsn['user']) ? rawurldecode($dsn['user']) : '', 'password' => isset($dsn['pass']) ? rawurldecode($dsn['pass']) : '', 'database' => isset($dsn['path']) ? rawurldecode(substr($dsn['path'], 1)) : '' ); // Were additional config items set? if (isset($dsn['query'])) { parse_str($dsn['query'], $extra); foreach ($extra as $key => $val) { if (is_string($val) && in_array(strtoupper($val), array('TRUE', 'FALSE', 'NULL'))) { $val = var_export($val, TRUE); } $params[$key] = $val; } } } // No DB specified yet? Beat them senseless... if (empty($params['dbdriver'])) { show_error('You have not selected a database type to connect to.'); } // Load the DB classes. Note: Since the query builder class is optional // we need to dynamically create a class that extends proper parent class // based on whether we're using the query builder class or not. if ($query_builder_override !== NULL) { $query_builder = $query_builder_override; } // Backwards compatibility work-around for keeping the // $active_record config variable working. Should be // removed in v3.1 elseif ( ! isset($query_builder) && isset($active_record)) { $query_builder = $active_record; } require_once(BASEPATH.'database/DB_driver.php'); if ( ! isset($query_builder) OR $query_builder === TRUE) { require_once(BASEPATH.'database/DB_query_builder.php'); if ( ! class_exists('CI_DB', FALSE)) { /** * CI_DB * * Acts as an alias for both CI_DB_driver and CI_DB_query_builder. * * @see CI_DB_query_builder * @see CI_DB_driver */ class CI_DB extends CI_DB_query_builder { } } } elseif ( ! class_exists('CI_DB', FALSE)) { /** * @ignore */ class CI_DB extends CI_DB_driver { } } // Load the DB driver $driver_file = BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php'; file_exists($driver_file) OR show_error('Invalid DB driver'); require_once($driver_file); // Instantiate the DB adapter $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; $DB = new $driver($params); // Check for a subdriver if ( ! empty($DB->subdriver)) { $driver_file = BASEPATH.'database/drivers/'.$DB->dbdriver.'/subdrivers/'.$DB->dbdriver.'_'.$DB->subdriver.'_driver.php'; if (file_exists($driver_file)) { require_once($driver_file); $driver = 'CI_DB_'.$DB->dbdriver.'_'.$DB->subdriver.'_driver'; $DB = new $driver($params); } } $DB->initialize(); return $DB; } language/english/pagination_lang.php000064400000003703152270514220013626 0ustar00 403 Forbidden

Directory access is forbidden.

language/english/imglib_lang.php000064400000007222152270514220012740 0ustar00 403 Forbidden

Directory access is forbidden.

index.html000064400000000203152270514220006534 0ustar00 403 Forbidden

Directory access is forbidden.

helpers/download_helper.php000064400000011054152270514220012066 0ustar00'.$data.''; } } // ------------------------------------------------------------------------ if ( ! function_exists('ul')) { /** * Unordered List * * Generates an HTML unordered list from an single or multi-dimensional array. * * @param array * @param mixed * @return string */ function ul($list, $attributes = '') { return _list('ul', $list, $attributes); } } // ------------------------------------------------------------------------ if ( ! function_exists('ol')) { /** * Ordered List * * Generates an HTML ordered list from an single or multi-dimensional array. * * @param array * @param mixed * @return string */ function ol($list, $attributes = '') { return _list('ol', $list, $attributes); } } // ------------------------------------------------------------------------ if ( ! function_exists('_list')) { /** * Generates the list * * Generates an HTML ordered list from an single or multi-dimensional array. * * @param string * @param mixed * @param mixed * @param int * @return string */ function _list($type = 'ul', $list = array(), $attributes = '', $depth = 0) { // If an array wasn't submitted there's nothing to do... if ( ! is_array($list)) { return $list; } // Set the indentation based on the depth $out = str_repeat(' ', $depth) // Write the opening list tag .'<'.$type._stringify_attributes($attributes).">\n"; // Cycle through the list elements. If an array is // encountered we will recursively call _list() static $_last_list_item = ''; foreach ($list as $key => $val) { $_last_list_item = $key; $out .= str_repeat(' ', $depth + 2).'
  • '; if ( ! is_array($val)) { $out .= $val; } else { $out .= $_last_list_item."\n"._list($type, $val, '', $depth + 4).str_repeat(' ', $depth + 2); } $out .= "
  • \n"; } // Set the indentation for the closing tag and apply it return $out.str_repeat(' ', $depth).'\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('img')) { /** * Image * * Generates an element * * @param mixed * @param bool * @param mixed * @return string */ function img($src = '', $index_page = FALSE, $attributes = '') { if ( ! is_array($src) ) { $src = array('src' => $src); } // If there is no alt attribute defined, set it to an empty string if ( ! isset($src['alt'])) { $src['alt'] = ''; } $img = ' $v) { if ($k === 'src' && ! preg_match('#^(data:[a-z,;])|(([a-z]+:)?(?config->site_url($v).'"'; } else { $img .= ' src="'.get_instance()->config->base_url($v).'"'; } } else { $img .= ' '.$k.'="'.$v.'"'; } } return $img._stringify_attributes($attributes).' />'; } } // ------------------------------------------------------------------------ if ( ! function_exists('doctype')) { /** * Doctype * * Generates a page document type declaration * * Examples of valid options: html5, xhtml-11, xhtml-strict, xhtml-trans, * xhtml-frame, html4-strict, html4-trans, and html4-frame. * All values are saved in the doctypes config file. * * @param string type The doctype to be generated * @return string */ function doctype($type = 'xhtml1-strict') { static $doctypes; if ( ! is_array($doctypes)) { if (file_exists(APPPATH.'config/doctypes.php')) { include(APPPATH.'config/doctypes.php'); } if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php'); } if (empty($_doctypes) OR ! is_array($_doctypes)) { $doctypes = array(); return FALSE; } $doctypes = $_doctypes; } return isset($doctypes[$type]) ? $doctypes[$type] : FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists('link_tag')) { /** * Link * * Generates link to a CSS file * * @param mixed stylesheet hrefs or an array * @param string rel * @param string type * @param string title * @param string media * @param bool should index_page be added to the css path * @return string */ function link_tag($href = '', $rel = 'stylesheet', $type = 'text/css', $title = '', $media = '', $index_page = FALSE) { $CI =& get_instance(); $link = ' $v) { if ($k === 'href' && ! preg_match('#^([a-z]+:)?//#i', $v)) { if ($index_page === TRUE) { $link .= 'href="'.$CI->config->site_url($v).'" '; } else { $link .= 'href="'.$CI->config->base_url($v).'" '; } } else { $link .= $k.'="'.$v.'" '; } } } else { if (preg_match('#^([a-z]+:)?//#i', $href)) { $link .= 'href="'.$href.'" '; } elseif ($index_page === TRUE) { $link .= 'href="'.$CI->config->site_url($href).'" '; } else { $link .= 'href="'.$CI->config->base_url($href).'" '; } $link .= 'rel="'.$rel.'" type="'.$type.'" '; if ($media !== '') { $link .= 'media="'.$media.'" '; } if ($title !== '') { $link .= 'title="'.$title.'" '; } } return $link."/>\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('meta')) { /** * Generates meta tags from an array of key/values * * @param array * @param string * @param string * @param string * @return string */ function meta($name = '', $content = '', $type = 'name', $newline = "\n") { // Since we allow the data to be passes as a string, a simple array // or a multidimensional one, we need to do a little prepping. if ( ! is_array($name)) { $name = array(array('name' => $name, 'content' => $content, 'type' => $type, 'newline' => $newline)); } elseif (isset($name['name'])) { // Turn single array into multidimensional $name = array($name); } $str = ''; foreach ($name as $meta) { $type = (isset($meta['type']) && $meta['type'] !== 'name') ? 'http-equiv' : 'name'; $name = isset($meta['name']) ? $meta['name'] : ''; $content = isset($meta['content']) ? $meta['content'] : ''; $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; $str .= ''.$newline; } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('br')) { /** * Generates HTML BR tags based on number supplied * * @deprecated 3.0.0 Use str_repeat() instead * @param int $count Number of times to repeat the tag * @return string */ function br($count = 1) { return str_repeat('
    ', $count); } } // ------------------------------------------------------------------------ if ( ! function_exists('nbs')) { /** * Generates non-breaking space entities based on number supplied * * @deprecated 3.0.0 Use str_repeat() instead * @param int * @return string */ function nbs($num = 1) { return str_repeat(' ', $num); } } helpers/language_helper.php000064400000005147152270514220012050 0ustar00lang->line($line); if ($for !== '') { $line = ''; } return $line; } } helpers/date_helper.php000064400000042524152270514220011202 0ustar00format('j-n-Y G:i:s'), '%d-%d-%d %d:%d:%d', $day, $month, $year, $hour, $minute, $second); return mktime($hour, $minute, $second, $month, $day, $year); } } // ------------------------------------------------------------------------ if ( ! function_exists('mdate')) { /** * 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. * * @param string * @param int * @return int */ function mdate($datestr = '', $time = '') { if ($datestr === '') { return ''; } elseif (empty($time)) { $time = now(); } $datestr = str_replace( '%\\', '', preg_replace('/([a-z]+?){1}/i', '\\\\\\1', $datestr) ); return date($datestr, $time); } } // ------------------------------------------------------------------------ if ( ! function_exists('standard_date')) { /** * Standard Date * * Returns a date formatted according to the submitted standard. * * As of PHP 5.2, the DateTime extension provides constants that * serve for the exact same purpose and are used with date(). * * @todo Remove in version 3.1+. * @deprecated 3.0.0 Use PHP's native date() instead. * @link https://www.php.net/manual/en/class.datetime.php#datetime.constants.types * * @example date(DATE_RFC822, now()); // default * @example date(DATE_W3C, $time); // a different format and time * * @param string $fmt = 'DATE_RFC822' the chosen format * @param int $time = NULL Unix timestamp * @return string */ function standard_date($fmt = 'DATE_RFC822', $time = NULL) { if (empty($time)) { $time = now(); } // Procedural style pre-defined constants from the DateTime extension if (strpos($fmt, 'DATE_') !== 0 OR defined($fmt) === FALSE) { return FALSE; } return date(constant($fmt), $time); } } // ------------------------------------------------------------------------ if ( ! function_exists('timespan')) { /** * Timespan * * Returns a span of seconds in this format: * 10 days 14 hours 36 minutes 47 seconds * * @param int a number of seconds * @param int Unix timestamp * @param int a number of display units * @return string */ function timespan($seconds = 1, $time = '', $units = 7) { $CI =& get_instance(); $CI->lang->load('date'); is_numeric($seconds) OR $seconds = 1; is_numeric($time) OR $time = time(); is_numeric($units) OR $units = 7; $seconds = ($time <= $seconds) ? 1 : $time - $seconds; $str = array(); $years = floor($seconds / 31557600); if ($years > 0) { $str[] = $years.' '.$CI->lang->line($years > 1 ? 'date_years' : 'date_year'); } $seconds -= $years * 31557600; $months = floor($seconds / 2629743); if (count($str) < $units && ($years > 0 OR $months > 0)) { if ($months > 0) { $str[] = $months.' '.$CI->lang->line($months > 1 ? 'date_months' : 'date_month'); } $seconds -= $months * 2629743; } $weeks = floor($seconds / 604800); if (count($str) < $units && ($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 (count($str) < $units && ($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 (count($str) < $units && ($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 (count($str) < $units && ($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 (count($str) === 0) { $str[] = $seconds.' '.$CI->lang->line($seconds > 1 ? 'date_seconds' : 'date_second'); } return implode(', ', $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('days_in_month')) { /** * 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. * * @param int a numeric month * @param int a numeric year * @return int */ function days_in_month($month = 0, $year = '') { if ($month < 1 OR $month > 12) { return 0; } elseif ( ! is_numeric($year) OR strlen($year) !== 4) { $year = date('Y'); } if (defined('CAL_GREGORIAN')) { return cal_days_in_month(CAL_GREGORIAN, $month, $year); } if ($year >= 1970) { return (int) date('t', mktime(12, 0, 0, $month, 1, $year)); } if ($month == 2) { if ($year % 400 === 0 OR ($year % 4 === 0 && $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]; } } // ------------------------------------------------------------------------ if ( ! function_exists('local_to_gmt')) { /** * Converts a local Unix timestamp to GMT * * @param int Unix timestamp * @return int */ function local_to_gmt($time = '') { if ($time === '') { $time = time(); } return mktime( gmdate('G', $time), gmdate('i', $time), gmdate('s', $time), gmdate('n', $time), gmdate('j', $time), gmdate('Y', $time) ); } } // ------------------------------------------------------------------------ if ( ! function_exists('gmt_to_local')) { /** * 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 * * @param int Unix timestamp * @param string timezone * @param bool whether DST is active * @return int */ function gmt_to_local($time = '', $timezone = 'UTC', $dst = FALSE) { if ($time === '') { return now(); } $time += timezones($timezone) * 3600; return ($dst === TRUE) ? $time + 3600 : $time; } } // ------------------------------------------------------------------------ if ( ! function_exists('mysql_to_unix')) { /** * Converts a MySQL Timestamp to Unix * * @param int MySQL timestamp YYYY-MM-DD HH:MM:SS * @return int Unix timstamp */ 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(array('-', ':', ' '), '', $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) ); } } // ------------------------------------------------------------------------ if ( ! function_exists('unix_to_human')) { /** * Unix to "Human" * * Formats Unix timestamp to the following prototype: 2006-08-21 11:35 PM * * @param int Unix timestamp * @param bool whether to show seconds * @param string format: us or euro * @return string */ 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') { return $r.' '.date('A', $time); } return $r; } } // ------------------------------------------------------------------------ if ( ! function_exists('human_to_unix')) { /** * Convert "human" date to GMT * * Reverses the above process * * @param string format: us or euro * @return int */ function human_to_unix($datestr = '') { if ($datestr === '') { return FALSE; } $datestr = preg_replace('/\040+/', ' ', trim($datestr)); if ( ! preg_match('/^(\d{2}|\d{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; } sscanf($datestr, '%d-%d-%d %s %s', $year, $month, $day, $time, $ampm); sscanf($time, '%d:%d:%d', $hour, $min, $sec); isset($sec) OR $sec = 0; if (isset($ampm)) { $ampm = strtolower($ampm); if ($ampm[0] === 'p' && $hour < 12) { $hour += 12; } elseif ($ampm[0] === 'a' && $hour === 12) { $hour = 0; } } return mktime($hour, $min, $sec, $month, $day, $year); } } // ------------------------------------------------------------------------ if ( ! function_exists('nice_date')) { /** * Turns many "reasonably-date-like" strings into something * that is actually useful. This only works for dates after unix epoch. * * @deprecated 3.1.3 Use DateTime::createFromFormat($input_format, $input)->format($output_format); * @param string The terribly formatted date-like string * @param string Date format to return (same as php date function) * @return string */ function nice_date($bad_date = '', $format = FALSE) { if (empty($bad_date)) { return 'Unknown'; } elseif (empty($format)) { $format = 'U'; } // Date like: YYYYMM if (preg_match('/^\d{6}$/i', $bad_date)) { if (in_array(substr($bad_date, 0, 2), array('19', '20'))) { $year = substr($bad_date, 0, 4); $month = substr($bad_date, 4, 2); } else { $month = substr($bad_date, 0, 2); $year = substr($bad_date, 2, 4); } return date($format, strtotime($year.'-'.$month.'-01')); } // Date Like: YYYYMMDD if (preg_match('/^\d{8}$/i', $bad_date, $matches)) { return DateTime::createFromFormat('Ymd', $bad_date)->format($format); } // Date Like: MM-DD-YYYY __or__ M-D-YYYY (or anything in between) if (preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/i', $bad_date, $matches)) { return date($format, strtotime($matches[3].'-'.$matches[1].'-'.$matches[2])); } // Any other kind of string, when converted into UNIX time, // produces "0 seconds after epoc..." is probably bad... // return "Invalid Date". if (date('U', strtotime($bad_date)) === '0') { return 'Invalid Date'; } // It's probably a valid-ish date format already return date($format, strtotime($bad_date)); } } // ------------------------------------------------------------------------ if ( ! function_exists('timezone_menu')) { /** * Timezone Menu * * Generates a drop-down menu of timezones. * * @param string timezone * @param string classname * @param string menu name * @param mixed attributes * @return string */ function timezone_menu($default = 'UTC', $class = '', $name = 'timezones', $attributes = '') { $CI =& get_instance(); $CI->lang->load('date'); $default = ($default === 'GMT') ? 'UTC' : $default; $menu = ''; } } // ------------------------------------------------------------------------ if ( ! function_exists('timezones')) { /** * Timezones * * Returns an array of timezones. This is a helper function * for various other ones in this library * * @param string timezone * @return string */ 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; } return isset($zones[$tz]) ? $zones[$tz] : 0; } } // ------------------------------------------------------------------------ if ( ! function_exists('date_range')) { /** * Date range * * Returns a list of dates within a specified period. * * @param int unix_start UNIX timestamp of period start date * @param int unix_end|days UNIX timestamp of period end date * or interval in days. * @param mixed is_unix Specifies whether the second parameter * is a UNIX timestamp or a day interval * - TRUE or 'unix' for a timestamp * - FALSE or 'days' for an interval * @param string date_format Output date format, same as in date() * @return array */ function date_range($unix_start = '', $mixed = '', $is_unix = TRUE, $format = 'Y-m-d') { if ($unix_start == '' OR $mixed == '' OR $format == '') { return FALSE; } $is_unix = ! ( ! $is_unix OR $is_unix === 'days'); // Validate input and try strtotime() on invalid timestamps/intervals, just in case if ( ( ! ctype_digit((string) $unix_start) && ($unix_start = @strtotime($unix_start)) === FALSE) OR ( ! ctype_digit((string) $mixed) && ($is_unix === FALSE OR ($mixed = @strtotime($mixed)) === FALSE)) OR ($is_unix === TRUE && $mixed < $unix_start)) { return FALSE; } if ($is_unix && ($unix_start == $mixed OR date($format, $unix_start) === date($format, $mixed))) { return array(date($format, $unix_start)); } $range = array(); $from = new DateTime(); $from->setTimestamp($unix_start); if ($is_unix) { $arg = new DateTime(); $arg->setTimestamp($mixed); } else { $arg = (int) $mixed; } $period = new DatePeriod($from, new DateInterval('P1D'), $arg); foreach ($period as $date) { $range[] = $date->format($format); } /* If a period end date was passed to the DatePeriod constructor, it might not * be in our results. Not sure if this is a bug or it's just possible because * the end date might actually be less than 24 hours away from the previously * generated DateTime object, but either way - we have to append it manually. */ if ( ! is_int($arg) && $range[count($range) - 1] !== $arg->format($format)) { $range[] = $arg->format($format); } return $range; } } helpers/security_helper.php000064400000007303152270514220012130 0ustar00security->xss_clean($str, $is_image); } } // ------------------------------------------------------------------------ if ( ! function_exists('sanitize_filename')) { /** * Sanitize Filename * * @param string * @return string */ function sanitize_filename($filename) { return get_instance()->security->sanitize_filename($filename); } } // -------------------------------------------------------------------- if ( ! function_exists('do_hash')) { /** * Hash encode a string * * @todo Remove in version 3.1+. * @deprecated 3.0.0 Use PHP's native hash() instead. * @param string $str * @param string $type = 'sha1' * @return string */ function do_hash($str, $type = 'sha1') { if ( ! in_array(strtolower($type), hash_algos())) { $type = 'md5'; } return hash($type, $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('strip_image_tags')) { /** * Strip Image Tags * * @param string * @return string */ function strip_image_tags($str) { return get_instance()->security->strip_image_tags($str); } } // ------------------------------------------------------------------------ if ( ! function_exists('encode_php_tags')) { /** * Convert PHP tags to entities * * @param string * @return string */ function encode_php_tags($str) { return str_replace(array(''), array('<?', '?>'), $str); } } helpers/captcha_helper.php000064400000023363152270514220011670 0ustar00 '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200, 'word_length' => 8, 'font_size' => 16, 'img_id' => '', 'pool' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'colors' => array( 'background' => array(255,255,255), 'border' => array(153,102,102), 'text' => array(204,153,153), 'grid' => array(255,182,182) ) ); foreach ($defaults as $key => $val) { if ( ! is_array($data) && empty($$key)) { $$key = $val; } else { $$key = isset($data[$key]) ? $data[$key] : $val; } } if ( ! extension_loaded('gd')) { log_message('error', 'create_captcha(): GD extension is not loaded.'); return FALSE; } if ($img_path === '' OR $img_url === '') { log_message('error', 'create_captcha(): $img_path and $img_url are required.'); return FALSE; } if ( ! is_dir($img_path) OR ! is_really_writable($img_path)) { log_message('error', "create_captcha(): '{$img_path}' is not a dir, nor is it writable."); return FALSE; } // ----------------------------------- // Remove old images // ----------------------------------- $now = microtime(TRUE); $current_dir = @opendir($img_path); while ($filename = @readdir($current_dir)) { if (in_array(substr($filename, -4), array('.jpg', '.png')) && (str_replace(array('.jpg', '.png'), '', $filename) + $expiration) < $now) { @unlink($img_path.$filename); } } @closedir($current_dir); // ----------------------------------- // Do we have a "word" yet? // ----------------------------------- if (empty($word)) { $word = ''; $pool_length = strlen($pool); $rand_max = $pool_length - 1; // PHP7 or a suitable polyfill if (function_exists('random_int')) { try { for ($i = 0; $i < $word_length; $i++) { $word .= $pool[random_int(0, $rand_max)]; } } catch (Exception $e) { // This means fallback to the next possible // alternative to random_int() $word = ''; } } } if (empty($word)) { // Nobody will have a larger character pool than // 256 characters, but let's handle it just in case ... // // No, I do not care that the fallback to mt_rand() can // handle it; if you trigger this, you're very obviously // trying to break it. -- Narf if ($pool_length > 256) { return FALSE; } // We'll try using the operating system's PRNG first, // which we can access through CI_Security::get_random_bytes() $security = get_instance()->security; // To avoid numerous get_random_bytes() calls, we'll // just try fetching as much bytes as we need at once. if (($bytes = $security->get_random_bytes($pool_length)) !== FALSE) { $byte_index = $word_index = 0; while ($word_index < $word_length) { // Do we have more random data to use? // It could be exhausted by previous iterations // ignoring bytes higher than $rand_max. if ($byte_index === $pool_length) { // No failures should be possible if the // first get_random_bytes() call didn't // return FALSE, but still ... for ($i = 0; $i < 5; $i++) { if (($bytes = $security->get_random_bytes($pool_length)) === FALSE) { continue; } $byte_index = 0; break; } if ($bytes === FALSE) { // Sadly, this means fallback to mt_rand() $word = ''; break; } } list(, $rand_index) = unpack('C', $bytes[$byte_index++]); if ($rand_index > $rand_max) { continue; } $word .= $pool[$rand_index]; $word_index++; } } } if (empty($word)) { for ($i = 0; $i < $word_length; $i++) { $word .= $pool[mt_rand(0, $rand_max)]; } } elseif ( ! is_string($word)) { $word = (string) $word; } // ----------------------------------- // Determine angle and position // ----------------------------------- $length = strlen($word); $angle = ($length >= 6) ? mt_rand(-($length-6), ($length-6)) : 0; $x_axis = mt_rand(6, (360/$length)-16); $y_axis = ($angle >= 0) ? mt_rand($img_height, $img_width) : mt_rand(6, $img_height); // Create image // PHP.net recommends imagecreatetruecolor(), but it isn't always available $im = function_exists('imagecreatetruecolor') ? imagecreatetruecolor($img_width, $img_height) : imagecreate($img_width, $img_height); // ----------------------------------- // Assign colors // ---------------------------------- is_array($colors) OR $colors = $defaults['colors']; foreach (array_keys($defaults['colors']) as $key) { // Check for a possible missing value is_array($colors[$key]) OR $colors[$key] = $defaults['colors'][$key]; $colors[$key] = imagecolorallocate($im, $colors[$key][0], $colors[$key][1], $colors[$key][2]); } // Create the rectangle ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $colors['background']); // ----------------------------------- // Create the spiral pattern // ----------------------------------- $theta = 1; $thetac = 7; $radius = 16; $circles = 20; $points = 32; for ($i = 0, $cp = ($circles * $points) - 1; $i < $cp; $i++) { $theta += $thetac; $rad = $radius * ($i / $points); $x = ($rad * cos($theta)) + $x_axis; $y = ($rad * sin($theta)) + $y_axis; $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, $colors['grid']); $theta -= $thetac; } // ----------------------------------- // Write the text // ----------------------------------- $use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext')); if ($use_font === FALSE) { ($font_size > 5) && $font_size = 5; $x = mt_rand(0, $img_width / ($length / 3)); $y = 0; } else { ($font_size > 30) && $font_size = 30; $x = mt_rand(0, $img_width / ($length / 1.5)); $y = $font_size + 2; } for ($i = 0; $i < $length; $i++) { if ($use_font === FALSE) { $y = mt_rand(0 , $img_height / 2); imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']); $x += ($font_size * 2); } else { $y = mt_rand($img_height / 2, $img_height - 3); imagettftext($im, $font_size, $angle, $x, $y, $colors['text'], $font_path, $word[$i]); $x += $font_size; } } // Create the border imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $colors['border']); // ----------------------------------- // Generate the image // ----------------------------------- $img_url = rtrim($img_url, '/').'/'; if (function_exists('imagejpeg')) { $img_filename = $now.'.jpg'; imagejpeg($im, $img_path.$img_filename); } elseif (function_exists('imagepng')) { $img_filename = $now.'.png'; imagepng($im, $img_path.$img_filename); } else { return FALSE; } $img = ' '; ImageDestroy($im); return array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename); } } helpers/path_helper.php000064400000005620152270514220011215 0ustar00 0) ? @rmdir($path) : TRUE; } } // ------------------------------------------------------------------------ if ( ! function_exists('get_filenames')) { /** * 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. * * @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 */ 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) && $file[0] !== '.') { get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE); } elseif ($file[0] !== '.') { $_filedata[] = ($include_path === TRUE) ? $source_dir.$file : $file; } } closedir($fp); return $_filedata; } return FALSE; } } // -------------------------------------------------------------------- if ( ! function_exists('get_dir_file_info')) { /** * 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. * * @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 */ 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; } // Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast while (FALSE !== ($file = readdir($fp))) { if (is_dir($source_dir.$file) && $file[0] !== '.' && $top_level_only === FALSE) { get_dir_file_info($source_dir.$file.DIRECTORY_SEPARATOR, $top_level_only, TRUE); } elseif ($file[0] !== '.') { $_filedata[$file] = get_file_info($source_dir.$file); $_filedata[$file]['relative_path'] = $relative_path; } } closedir($fp); return $_filedata; } return FALSE; } } // -------------------------------------------------------------------- if ( ! function_exists('get_file_info')) { /** * 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. * * @param string path to file * @param mixed array or comma separated string of information returned * @return array */ 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'] = basename($file); 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': $fileinfo['writable'] = is_really_writable($file); break; case 'executable': $fileinfo['executable'] = is_executable($file); break; case 'fileperms': $fileinfo['fileperms'] = fileperms($file); break; } } return $fileinfo; } } // -------------------------------------------------------------------- if ( ! function_exists('get_mime_by_extension')) { /** * 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 * * @param string $filename File name * @return string */ function get_mime_by_extension($filename) { static $mimes; if ( ! is_array($mimes)) { $mimes = get_mimes(); if (empty($mimes)) { return FALSE; } } $extension = strtolower(substr(strrchr($filename, '.'), 1)); if (isset($mimes[$extension])) { return is_array($mimes[$extension]) ? current($mimes[$extension]) // Multiple mime types, just give the first one : $mimes[$extension]; } return FALSE; } } // -------------------------------------------------------------------- if ( ! function_exists('symbolic_permissions')) { /** * Symbolic Permissions * * Takes a numeric value representing a file's permissions and returns * standard symbolic notation representing that value * * @param int $perms Permissions * @return string */ 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' : '-') .(($perms & 0x0080) ? 'w' : '-') .(($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); // Group $symbolic .= (($perms & 0x0020) ? 'r' : '-') .(($perms & 0x0010) ? 'w' : '-') .(($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); // World $symbolic .= (($perms & 0x0004) ? 'r' : '-') .(($perms & 0x0002) ? 'w' : '-') .(($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $symbolic; } } // -------------------------------------------------------------------- if ( ! function_exists('octal_permissions')) { /** * Octal Permissions * * Takes a numeric value representing a file's permissions and returns * a three character string representing the file's octal permissions * * @param int $perms Permissions * @return string */ function octal_permissions($perms) { return substr(sprintf('%o', $perms), -3); } } helpers/string_helper.php000064400000016712152270514220011573 0ustar00 $val) { $str[$key] = strip_slashes($val); } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('strip_quotes')) { /** * Strip Quotes * * Removes single and double quotes from a string * * @param string * @return string */ function strip_quotes($str) { return str_replace(array('"', "'"), '', $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('quotes_to_entities')) { /** * Quotes to Entities * * Converts single and double quotes to entities * * @param string * @return string */ function quotes_to_entities($str) { return str_replace(array("\'","\"","'",'"'), array("'",""","'","""), $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('reduce_double_slashes')) { /** * Reduce Double Slashes * * Converts double slashes in a string to a single slash, * except those found in http:// * * http://www.some-site.com//index.php * * becomes: * * http://www.some-site.com/index.php * * @param string * @return string */ function reduce_double_slashes($str) { return preg_replace('#(^|[^:])//+#', '\\1/', $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('reduce_multiples')) { /** * Reduce Multiples * * Reduces multiple instances of a particular character. Example: * * Fred, Bill,, Joe, Jimmy * * becomes: * * Fred, Bill, Joe, Jimmy * * @param string * @param string the character you wish to reduce * @param bool TRUE/FALSE - whether to trim the character from the beginning/end * @return string */ function reduce_multiples($str, $character = ',', $trim = FALSE) { $str = preg_replace('#'.preg_quote($character, '#').'{2,}#', $character, $str); return ($trim === TRUE) ? trim($str, $character) : $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('random_string')) { /** * Create a "Random" String * * @param string type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1 * @param int number of characters * @return string */ function random_string($type = 'alnum', $len = 8) { switch ($type) { case 'basic': return mt_rand(); case 'alnum': case 'numeric': case 'nozero': case 'alpha': switch ($type) { case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; } return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len); case 'unique': // todo: remove in 3.1+ case 'md5': return md5(uniqid(mt_rand())); case 'encrypt': // todo: remove in 3.1+ case 'sha1': return sha1(uniqid(mt_rand(), TRUE)); } } } // ------------------------------------------------------------------------ if ( ! function_exists('increment_string')) { /** * Add's _1 to a string or increment the ending number to allow _2, _3, etc * * @param string required * @param string What should the duplicate number be appended with * @param string Which number should be used for the first dupe increment * @return string */ function increment_string($str, $separator = '_', $first = 1) { preg_match('/(.+)'.preg_quote($separator, '/').'([0-9]+)$/', $str, $match); return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first; } } // ------------------------------------------------------------------------ if ( ! function_exists('alternator')) { /** * Alternator * * Allows strings to be alternated. See docs... * * @param string (as many parameters as needed) * @return string */ function alternator() { static $i; if (func_num_args() === 0) { $i = 0; return ''; } $args = func_get_args(); return $args[($i++ % count($args))]; } } // ------------------------------------------------------------------------ if ( ! function_exists('repeater')) { /** * Repeater function * * @todo Remove in version 3.1+. * @deprecated 3.0.0 This is just an alias for PHP's native str_repeat() * * @param string $data String to repeat * @param int $num Number of repeats * @return string */ function repeater($data, $num = 1) { return ($num > 0) ? str_repeat($data, $num) : ''; } } helpers/xml_helper.php000064400000005573152270514220011070 0ustar00', '"', "'", '-'), array('&', '<', '>', '"', ''', '-'), $str ); // Decode the temp markers back to entities $str = preg_replace('/'.$temp.'(\d+);/', '&#\\1;', $str); if ($protect_all === TRUE) { return preg_replace('/'.$temp.'(\w+);/', '&\\1;', $str); } return $str; } } helpers/url_helper.php000064400000033337152270514220011071 0ustar00config->site_url($uri, $protocol); } } // ------------------------------------------------------------------------ if ( ! function_exists('base_url')) { /** * Base URL * * Create a local URL based on your basepath. * Segments can be passed in as a string or an array, same as site_url * or a URL to a file can be passed in, e.g. to an image file. * * @param string $uri * @param string $protocol * @return string */ function base_url($uri = '', $protocol = NULL) { return get_instance()->config->base_url($uri, $protocol); } } // ------------------------------------------------------------------------ if ( ! function_exists('current_url')) { /** * Current URL * * Returns the full URL (including segments) of the page where this * function is placed * * @return string */ function current_url() { $CI =& get_instance(); return $CI->config->site_url($CI->uri->uri_string()); } } // ------------------------------------------------------------------------ if ( ! function_exists('uri_string')) { /** * URL String * * Returns the URI segments. * * @return string */ function uri_string() { return get_instance()->uri->uri_string(); } } // ------------------------------------------------------------------------ if ( ! function_exists('index_page')) { /** * Index page * * Returns the "index_page" from your config file * * @return string */ function index_page() { return get_instance()->config->item('index_page'); } } // ------------------------------------------------------------------------ if ( ! function_exists('anchor')) { /** * Anchor Link * * Creates an anchor based on the local URL. * * @param string the URL * @param string the link title * @param mixed any attributes * @return string */ function anchor($uri = '', $title = '', $attributes = '') { $title = (string) $title; $site_url = is_array($uri) ? site_url($uri) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri)); if ($title === '') { $title = $site_url; } if ($attributes !== '') { $attributes = _stringify_attributes($attributes); } return '
    '.$title.''; } } // ------------------------------------------------------------------------ if ( ! function_exists('anchor_popup')) { /** * Anchor Link - Pop-up version * * Creates an anchor based on the local URL. The link * opens a new window based on the attributes specified. * * @param string the URL * @param string the link title * @param mixed any attributes * @return string */ function anchor_popup($uri = '', $title = '', $attributes = FALSE) { $title = (string) $title; $site_url = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri); if ($title === '') { $title = $site_url; } if ($attributes === FALSE) { return '".$title.''; } if ( ! is_array($attributes)) { $attributes = array($attributes); // Ref: http://www.w3schools.com/jsref/met_win_open.asp $window_name = '_blank'; } elseif ( ! empty($attributes['window_name'])) { $window_name = $attributes['window_name']; unset($attributes['window_name']); } else { $window_name = '_blank'; } foreach (array('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0') as $key => $val) { $atts[$key] = isset($attributes[$key]) ? $attributes[$key] : $val; unset($attributes[$key]); } $attributes = _stringify_attributes($attributes); return ''.$title.''; } } // ------------------------------------------------------------------------ if ( ! function_exists('mailto')) { /** * Mailto Link * * @param string the email address * @param string the link title * @param mixed any attributes * @return string */ function mailto($email, $title = '', $attributes = '') { $title = (string) $title; if ($title === '') { $title = $email; } return ''.$title.''; } } // ------------------------------------------------------------------------ if ( ! function_exists('safe_mailto')) { /** * Encoded Mailto Link * * Create a spam-protected mailto link written in Javascript * * @param string the email address * @param string the link title * @param mixed any attributes * @return string */ function safe_mailto($email, $title = '', $attributes = '') { $title = (string) $title; if ($title === '') { $title = $email; } $x = str_split(' $val) { $x[] = ' '.$key.'="'; for ($i = 0, $l = strlen($val); $i < $l; $i++) { $x[] = '|'.ord($val[$i]); } $x[] = '"'; } } else { for ($i = 0, $l = strlen($attributes); $i < $l; $i++) { $x[] = $attributes[$i]; } } } $x[] = '>'; $temp = array(); for ($i = 0, $l = strlen($title); $i < $l; $i++) { $ordinal = ord($title[$i]); if ($ordinal < 128) { $x[] = '|'.$ordinal; } else { if (count($temp) === 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) === $count) { $number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); $x[] = '|'.$number; $count = 1; $temp = array(); } } } $x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>'; $x = array_reverse($x); $output = "'; return $output; } } // ------------------------------------------------------------------------ if ( ! function_exists('auto_link')) { /** * Auto-linker * * Automatically links URL and Email addresses. * Note: There's a bit of extra code here to deal with * URLs or emails that end in a period. We'll strip these * off and add them after the link. * * @param string the string * @param string the type: email, url, or both * @param bool whether to create pop-up links * @return string */ function auto_link($str, $type = 'both', $popup = FALSE) { // Find and replace any URLs. if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { // Set our target HTML if using popup links. $target = ($popup) ? ' target="_blank" rel="noopener"' : ''; // We process the links in reverse order (last -> first) so that // the returned string offsets from preg_match_all() are not // moved as we add more HTML. foreach (array_reverse($matches) as $match) { // $match[0] is the matched string/link // $match[1] is either a protocol prefix or 'www.' // // With PREG_OFFSET_CAPTURE, both of the above is an array, // where the actual value is held in [0] and its offset at the [1] index. $a = ''.$match[0][0].''; $str = substr_replace($str, $a, $match[0][1], strlen($match[0][0])); } } // Find and replace any emails. if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) { foreach (array_reverse($matches[0]) as $match) { if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== FALSE) { $str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0])); } } } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('prep_url')) { /** * Prep URL * * Simply adds the http:// part if no scheme is included * * @param string the URL * @return string */ function prep_url($str = '') { if ($str === 'http://' OR $str === '') { return ''; } $url = parse_url($str); if ( ! $url OR ! isset($url['scheme'])) { return 'http://'.$str; } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('url_title')) { /** * Create URL Title * * Takes a "title" string as input and creates a * human-friendly URL string with a "separator" string * as the word separator. * * @todo Remove old 'dash' and 'underscore' usage in 3.1+. * @param string $str Input string * @param string $separator Word separator * (usually '-' or '_') * @param bool $lowercase Whether to transform the output string to lowercase * @return string */ function url_title($str, $separator = '-', $lowercase = FALSE) { if ($separator === 'dash') { $separator = '-'; } elseif ($separator === 'underscore') { $separator = '_'; } $q_separator = preg_quote($separator, '#'); $trans = array( '&.+?;' => '', '[^\w\d _-]' => '', '\s+' => $separator, '('.$q_separator.')+' => $separator ); $str = strip_tags($str); foreach ($trans as $key => $val) { $str = preg_replace('#'.$key.'#i'.(UTF8_ENABLED ? 'u' : ''), $val, $str); } if ($lowercase === TRUE) { $str = strtolower($str); } return trim(trim($str, $separator)); } } // ------------------------------------------------------------------------ if ( ! function_exists('redirect')) { /** * Header Redirect * * Header redirect in two flavors * For very fine grained control over headers, you could use the Output * Library's set_header() function. * * @param string $uri URL * @param string $method Redirect method * 'auto', 'location' or 'refresh' * @param int $code HTTP Response status code * @return void */ function redirect($uri = '', $method = 'auto', $code = NULL) { if ( ! preg_match('#^(\w+:)?//#i', $uri)) { $uri = site_url($uri); } // IIS environment likely? Use 'refresh' for better compatibility if ($method === 'auto' && isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== FALSE) { $method = 'refresh'; } elseif ($method !== 'refresh' && (empty($code) OR ! is_numeric($code))) { if (isset($_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1') { $code = ($_SERVER['REQUEST_METHOD'] !== 'GET') ? 303 // reference: http://en.wikipedia.org/wiki/Post/Redirect/Get : 307; } else { $code = 302; } } switch ($method) { case 'refresh': header('Refresh:0;url='.$uri); break; default: header('Location: '.$uri, TRUE, $code); break; } exit; } } helpers/directory_helper.php000064400000006512152270514220012266 0ustar00 0) && is_dir($source_dir.$file)) { $filedata[$file] = directory_map($source_dir.$file, $new_depth, $hidden); } else { $filedata[] = $file; } } closedir($fp); return $filedata; } return FALSE; } } helpers/cookie_helper.php000064400000007516152270514220011540 0ustar00input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httponly); } } // -------------------------------------------------------------------- if ( ! function_exists('get_cookie')) { /** * Fetch an item from the COOKIE array * * @param string * @param bool * @return mixed */ function get_cookie($index, $xss_clean = NULL) { is_bool($xss_clean) OR $xss_clean = (config_item('global_xss_filtering') === TRUE); $prefix = isset($_COOKIE[$index]) ? '' : config_item('cookie_prefix'); return get_instance()->input->cookie($prefix.$index, $xss_clean); } } // -------------------------------------------------------------------- if ( ! function_exists('delete_cookie')) { /** * 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 */ function delete_cookie($name, $domain = '', $path = '/', $prefix = '') { set_cookie($name, '', '', $domain, $path, $prefix); } } helpers/smiley_helper.php000064400000015505152270514220011566 0ustar00field_id pairs * @param string field_id if alias name was passed in * @param bool * @return array */ function smiley_js($alias = '', $field_id = '', $inline = TRUE) { static $do_setup = TRUE; $r = ''; if ($alias !== '' && ! is_array($alias)) { $alias = array($alias => $field_id); } if ($do_setup === TRUE) { $do_setup = FALSE; $m = array(); if (is_array($alias)) { foreach ($alias as $name => $id) { $m[] = '"'.$name.'" : "'.$id.'"'; } } $m = '{'.implode(',', $m).'}'; $r .= << $id) { $r .= 'smiley_map["'.$name.'"] = "'.$id."\";\n"; } } return ($inline) ? '' : $r; } } // ------------------------------------------------------------------------ if ( ! function_exists('get_clickable_smileys')) { /** * Get Clickable Smileys * * Returns an array of image tag links that can be clicked to be inserted * into a form field. * * @param string the URL to the folder containing the smiley images * @param array * @return array */ function get_clickable_smileys($image_url, $alias = '') { // For backward compatibility with js_insert_smiley if (is_array($alias)) { $smileys = $alias; } elseif (FALSE === ($smileys = _get_smiley_array())) { return FALSE; } // Add a trailing slash to the file path if needed $image_url = rtrim($image_url, '/').'/'; $used = array(); foreach ($smileys as $key => $val) { // Keep duplicates from being used, which can happen if the // mapping array contains multiple identical replacements. For example: // :-) and :) might be replaced with the same image so both smileys // will be in the array. if (isset($used[$smileys[$key][0]])) { continue; } $link[] = ''.$smileys[$key][3].''; $used[$smileys[$key][0]] = TRUE; } return $link; } } // ------------------------------------------------------------------------ if ( ! function_exists('parse_smileys')) { /** * Parse Smileys * * Takes a string as input and swaps any contained smileys for the actual image * * @param string the text to be parsed * @param string the URL to the folder containing the smiley images * @param array * @return string */ function parse_smileys($str = '', $image_url = '', $smileys = NULL) { if ($image_url === '' OR ( ! is_array($smileys) && FALSE === ($smileys = _get_smiley_array()))) { return $str; } // Add a trailing slash to the file path if needed $image_url = rtrim($image_url, '/').'/'; foreach ($smileys as $key => $val) { $str = str_replace($key, ''.$smileys[$key][3].'', $str); } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('_get_smiley_array')) { /** * Get Smiley Array * * Fetches the config/smiley.php file * * @return mixed */ function _get_smiley_array() { static $_smileys; if ( ! is_array($_smileys)) { if (file_exists(APPPATH.'config/smileys.php')) { include(APPPATH.'config/smileys.php'); } if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/smileys.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/smileys.php'); } if (empty($smileys) OR ! is_array($smileys)) { $_smileys = array(); return FALSE; } $_smileys = $smileys; } return $_smileys; } } helpers/email_helper.php000064400000005326152270514220011353 0ustar00load->library('typography'); return $CI->typography->nl2br_except_pre($str); } } // ------------------------------------------------------------------------ if ( ! function_exists('auto_typography')) { /** * Auto Typography Wrapper Function * * @param string $str * @param bool $reduce_linebreaks = FALSE whether to reduce multiple instances of double newlines to two * @return string */ function auto_typography($str, $reduce_linebreaks = FALSE) { $CI =& get_instance(); $CI->load->library('typography'); return $CI->typography->auto_typography($str, $reduce_linebreaks); } } // -------------------------------------------------------------------- if ( ! function_exists('entity_decode')) { /** * HTML Entities Decode * * This function is a replacement for html_entity_decode() * * @param string * @param string * @return string */ function entity_decode($str, $charset = NULL) { return get_instance()->security->entity_decode($str, $charset); } } helpers/inflector_helper.php000064400000017244152270514220012253 0ustar00 '\1ix', '/(vert|ind)ices$/' => '\1ex', '/^(ox)en/' => '\1', '/(alias)es$/' => '\1', '/([octop|vir])i$/' => '\1us', '/(cris|ax|test)es$/' => '\1is', '/(shoe)s$/' => '\1', '/(o)es$/' => '\1', '/(bus|campus)es$/' => '\1', '/([m|l])ice$/' => '\1ouse', '/(x|ch|ss|sh)es$/' => '\1', '/(m)ovies$/' => '\1\2ovie', '/(s)eries$/' => '\1\2eries', '/([^aeiouy]|qu)ies$/' => '\1y', '/([lr])ves$/' => '\1f', '/(tive)s$/' => '\1', '/(hive)s$/' => '\1', '/([^f])ves$/' => '\1fe', '/(^analy)ses$/' => '\1sis', '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis', '/([ti])a$/' => '\1um', '/(p)eople$/' => '\1\2erson', '/(m)en$/' => '\1an', '/(s)tatuses$/' => '\1\2tatus', '/(c)hildren$/' => '\1\2hild', '/(n)ews$/' => '\1\2ews', '/(quiz)zes$/' => '\1', '/([^us])s$/' => '\1' ); foreach ($singular_rules as $rule => $replacement) { if (preg_match($rule, $result)) { $result = preg_replace($rule, $replacement, $result); break; } } return $result; } } // -------------------------------------------------------------------- if ( ! function_exists('plural')) { /** * Plural * * Takes a singular word and makes it plural * * @param string $str Input string * @return string */ function plural($str) { $result = strval($str); if ( ! word_is_countable($result)) { return $result; } $plural_rules = array( '/(quiz)$/' => '\1zes', // quizzes '/^(ox)$/' => '\1\2en', // ox '/([m|l])ouse$/' => '\1ice', // mouse, louse '/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index '/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address '/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency '/(hive)$/' => '\1s', // archive, hive '/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife '/sis$/' => 'ses', // basis, diagnosis '/([ti])um$/' => '\1a', // datum, medium '/(p)erson$/' => '\1eople', // person, salesperson '/(m)an$/' => '\1en', // man, woman, spokesman '/(c)hild$/' => '\1hildren', // child '/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato '/(bu|campu)s$/' => '\1\2ses', // bus, campus '/(alias|status|virus)$/' => '\1es', // alias '/(octop)us$/' => '\1i', // octopus '/(ax|cris|test)is$/' => '\1es', // axis, crisis '/s$/' => 's', // no change (compatibility) '/$/' => 's', ); foreach ($plural_rules as $rule => $replacement) { if (preg_match($rule, $result)) { $result = preg_replace($rule, $replacement, $result); break; } } return $result; } } // -------------------------------------------------------------------- if ( ! function_exists('camelize')) { /** * Camelize * * Takes multiple words separated by spaces or underscores and camelizes them * * @param string $str Input string * @return string */ function camelize($str) { return strtolower($str[0]).substr(str_replace(' ', '', ucwords(preg_replace('/[\s_]+/', ' ', $str))), 1); } } // -------------------------------------------------------------------- if ( ! function_exists('underscore')) { /** * Underscore * * Takes multiple words separated by spaces and underscores them * * @param string $str Input string * @return string */ function underscore($str) { return preg_replace('/[\s]+/', '_', trim(MB_ENABLED ? mb_strtolower($str) : strtolower($str))); } } // -------------------------------------------------------------------- if ( ! function_exists('humanize')) { /** * Humanize * * Takes multiple words separated by the separator and changes them to spaces * * @param string $str Input string * @param string $separator Input separator * @return string */ function humanize($str, $separator = '_') { return ucwords(preg_replace('/['.preg_quote($separator).']+/', ' ', trim(MB_ENABLED ? mb_strtolower($str) : strtolower($str)))); } } // -------------------------------------------------------------------- if ( ! function_exists('word_is_countable')) { /** * Checks if the given word has a plural version. * * @param string $word Word to check * @return bool */ function word_is_countable($word) { return ! in_array( strtolower($word), array( 'audio', 'bison', 'chassis', 'compensation', 'coreopsis', 'data', 'deer', 'education', 'emoji', 'equipment', 'fish', 'furniture', 'gold', 'information', 'knowledge', 'love', 'rain', 'money', 'moose', 'nutrition', 'offspring', 'plankton', 'pokemon', 'police', 'rice', 'series', 'sheep', 'species', 'swine', 'traffic', 'wheat' ) ); } } // -------------------------------------------------------------------- if ( ! function_exists('is_countable')) { function is_countable($word) { trigger_error('is_countable() is a native PHP function since version 7.3.0; use word_is_countable() instead', E_USER_WARNING); return word_is_countable($word); } } helpers/index.html000064400000000203152270514220010176 0ustar00 403 Forbidden

    Directory access is forbidden.

    helpers/text_helper.php000064400000034354152270514220011253 0ustar00= $n) { $out = trim($out); return (mb_strlen($out) === mb_strlen($str)) ? $out : $out.$end_char; } } } } // ------------------------------------------------------------------------ if ( ! function_exists('ascii_to_entities')) { /** * High ASCII to Entities * * Converts high ASCII text and MS Word special characters to character entities * * @param string $str * @return string */ function ascii_to_entities($str) { $out = ''; $length = defined('MB_OVERLOAD_STRING') ? mb_strlen($str, '8bit') - 1 : strlen($str) - 1; for ($i = 0, $count = 1, $temp = array(); $i <= $length; $i++) { $ordinal = ord($str[$i]); if ($ordinal < 128) { /* If the $temp array has a value but we have moved on, then it seems only fair that we output that entity and restart $temp before continuing. -Paul */ if (count($temp) === 1) { $out .= '&#'.array_shift($temp).';'; $count = 1; } $out .= $str[$i]; } else { if (count($temp) === 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) === $count) { $number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); $out .= '&#'.$number.';'; $count = 1; $temp = array(); } // If this is the last iteration, just output whatever we have elseif ($i === $length) { $out .= '&#'.implode(';', $temp).';'; } } } return $out; } } // ------------------------------------------------------------------------ if ( ! function_exists('entities_to_ascii')) { /** * Entities to ASCII * * Converts character entities back to ASCII * * @param string * @param bool * @return string */ function entities_to_ascii($str, $all = TRUE) { if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) { for ($i = 0, $s = count($matches[0]); $i < $s; $i++) { $digits = $matches[1][$i]; $out = ''; if ($digits < 128) { $out .= chr($digits); } elseif ($digits < 2048) { $out .= chr(192 + (($digits - ($digits % 64)) / 64)).chr(128 + ($digits % 64)); } else { $out .= chr(224 + (($digits - ($digits % 4096)) / 4096)) .chr(128 + ((($digits % 4096) - ($digits % 64)) / 64)) .chr(128 + ($digits % 64)); } $str = str_replace($matches[0][$i], $out, $str); } } if ($all) { return str_replace( array('&', '<', '>', '"', ''', '-'), array('&', '<', '>', '"', "'", '-'), $str ); } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('word_censor')) { /** * Word Censoring Function * * Supply a string and an array of disallowed words and any * matched words will be converted to #### or to the replacement * word you've submitted. * * @param string the text string * @param string the array of censored words * @param string the optional replacement value * @return string */ function word_censor($str, $censored, $replacement = '') { if ( ! is_array($censored)) { return $str; } $str = ' '.$str.' '; // \w, \b and a few others do not match on a unicode character // set for performance reasons. As a result words like über // will not match on a word boundary. Instead, we'll assume that // a bad word will be bookeneded by any of these characters. $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]'; foreach ($censored as $badword) { $badword = str_replace('\*', '\w*?', preg_quote($badword, '/')); if ($replacement !== '') { $str = preg_replace( "/({$delim})(".$badword.")({$delim})/i", "\\1{$replacement}\\3", $str ); } elseif (preg_match_all("/{$delim}(".$badword."){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) { $matches = $matches[1]; for ($i = count($matches) - 1; $i >= 0; $i--) { $length = strlen($matches[$i][0]); $str = substr_replace( $str, str_repeat('#', $length), $matches[$i][1], $length ); } } } return trim($str); } } // ------------------------------------------------------------------------ if ( ! function_exists('highlight_code')) { /** * Code Highlighter * * Colorizes code strings * * @param string the text string * @return string */ function highlight_code($str) { /* The highlight string function encodes and highlights * brackets so we need them to start raw. * * Also replace any existing PHP tags to temporary markers * so they don't accidentally break the string out of PHP, * and thus, thwart the highlighting. */ $str = str_replace( array('<', '>', '', '<%', '%>', '\\', ''), array('<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str ); // The highlight_string function requires that the text be surrounded // by PHP tags, which we will remove later $str = highlight_string('', TRUE); // Remove our artificially added PHP, and the syntax highlighting that came with it $str = preg_replace( array( '/<\?php( | )/i', '/(.*?)\?><\/span>\n<\/span>\n<\/code>/is', '/<\/span>/i' ), array( '', "$1\n\n", '' ), $str ); // Replace our markers back to PHP tags. return str_replace( array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), array('<?', '?>', '<%', '%>', '\\', '</script>'), $str ); } } // ------------------------------------------------------------------------ if ( ! function_exists('highlight_phrase')) { /** * Phrase Highlighter * * Highlights a phrase within a text string * * @param string $str the text string * @param string $phrase the phrase you'd like to highlight * @param string $tag_open the openging tag to precede the phrase with * @param string $tag_close the closing tag to end the phrase with * @return string */ function highlight_phrase($str, $phrase, $tag_open = '', $tag_close = '') { return ($str !== '' && $phrase !== '') ? preg_replace('/('.preg_quote($phrase, '/').')/i'.(UTF8_ENABLED ? 'u' : ''), $tag_open.'\\1'.$tag_close, $str) : $str; } } // ------------------------------------------------------------------------ if ( ! function_exists('convert_accented_characters')) { /** * Convert Accented Foreign Characters to ASCII * * @param string $str Input string * @return string */ function convert_accented_characters($str) { static $array_from, $array_to; if ( ! is_array($array_from)) { if (file_exists(APPPATH.'config/foreign_chars.php')) { include(APPPATH.'config/foreign_chars.php'); } if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'); } if (empty($foreign_characters) OR ! is_array($foreign_characters)) { $array_from = array(); $array_to = array(); return $str; } $array_from = array_keys($foreign_characters); $array_to = array_values($foreign_characters); } return preg_replace($array_from, $array_to, $str); } } // ------------------------------------------------------------------------ if ( ! function_exists('word_wrap')) { /** * Word Wrap * * Wraps text at the specified character. Maintains the integrity of words. * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor * will URLs. * * @param string $str the text string * @param int $charlim = 76 the number of characters to wrap at * @return string */ function word_wrap($str, $charlim = 76) { // Set the character limit is_numeric($charlim) OR $charlim = 76; // Reduce multiple spaces $str = preg_replace('| +|', ' ', $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } // If the current word is surrounded by {unwrap} tags we'll // strip the entire chunk and replace it with a marker. $unwrap = array(); if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches)) { for ($i = 0, $c = count($matches[0]); $i < $c; $i++) { $unwrap[] = $matches[1][$i]; $str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str); } } // Use PHP's native function to do the initial wordwrap. // We set the cut flag to FALSE so that any individual words that are // too long get left alone. In the next step we'll deal with them. $str = wordwrap($str, $charlim, "\n", FALSE); // Split the string into individual lines of text and cycle through them $output = ''; foreach (explode("\n", $str) as $line) { // Is the line within the allowed character count? // If so we'll join it to the output and continue if (mb_strlen($line) <= $charlim) { $output .= $line."\n"; continue; } $temp = ''; while (mb_strlen($line) > $charlim) { // If the over-length word is a URL we won't wrap it if (preg_match('!\[url.+\]|://|www\.!', $line)) { break; } // Trim the word down $temp .= mb_substr($line, 0, $charlim - 1); $line = mb_substr($line, $charlim - 1); } // If $temp contains data it means we had to split up an over-length // word into smaller chunks so we'll add it back to our current line if ($temp !== '') { $output .= $temp."\n".$line."\n"; } else { $output .= $line."\n"; } } // Put our markers back if (count($unwrap) > 0) { foreach ($unwrap as $key => $val) { $output = str_replace('{{unwrapped'.$key.'}}', $val, $output); } } return $output; } } // ------------------------------------------------------------------------ if ( ! function_exists('ellipsize')) { /** * Ellipsize String * * This function will strip tags from a string, split it at its max_length and ellipsize * * @param string string to ellipsize * @param int max length of string * @param mixed int (1|0) or float, .5, .2, etc for position to split * @param string ellipsis ; Default '...' * @return string ellipsized string */ function ellipsize($str, $max_length, $position = 1, $ellipsis = '…') { // Strip tags $str = trim(strip_tags($str)); // Is the string long enough to ellipsize? if (mb_strlen($str) <= $max_length) { return $str; } $beg = mb_substr($str, 0, floor($max_length * $position)); $position = ($position > 1) ? 1 : $position; if ($position === 1) { $end = mb_substr($str, 0, -($max_length - mb_strlen($beg))); } else { $end = mb_substr($str, -($max_length - mb_strlen($beg))); } return $beg.$ellipsis.$end; } } helpers/number_helper.php000064400000005767152270514220011565 0ustar00lang->load('number'); if ($num >= 1000000000000) { $num = round($num / 1099511627776, $precision); $unit = $CI->lang->line('terabyte_abbr'); } elseif ($num >= 1000000000) { $num = round($num / 1073741824, $precision); $unit = $CI->lang->line('gigabyte_abbr'); } elseif ($num >= 1000000) { $num = round($num / 1048576, $precision); $unit = $CI->lang->line('megabyte_abbr'); } elseif ($num >= 1000) { $num = round($num / 1024, $precision); $unit = $CI->lang->line('kilobyte_abbr'); } else { $unit = $CI->lang->line('bytes'); return number_format($num).' '.$unit; } return number_format($num, $precision).' '.$unit; } } helpers/form_helper.php000064400000057112152270514220011227 0ustar00config->site_url($CI->uri->uri_string()); } // If an action is not a full URL then turn it into one elseif (strpos($action, '://') === FALSE) { $action = $CI->config->site_url($action); } $attributes = _attributes_to_string($attributes); if (stripos($attributes, 'method=') === FALSE) { $attributes .= ' method="post"'; } if (stripos($attributes, 'accept-charset=') === FALSE) { $attributes .= ' accept-charset="'.strtolower(config_item('charset')).'"'; } $form = '
    \n"; if (is_array($hidden)) { foreach ($hidden as $name => $value) { $form .= ''."\n"; } } // Add CSRF field if enabled, but leave it out for GET requests and requests to external websites if ($CI->config->item('csrf_protection') === TRUE && strpos($action, $CI->config->base_url()) !== FALSE && ! stripos($form, 'method="get"')) { // Prepend/append random-length "white noise" around the CSRF // token input, as a form of protection against BREACH attacks if (FALSE !== ($noise = $CI->security->get_random_bytes(1))) { list(, $noise) = unpack('c', $noise); } else { $noise = mt_rand(-128, 127); } // Prepend if $noise has a negative value, append if positive, do nothing for zero $prepend = $append = ''; if ($noise < 0) { $prepend = str_repeat(" ", abs($noise)); } elseif ($noise > 0) { $append = str_repeat(" ", $noise); } $form .= sprintf( '%s%s%s', $prepend, $CI->security->get_csrf_token_name(), $CI->security->get_csrf_hash(), $append, "\n" ); } return $form; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_open_multipart')) { /** * Form Declaration - Multipart type * * Creates the opening portion of the form, but with "multipart/form-data". * * @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 */ 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); } } // ------------------------------------------------------------------------ if ( ! function_exists('form_hidden')) { /** * Hidden Input Field * * Generates hidden fields. You can pass a simple key/value string or * an associative array with multiple values. * * @param mixed $name Field name * @param string $value Field value * @param bool $recursing * @return string */ 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; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_input')) { /** * Text Input Field * * @param mixed * @param string * @param mixed * @return string */ function form_input($data = '', $value = '', $extra = '') { $defaults = array( 'type' => 'text', 'name' => is_array($data) ? '' : $data, 'value' => $value ); return '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_password')) { /** * Password Field * * Identical to the input function but adds the "password" type * * @param mixed * @param string * @param mixed * @return string */ function form_password($data = '', $value = '', $extra = '') { is_array($data) OR $data = array('name' => $data); $data['type'] = 'password'; return form_input($data, $value, $extra); } } // ------------------------------------------------------------------------ if ( ! function_exists('form_upload')) { /** * Upload Field * * Identical to the input function but adds the "file" type * * @param mixed * @param string * @param mixed * @return string */ function form_upload($data = '', $value = '', $extra = '') { $defaults = array('type' => 'file', 'name' => ''); is_array($data) OR $data = array('name' => $data); $data['type'] = 'file'; return '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_textarea')) { /** * Textarea field * * @param mixed $data * @param string $value * @param mixed $extra * @return string */ 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 } return '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_multiselect')) { /** * Multi-select menu * * @param string * @param array * @param mixed * @param mixed * @return string */ function form_multiselect($name = '', $options = array(), $selected = array(), $extra = '') { $extra = _attributes_to_string($extra); if (stripos($extra, 'multiple') === FALSE) { $extra .= ' multiple="multiple"'; } return form_dropdown($name, $options, $selected, $extra); } } // -------------------------------------------------------------------- if ( ! function_exists('form_dropdown')) { /** * Drop-down Menu * * @param mixed $data * @param mixed $options * @param mixed $selected * @param mixed $extra * @return string */ function form_dropdown($data = '', $options = array(), $selected = array(), $extra = '') { $defaults = array(); if (is_array($data)) { if (isset($data['selected'])) { $selected = $data['selected']; unset($data['selected']); // select tags don't have a selected attribute } if (isset($data['options'])) { $options = $data['options']; unset($data['options']); // select tags don't use an options attribute } } else { $defaults = array('name' => $data); } is_array($selected) OR $selected = array($selected); is_array($options) OR $options = array($options); // If no selected state was submitted we will attempt to set it automatically if (empty($selected)) { if (is_array($data)) { if (isset($data['name'], $_POST[$data['name']])) { $selected = array($_POST[$data['name']]); } } elseif (isset($_POST[$data])) { $selected = array($_POST[$data]); } } $extra = _attributes_to_string($extra); $multiple = (count($selected) > 1 && stripos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : ''; $form = '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_checkbox')) { /** * Checkbox Field * * @param mixed * @param string * @param bool * @param mixed * @return string */ function form_checkbox($data = '', $value = '', $checked = FALSE, $extra = '') { $defaults = array('type' => 'checkbox', 'name' => ( ! is_array($data) ? $data : ''), 'value' => $value); if (is_array($data) && 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 '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_radio')) { /** * Radio Button * * @param mixed * @param string * @param bool * @param mixed * @return string */ function form_radio($data = '', $value = '', $checked = FALSE, $extra = '') { is_array($data) OR $data = array('name' => $data); $data['type'] = 'radio'; return form_checkbox($data, $value, $checked, $extra); } } // ------------------------------------------------------------------------ if ( ! function_exists('form_submit')) { /** * Submit Button * * @param mixed * @param string * @param mixed * @return string */ function form_submit($data = '', $value = '', $extra = '') { $defaults = array( 'type' => 'submit', 'name' => is_array($data) ? '' : $data, 'value' => $value ); return '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_reset')) { /** * Reset Button * * @param mixed * @param string * @param mixed * @return string */ function form_reset($data = '', $value = '', $extra = '') { $defaults = array( 'type' => 'reset', 'name' => is_array($data) ? '' : $data, 'value' => $value ); return '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_button')) { /** * Form Button * * @param mixed * @param string * @param mixed * @return string */ function form_button($data = '', $content = '', $extra = '') { $defaults = array( 'name' => is_array($data) ? '' : $data, 'type' => 'button' ); if (is_array($data) && isset($data['content'])) { $content = $data['content']; unset($data['content']); // content is not an attribute } return '\n"; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_label')) { /** * Form Label Tag * * @param string The text to appear onscreen * @param string The id the label applies to * @param mixed Additional attributes * @return string */ function form_label($label_text = '', $id = '', $attributes = array()) { $label = ''.$label_text.''; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_fieldset')) { /** * Fieldset Tag * * Used to produce
    text. To close fieldset * use form_fieldset_close() * * @param string The legend text * @param array Additional attributes * @return string */ function form_fieldset($legend_text = '', $attributes = array()) { $fieldset = '\n"; if ($legend_text !== '') { return $fieldset.''.$legend_text."\n"; } return $fieldset; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_fieldset_close')) { /** * Fieldset Close Tag * * @param string * @return string */ function form_fieldset_close($extra = '') { return '
    '.$extra; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_close')) { /** * Form Close Tag * * @param string * @return string */ function form_close($extra = '') { return ''.$extra; } } // ------------------------------------------------------------------------ if ( ! function_exists('form_prep')) { /** * Form Prep * * Formats text so that it can be safely placed in a form field in the event it has HTML tags. * * @deprecated 3.0.0 An alias for html_escape() * @param string|string[] $str Value to escape * @return string|string[] Escaped values */ function form_prep($str) { return html_escape($str, TRUE); } } // ------------------------------------------------------------------------ if ( ! function_exists('set_value')) { /** * 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 * * @param string $field Field name * @param string $default Default value * @param bool $html_escape Whether to escape HTML special characters or not * @return string */ function set_value($field, $default = '', $html_escape = TRUE) { $CI =& get_instance(); $value = (isset($CI->form_validation) && is_object($CI->form_validation) && $CI->form_validation->has_rule($field)) ? $CI->form_validation->set_value($field, $default) : $CI->input->post($field, FALSE); isset($value) OR $value = $default; return ($html_escape) ? html_escape($value) : $value; } } // ------------------------------------------------------------------------ if ( ! function_exists('set_select')) { /** * Set Select * * Let's you set the selected value of a