diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..39f48d95 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true + +# Matches multiple files with brace expansion notation +# Set default charset +[*] +charset = utf-8 + +# Tab indentation (no size specified) +indent_style = tab diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..bdb0cabc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,17 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..0c7de110 --- /dev/null +++ b/.gitignore @@ -0,0 +1,88 @@ +*/config/development +*/logs/log-*.php +*/logs/!index.html +*/cache/* +*/cache/!index.html +*/cache/!.htaccess + +# ========================= +# Operating System Files +# ========================= + +# OSX +# ========================= + +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows +# ========================= + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Copy of CodeIgniter .gitignore file +# ========================= + +.DS_Store + +application/cache/* +!application/cache/index.html + +application/logs/* +!application/logs/index.html + +!application/*/.htaccess + +composer.lock + +user_guide_src/build/* +user_guide_src/cilexer/build/* +user_guide_src/cilexer/dist/* +user_guide_src/cilexer/pycilexer.egg-info/* +/vendor/ + +# IDE Files +#------------------------- +/nbproject/ +.idea/* + +## Sublime Text cache files +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache +*.sublime-workspace +*.sublime-project +/tests/tests/ +/tests/results/ \ No newline at end of file diff --git a/.htaccess b/.htaccess new file mode 100644 index 00000000..7eba6361 --- /dev/null +++ b/.htaccess @@ -0,0 +1,15 @@ +### CODEIGNITER ### + +# Suppress index.php from the URL + +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^(.*)$ index.php/$1 [L] + + +# Define CI execution environment : +# "development" (default) on development servers +# "testing" for running automated tests, set automatically by PHPUnit +# "production" on production servers +SetEnv CI_ENV development diff --git a/application/.htaccess b/application/.htaccess new file mode 100644 index 00000000..6c63ed4c --- /dev/null +++ b/application/.htaccess @@ -0,0 +1,6 @@ + + Require all denied + + + Deny from all + \ No newline at end of file diff --git a/application/config/autoload.php b/application/config/autoload.php new file mode 100644 index 00000000..a896b650 --- /dev/null +++ b/application/config/autoload.php @@ -0,0 +1,143 @@ + 'ua'); +*/ +$autoload['libraries'] = array('database', 'session', 'form_validation'); + +/* +| ------------------------------------------------------------------- +| Auto-load Drivers +| ------------------------------------------------------------------- +| These classes are located in system/libraries/ or in your +| application/libraries/ directory, but are also placed inside their +| own subdirectory and they extend the CI_Driver_Library class. They +| offer multiple interchangeable driver options. +| +| Prototype: +| +| $autoload['drivers'] = array('cache'); +| +| You can also supply an alternative property name to be assigned in +| the controller: +| +| $autoload['drivers'] = array('cache' => 'cch'); +| +*/ +$autoload['drivers'] = array(); + +/* +| ------------------------------------------------------------------- +| Auto-load Helper Files +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['helper'] = array('url', 'file'); +*/ +$autoload['helper'] = array('date', 'form', 'html', 'language'); +if (!defined('ENVIRONMENT') || ENVIRONMENT !== 'testing') { + /* + | Autoloading url_helper in tests does NOT work with HMVC. + | So you have to load it in the tests. + | The other option is to modify url_helper. + */ + $autoload['helper'][] = 'url'; +} + +/* +| ------------------------------------------------------------------- +| Auto-load Config files +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['config'] = array('config1', 'config2'); +| +| NOTE: This item is intended for use ONLY if you have created custom +| config files. Otherwise, leave it blank. +| +*/ +$autoload['config'] = array(); + +/* +| ------------------------------------------------------------------- +| Auto-load Language files +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['language'] = array('lang1', 'lang2'); +| +| NOTE: Do not include the "_lang" part of your file. For example +| "codeigniter_lang.php" would be referenced as array('codeigniter'); +| +*/ +$autoload['language'] = array('MY_application'); + +/* +| ------------------------------------------------------------------- +| Auto-load Models +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['model'] = array('first_model', 'second_model'); +| +| You can also supply an alternative model name to be assigned +| in the controller: +| +| $autoload['model'] = array('first_model' => 'first'); +*/ +$autoload['model'] = array(); diff --git a/application/config/config.php b/application/config/config.php new file mode 100644 index 00000000..cf4ec4f9 --- /dev/null +++ b/application/config/config.php @@ -0,0 +1,525 @@ +]+$/i +| +| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! +| +*/ +$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; + +/* +|-------------------------------------------------------------------------- +| Enable Query Strings +|-------------------------------------------------------------------------- +| +| By default CodeIgniter uses search-engine friendly segment based URLs: +| example.com/who/what/where/ +| +| You can optionally enable standard query string based URLs: +| example.com?who=me&what=something&where=here +| +| Options are: TRUE or FALSE (boolean) +| +| The other items let you set the query string 'words' that will +| invoke your controllers and its functions: +| example.com/index.php?c=controller&m=function +| +| Please note that some of the helpers won't work as expected when +| this feature is enabled, since CodeIgniter is designed primarily to +| use segment based URLs. +| +*/ +$config['enable_query_strings'] = FALSE; +$config['controller_trigger'] = 'c'; +$config['function_trigger'] = 'm'; +$config['directory_trigger'] = 'd'; + +/* +|-------------------------------------------------------------------------- +| Allow $_GET array +|-------------------------------------------------------------------------- +| +| By default CodeIgniter enables access to the $_GET array. If for some +| reason you would like to disable it, set 'allow_get_array' to FALSE. +| +| WARNING: This feature is DEPRECATED and currently available only +| for backwards compatibility purposes! +| +*/ +$config['allow_get_array'] = TRUE; + +/* +|-------------------------------------------------------------------------- +| Error Logging Threshold +|-------------------------------------------------------------------------- +| +| You can enable error logging by setting a threshold over zero. The +| threshold determines what gets logged. Threshold options are: +| +| 0 = Disables logging, Error logging TURNED OFF +| 1 = Error Messages (including PHP errors) +| 2 = Debug Messages +| 3 = Informational Messages +| 4 = All Messages +| +| You can also pass an array with threshold levels to show individual error types +| +| array(2) = Debug Messages, without Error Messages +| +| For a live site you'll usually only enable Errors (1) to be logged otherwise +| your log files will fill up very fast. +| +*/ +$config['log_threshold'] = 0; + +/* +|-------------------------------------------------------------------------- +| Error Logging Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/logs/ directory. Use a full server path with trailing slash. +| +*/ +$config['log_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Log File Extension +|-------------------------------------------------------------------------- +| +| The default filename extension for log files. The default 'php' allows for +| protecting the log files via basic scripting, when they are to be stored +| under a publicly accessible directory. +| +| Note: Leaving it blank will default to 'php'. +| +*/ +$config['log_file_extension'] = ''; + +/* +|-------------------------------------------------------------------------- +| Log File Permissions +|-------------------------------------------------------------------------- +| +| The file system permissions to be applied on newly created log files. +| +| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal +| integer notation (i.e. 0700, 0644, etc.) +*/ +$config['log_file_permissions'] = 0644; + +/* +|-------------------------------------------------------------------------- +| Date Format for Logs +|-------------------------------------------------------------------------- +| +| Each item that is logged has an associated date. You can use PHP date +| codes to set your own date formatting +| +*/ +$config['log_date_format'] = 'Y-m-d H:i:s'; + +/* +|-------------------------------------------------------------------------- +| Error Views Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/views/errors/ directory. Use a full server path with trailing slash. +| +*/ +$config['error_views_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Cache Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/cache/ directory. Use a full server path with trailing slash. +| +*/ +$config['cache_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Cache Include Query String +|-------------------------------------------------------------------------- +| +| Whether to take the URL query string into consideration when generating +| output cache files. Valid options are: +| +| FALSE = Disabled +| TRUE = Enabled, take all query parameters into account. +| Please be aware that this may result in numerous cache +| files generated for the same page over and over again. +| array('q') = Enabled, but only take into account the specified list +| of query parameters. +| +*/ +$config['cache_query_string'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Encryption Key +|-------------------------------------------------------------------------- +| +| If you use the Encryption class, you must set an encryption key. +| See the user guide for more info. +| +| https://codeigniter.com/user_guide/libraries/encryption.html +| +*/ +$config['encryption_key'] = 'k7W2DvW4Y9st'; + +/* +|-------------------------------------------------------------------------- +| Session Variables +|-------------------------------------------------------------------------- +| +| 'sess_driver' +| +| The storage driver to use: files, database, redis, memcached +| +| 'sess_cookie_name' +| +| The session cookie name, must contain only [0-9a-z_-] characters +| +| 'sess_expiration' +| +| The number of SECONDS you want the session to last. +| Setting to 0 (zero) means expire when the browser is closed. +| +| 'sess_save_path' +| +| The location to save sessions to, driver dependent. +| +| For the 'files' driver, it's a path to a writable directory. +| WARNING: Only absolute paths are supported! +| +| For the 'database' driver, it's a table name. +| Please read up the manual for the format with other session drivers. +| +| IMPORTANT: You are REQUIRED to set a valid save path! +| +| 'sess_match_ip' +| +| Whether to match the user's IP address when reading the session data. +| +| WARNING: If you're using the database driver, don't forget to update +| your session table's PRIMARY KEY when changing this setting. +| +| 'sess_time_to_update' +| +| How many seconds between CI regenerating the session ID. +| +| 'sess_regenerate_destroy' +| +| Whether to destroy session data associated with the old session ID +| when auto-regenerating the session ID. When set to FALSE, the data +| will be later deleted by the garbage collector. +| +| Other session cookie settings are shared with the rest of the application, +| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. +| +*/ +$config['sess_driver'] = 'database'; +$config['sess_cookie_name'] = 'ci_session'; +$config['sess_expiration'] = 7200; +$config['sess_save_path'] = 'ci_sessions'; +$config['sess_match_ip'] = FALSE; +$config['sess_time_to_update'] = 300; +$config['sess_regenerate_destroy'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Cookie Related Variables +|-------------------------------------------------------------------------- +| +| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions +| 'cookie_domain' = Set to .your-domain.com for site-wide cookies +| 'cookie_path' = Typically will be a forward slash +| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. +| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) +| +| Note: These settings (with the exception of 'cookie_prefix' and +| 'cookie_httponly') will also affect sessions. +| +*/ +$config['cookie_prefix'] = 'ci_packbase'; +$config['cookie_domain'] = ''; +$config['cookie_path'] = '/'; +$config['cookie_secure'] = FALSE; +$config['cookie_httponly'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Standardize newlines +|-------------------------------------------------------------------------- +| +| Determines whether to standardize newline characters in input data, +| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. +| +| WARNING: This feature is DEPRECATED and currently available only +| for backwards compatibility purposes! +| +*/ +$config['standardize_newlines'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Global XSS Filtering +|-------------------------------------------------------------------------- +| +| Determines whether the XSS filter is always active when GET, POST or +| COOKIE data is encountered +| +| WARNING: This feature is DEPRECATED and currently available only +| for backwards compatibility purposes! +| +*/ +$config['global_xss_filtering'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Cross Site Request Forgery +|-------------------------------------------------------------------------- +| Enables a CSRF cookie token to be set. When set to TRUE, token will be +| checked on a submitted form. If you are accepting user data, it is strongly +| recommended CSRF protection be enabled. +| +| 'csrf_token_name' = The token name +| 'csrf_cookie_name' = The cookie name +| 'csrf_expire' = The number in seconds the token should expire. +| 'csrf_regenerate' = Regenerate token on every submission +| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks +*/ +$config['csrf_protection'] = FALSE; +$config['csrf_token_name'] = 'csrf_test_name'; +$config['csrf_cookie_name'] = 'csrf_cookie_name'; +$config['csrf_expire'] = 7200; +$config['csrf_regenerate'] = TRUE; +$config['csrf_exclude_uris'] = array(); + +/* +|-------------------------------------------------------------------------- +| Output Compression +|-------------------------------------------------------------------------- +| +| Enables Gzip output compression for faster page loads. When enabled, +| the output class will test whether your server supports Gzip. +| Even if it does, however, not all browsers support compression +| so enable only if you are reasonably sure your visitors can handle it. +| +| Only used if zlib.output_compression is turned off in your php.ini. +| Please do not use it together with httpd-level output compression. +| +| VERY IMPORTANT: If you are getting a blank page when compression is enabled it +| means you are prematurely outputting something to your browser. It could +| even be a line of whitespace at the end of one of your scripts. For +| compression to work, nothing can be sent before the output buffer is called +| by the output class. Do not 'echo' any values with compression enabled. +| +*/ +$config['compress_output'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Master Time Reference +|-------------------------------------------------------------------------- +| +| Options are 'local' or any PHP supported timezone. This preference tells +| the system whether to use your server's local time as the master 'now' +| reference, or convert it to the configured one timezone. See the 'date +| helper' page of the user guide for information regarding date handling. +| +*/ +$config['time_reference'] = 'local'; + +/* +|-------------------------------------------------------------------------- +| Rewrite PHP Short Tags +|-------------------------------------------------------------------------- +| +| If your PHP installation does not have short tag support enabled CI +| can rewrite the tags on-the-fly, enabling you to utilize that syntax +| in your view files. Options are TRUE or FALSE (boolean) +| +| Note: You need to have eval() enabled for this to work. +| +*/ +$config['rewrite_short_tags'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Reverse Proxy IPs +|-------------------------------------------------------------------------- +| +| If your server is behind a reverse proxy, you must whitelist the proxy +| IP addresses from which CodeIgniter should trust headers such as +| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify +| the visitor's IP address. +| +| You can use both an array or a comma-separated list of proxy addresses, +| as well as specifying whole subnets. Here are a few examples: +| +| Comma-separated: '10.0.1.200,192.168.5.0/24' +| Array: array('10.0.1.200', '192.168.5.0/24') +*/ +$config['proxy_ips'] = ''; diff --git a/application/config/constants.php b/application/config/constants.php new file mode 100644 index 00000000..18d3b4b7 --- /dev/null +++ b/application/config/constants.php @@ -0,0 +1,85 @@ +db->last_query() and profiling of DB queries. +| When you run a query, with this setting set to TRUE (default), +| CodeIgniter will store the SQL statement for debugging purposes. +| However, this may cause high memory usage, especially if you run +| a lot of SQL queries ... disable this to avoid that problem. +| +| The $active_group variable lets you choose which connection group to +| make active. By default there is only one group (the 'default' group). +| +| The $query_builder variables lets you determine whether or not to load +| the query builder class. +*/ +$active_group = 'default'; +$query_builder = TRUE; + +$db['default'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => '', + 'database' => 'plafor', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => (ENVIRONMENT !== 'production'), + 'cache_on' => FALSE, + 'cachedir' => '', + 'char_set' => 'utf8', + 'dbcollat' => 'utf8_general_ci', + 'swap_pre' => '', + 'encrypt' => FALSE, + 'compress' => FALSE, + 'stricton' => FALSE, + 'failover' => array(), + 'save_queries' => TRUE +); diff --git a/application/config/doctypes.php b/application/config/doctypes.php new file mode 100644 index 00000000..59a7991e --- /dev/null +++ b/application/config/doctypes.php @@ -0,0 +1,24 @@ + '', + 'xhtml1-strict' => '', + 'xhtml1-trans' => '', + 'xhtml1-frame' => '', + 'xhtml-basic11' => '', + 'html5' => '', + 'html4-strict' => '', + 'html4-trans' => '', + 'html4-frame' => '', + 'mathml1' => '', + 'mathml2' => '', + 'svg10' => '', + 'svg11' => '', + 'svg11-basic' => '', + 'svg11-tiny' => '', + 'xhtml-math-svg-xh' => '', + 'xhtml-math-svg-sh' => '', + 'xhtml-rdfa-1' => '', + 'xhtml-rdfa-2' => '' +); diff --git a/application/config/foreign_chars.php b/application/config/foreign_chars.php new file mode 100644 index 00000000..995f4830 --- /dev/null +++ b/application/config/foreign_chars.php @@ -0,0 +1,103 @@ + 'ae', + '/ö|œ/' => 'oe', + '/ü/' => 'ue', + '/Ä/' => 'Ae', + '/Ü/' => 'Ue', + '/Ö/' => 'Oe', + '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|Α|Ά|Ả|Ạ|Ầ|Ẫ|Ẩ|Ậ|Ằ|Ắ|Ẵ|Ẳ|Ặ|А/' => 'A', + '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|α|ά|ả|ạ|ầ|ấ|ẫ|ẩ|ậ|ằ|ắ|ẵ|ẳ|ặ|а/' => 'a', + '/Б/' => 'B', + '/б/' => 'b', + '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', + '/ç|ć|ĉ|ċ|č/' => 'c', + '/Д/' => 'D', + '/д/' => 'd', + '/Ð|Ď|Đ|Δ/' => 'Dj', + '/ð|ď|đ|δ/' => 'dj', + '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Ε|Έ|Ẽ|Ẻ|Ẹ|Ề|Ế|Ễ|Ể|Ệ|Е|Э/' => 'E', + '/è|é|ê|ë|ē|ĕ|ė|ę|ě|έ|ε|ẽ|ẻ|ẹ|ề|ế|ễ|ể|ệ|е|э/' => 'e', + '/Ф/' => 'F', + '/ф/' => 'f', + '/Ĝ|Ğ|Ġ|Ģ|Γ|Г|Ґ/' => 'G', + '/ĝ|ğ|ġ|ģ|γ|г|ґ/' => 'g', + '/Ĥ|Ħ/' => 'H', + '/ĥ|ħ/' => 'h', + '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|Η|Ή|Ί|Ι|Ϊ|Ỉ|Ị|И|Ы/' => 'I', + '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|η|ή|ί|ι|ϊ|ỉ|ị|и|ы|ї/' => 'i', + '/Ĵ/' => 'J', + '/ĵ/' => 'j', + '/Ķ|Κ|К/' => 'K', + '/ķ|κ|к/' => 'k', + '/Ĺ|Ļ|Ľ|Ŀ|Ł|Λ|Л/' => 'L', + '/ĺ|ļ|ľ|ŀ|ł|λ|л/' => 'l', + '/М/' => 'M', + '/м/' => 'm', + '/Ñ|Ń|Ņ|Ň|Ν|Н/' => 'N', + '/ñ|ń|ņ|ň|ʼn|ν|н/' => 'n', + '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|Ο|Ό|Ω|Ώ|Ỏ|Ọ|Ồ|Ố|Ỗ|Ổ|Ộ|Ờ|Ớ|Ỡ|Ở|Ợ|О/' => 'O', + '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|ο|ό|ω|ώ|ỏ|ọ|ồ|ố|ỗ|ổ|ộ|ờ|ớ|ỡ|ở|ợ|о/' => 'o', + '/П/' => 'P', + '/п/' => 'p', + '/Ŕ|Ŗ|Ř|Ρ|Р/' => 'R', + '/ŕ|ŗ|ř|ρ|р/' => 'r', + '/Ś|Ŝ|Ş|Ș|Š|Σ|С/' => 'S', + '/ś|ŝ|ş|ș|š|ſ|σ|ς|с/' => 's', + '/Ț|Ţ|Ť|Ŧ|τ|Т/' => 'T', + '/ț|ţ|ť|ŧ|т/' => 't', + '/Þ|þ/' => 'th', + '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|Ũ|Ủ|Ụ|Ừ|Ứ|Ữ|Ử|Ự|У/' => 'U', + '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|υ|ύ|ϋ|ủ|ụ|ừ|ứ|ữ|ử|ự|у/' => 'u', + '/Ƴ|Ɏ|Ỵ|Ẏ|Ӳ|Ӯ|Ў|Ý|Ÿ|Ŷ|Υ|Ύ|Ϋ|Ỳ|Ỹ|Ỷ|Ỵ|Й/' => 'Y', + '/ẙ|ʏ|ƴ|ɏ|ỵ|ẏ|ӳ|ӯ|ў|ý|ÿ|ŷ|ỳ|ỹ|ỷ|ỵ|й/' => 'y', + '/В/' => 'V', + '/в/' => 'v', + '/Ŵ/' => 'W', + '/ŵ/' => 'w', + '/Ź|Ż|Ž|Ζ|З/' => 'Z', + '/ź|ż|ž|ζ|з/' => 'z', + '/Æ|Ǽ/' => 'AE', + '/ß/' => 'ss', + '/IJ/' => 'IJ', + '/ij/' => 'ij', + '/Œ/' => 'OE', + '/ƒ/' => 'f', + '/ξ/' => 'ks', + '/π/' => 'p', + '/β/' => 'v', + '/μ/' => 'm', + '/ψ/' => 'ps', + '/Ё/' => 'Yo', + '/ё/' => 'yo', + '/Є/' => 'Ye', + '/є/' => 'ye', + '/Ї/' => 'Yi', + '/Ж/' => 'Zh', + '/ж/' => 'zh', + '/Х/' => 'Kh', + '/х/' => 'kh', + '/Ц/' => 'Ts', + '/ц/' => 'ts', + '/Ч/' => 'Ch', + '/ч/' => 'ch', + '/Ш/' => 'Sh', + '/ш/' => 'sh', + '/Щ/' => 'Shch', + '/щ/' => 'shch', + '/Ъ|ъ|Ь|ь/' => '', + '/Ю/' => 'Yu', + '/ю/' => 'yu', + '/Я/' => 'Ya', + '/я/' => 'ya' +); diff --git a/application/config/hooks.php b/application/config/hooks.php new file mode 100644 index 00000000..a8f38a5d --- /dev/null +++ b/application/config/hooks.php @@ -0,0 +1,13 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/config/memcached.php b/application/config/memcached.php new file mode 100644 index 00000000..5c23b39c --- /dev/null +++ b/application/config/memcached.php @@ -0,0 +1,19 @@ + array( + 'hostname' => '127.0.0.1', + 'port' => '11211', + 'weight' => '1', + ), +); diff --git a/application/config/migration.php b/application/config/migration.php new file mode 100644 index 00000000..4b585a65 --- /dev/null +++ b/application/config/migration.php @@ -0,0 +1,84 @@ +migration->current() this is the version that schema will +| be upgraded / downgraded to. +| +*/ +$config['migration_version'] = 0; + +/* +|-------------------------------------------------------------------------- +| Migrations Path +|-------------------------------------------------------------------------- +| +| Path to your migrations folder. +| Typically, it will be within your application path. +| Also, writing permission is required within the migrations path. +| +*/ +$config['migration_path'] = APPPATH.'migrations/'; diff --git a/application/config/mimes.php b/application/config/mimes.php new file mode 100644 index 00000000..7aa5c9e4 --- /dev/null +++ b/application/config/mimes.php @@ -0,0 +1,184 @@ + array('application/mac-binhex40', 'application/mac-binhex', 'application/x-binhex40', 'application/x-mac-binhex40'), + 'cpt' => 'application/mac-compactpro', + 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'), + 'bin' => array('application/macbinary', 'application/mac-binary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'), + 'dms' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'exe' => array('application/octet-stream', 'application/x-msdownload'), + 'class' => 'application/octet-stream', + 'psd' => array('application/x-photoshop', 'image/vnd.adobe.photoshop'), + 'so' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => array('application/pdf', 'application/force-download', 'application/x-download', 'binary/octet-stream'), + 'ai' => array('application/pdf', 'application/postscript'), + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => array('application/vnd.ms-excel', 'application/msexcel', 'application/x-msexcel', 'application/x-ms-excel', 'application/x-excel', 'application/x-dos_ms_excel', 'application/xls', 'application/x-xls', 'application/excel', 'application/download', 'application/vnd.ms-office', 'application/msword'), + 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint', 'application/vnd.ms-office', 'application/msword'), + 'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-zip', 'application/zip'), + 'wbxml' => 'application/wbxml', + 'wmlc' => 'application/wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'gz' => 'application/x-gzip', + 'gzip' => 'application/x-gzip', + 'php' => array('application/x-httpd-php', 'application/php', 'application/x-php', 'text/php', 'text/x-php', 'application/x-httpd-php-source'), + 'php4' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => array('application/x-javascript', 'text/plain'), + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => array('application/x-tar', 'application/x-gzip-compressed'), + 'z' => 'application/x-compress', + 'xhtml' => 'application/xhtml+xml', + 'xht' => 'application/xhtml+xml', + 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed', 'application/s-compressed', 'multipart/x-zip'), + 'rar' => array('application/x-rar', 'application/rar', 'application/x-rar-compressed'), + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mpga' => 'audio/mpeg', + 'mp2' => 'audio/mpeg', + 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'), + 'aif' => array('audio/x-aiff', 'audio/aiff'), + 'aiff' => array('audio/x-aiff', 'audio/aiff'), + 'aifc' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'rv' => 'video/vnd.rn-realvideo', + 'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'), + 'bmp' => array('image/bmp', 'image/x-bmp', 'image/x-bitmap', 'image/x-xbitmap', 'image/x-win-bitmap', 'image/x-windows-bmp', 'image/ms-bmp', 'image/x-ms-bmp', 'application/bmp', 'application/x-bmp', 'application/x-win-bitmap'), + 'gif' => 'image/gif', + 'jpeg' => array('image/jpeg', 'image/pjpeg'), + 'jpg' => array('image/jpeg', 'image/pjpeg'), + 'jpe' => array('image/jpeg', 'image/pjpeg'), + 'jp2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'j2k' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'jpf' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'jpg2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'jpx' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'jpm' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'mj2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'mjp2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'), + 'png' => array('image/png', 'image/x-png'), + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'css' => array('text/css', 'text/plain'), + 'html' => array('text/html', 'text/plain'), + 'htm' => array('text/html', 'text/plain'), + 'shtml' => array('text/html', 'text/plain'), + 'txt' => 'text/plain', + 'text' => 'text/plain', + 'log' => array('text/plain', 'text/x-log'), + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => array('application/xml', 'text/xml', 'text/plain'), + 'xsl' => array('application/xml', 'text/xsl', 'text/xml'), + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'avi' => array('video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'), + 'movie' => 'video/x-sgi-movie', + 'doc' => array('application/msword', 'application/vnd.ms-office'), + 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip'), + 'dot' => array('application/msword', 'application/vnd.ms-office'), + 'dotx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword'), + 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel', 'application/msword', 'application/x-zip'), + 'word' => array('application/msword', 'application/octet-stream'), + 'xl' => 'application/excel', + 'eml' => 'message/rfc822', + 'json' => array('application/json', 'text/json'), + 'pem' => array('application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream'), + 'p10' => array('application/x-pkcs10', 'application/pkcs10'), + 'p12' => 'application/x-pkcs12', + 'p7a' => 'application/x-pkcs7-signature', + 'p7c' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'), + 'p7m' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'), + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'crt' => array('application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert'), + 'crl' => array('application/pkix-crl', 'application/pkcs-crl'), + 'der' => 'application/x-x509-ca-cert', + 'kdb' => 'application/octet-stream', + 'pgp' => 'application/pgp', + 'gpg' => 'application/gpg-keys', + 'sst' => 'application/octet-stream', + 'csr' => 'application/octet-stream', + 'rsa' => 'application/x-pkcs7', + 'cer' => array('application/pkix-cert', 'application/x-x509-ca-cert'), + '3g2' => 'video/3gpp2', + '3gp' => array('video/3gp', 'video/3gpp'), + 'mp4' => 'video/mp4', + 'm4a' => 'audio/x-m4a', + 'f4v' => array('video/mp4', 'video/x-f4v'), + 'flv' => 'video/x-flv', + 'webm' => 'video/webm', + 'aac' => array('audio/x-aac', 'audio/aac'), + 'm4u' => 'application/vnd.mpegurl', + 'm3u' => 'text/plain', + 'xspf' => 'application/xspf+xml', + 'vlc' => 'application/videolan', + 'wmv' => array('video/x-ms-wmv', 'video/x-ms-asf'), + 'au' => 'audio/x-au', + 'ac3' => 'audio/ac3', + 'flac' => 'audio/x-flac', + 'ogg' => array('audio/ogg', 'video/ogg', 'application/ogg'), + 'kmz' => array('application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip'), + 'kml' => array('application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml'), + 'ics' => 'text/calendar', + 'ical' => 'text/calendar', + 'zsh' => 'text/x-scriptzsh', + '7z' => array('application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'), + '7zip' => array('application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'), + 'cdr' => array('application/cdr', 'application/coreldraw', 'application/x-cdr', 'application/x-coreldraw', 'image/cdr', 'image/x-cdr', 'zz-application/zz-winassoc-cdr'), + 'wma' => array('audio/x-ms-wma', 'video/x-ms-asf'), + 'jar' => array('application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed'), + 'svg' => array('image/svg+xml', 'application/xml', 'text/xml'), + 'vcf' => 'text/x-vcard', + 'srt' => array('text/srt', 'text/plain'), + 'vtt' => array('text/vtt', 'text/plain'), + 'ico' => array('image/x-icon', 'image/x-ico', 'image/vnd.microsoft.icon'), + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'otf' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web' +); diff --git a/application/config/profiler.php b/application/config/profiler.php new file mode 100644 index 00000000..3db22e39 --- /dev/null +++ b/application/config/profiler.php @@ -0,0 +1,14 @@ + my_controller/index +| my-controller/my-method -> my_controller/my_method +*/ +$route['default_controller'] = 'welcome'; +$route['404_override'] = ''; +$route['translate_uri_dashes'] = FALSE; diff --git a/application/config/smileys.php b/application/config/smileys.php new file mode 100644 index 00000000..abf9a898 --- /dev/null +++ b/application/config/smileys.php @@ -0,0 +1,64 @@ + array('grin.gif', '19', '19', 'grin'), + ':lol:' => array('lol.gif', '19', '19', 'LOL'), + ':cheese:' => array('cheese.gif', '19', '19', 'cheese'), + ':)' => array('smile.gif', '19', '19', 'smile'), + ';-)' => array('wink.gif', '19', '19', 'wink'), + ';)' => array('wink.gif', '19', '19', 'wink'), + ':smirk:' => array('smirk.gif', '19', '19', 'smirk'), + ':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'), + ':-S' => array('confused.gif', '19', '19', 'confused'), + ':wow:' => array('surprise.gif', '19', '19', 'surprised'), + ':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'), + ':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'), + '%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'), + ';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'), + ':P' => array('raspberry.gif', '19', '19', 'raspberry'), + ':blank:' => array('blank.gif', '19', '19', 'blank stare'), + ':long:' => array('longface.gif', '19', '19', 'long face'), + ':ohh:' => array('ohh.gif', '19', '19', 'ohh'), + ':grrr:' => array('grrr.gif', '19', '19', 'grrr'), + ':gulp:' => array('gulp.gif', '19', '19', 'gulp'), + '8-/' => array('ohoh.gif', '19', '19', 'oh oh'), + ':down:' => array('downer.gif', '19', '19', 'downer'), + ':red:' => array('embarrassed.gif', '19', '19', 'red face'), + ':sick:' => array('sick.gif', '19', '19', 'sick'), + ':shut:' => array('shuteye.gif', '19', '19', 'shut eye'), + ':-/' => array('hmm.gif', '19', '19', 'hmmm'), + '>:(' => array('mad.gif', '19', '19', 'mad'), + ':mad:' => array('mad.gif', '19', '19', 'mad'), + '>:-(' => array('angry.gif', '19', '19', 'angry'), + ':angry:' => array('angry.gif', '19', '19', 'angry'), + ':zip:' => array('zip.gif', '19', '19', 'zipper'), + ':kiss:' => array('kiss.gif', '19', '19', 'kiss'), + ':ahhh:' => array('shock.gif', '19', '19', 'shock'), + ':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'), + ':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'), + ':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'), + ':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'), + ':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'), + ':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'), + ':vampire:' => array('vampire.gif', '19', '19', 'vampire'), + ':snake:' => array('snake.gif', '19', '19', 'snake'), + ':exclaim:' => array('exclaim.gif', '19', '19', 'exclaim'), + ':question:' => array('question.gif', '19', '19', 'question') + +); diff --git a/application/config/user_agents.php b/application/config/user_agents.php new file mode 100644 index 00000000..b6c85631 --- /dev/null +++ b/application/config/user_agents.php @@ -0,0 +1,214 @@ + 'Windows 10', + 'windows nt 6.3' => 'Windows 8.1', + 'windows nt 6.2' => 'Windows 8', + 'windows nt 6.1' => 'Windows 7', + 'windows nt 6.0' => 'Windows Vista', + 'windows nt 5.2' => 'Windows 2003', + 'windows nt 5.1' => 'Windows XP', + 'windows nt 5.0' => 'Windows 2000', + 'windows nt 4.0' => 'Windows NT 4.0', + 'winnt4.0' => 'Windows NT 4.0', + 'winnt 4.0' => 'Windows NT', + 'winnt' => 'Windows NT', + 'windows 98' => 'Windows 98', + 'win98' => 'Windows 98', + 'windows 95' => 'Windows 95', + 'win95' => 'Windows 95', + 'windows phone' => 'Windows Phone', + 'windows' => 'Unknown Windows OS', + 'android' => 'Android', + 'blackberry' => 'BlackBerry', + 'iphone' => 'iOS', + 'ipad' => 'iOS', + 'ipod' => 'iOS', + 'os x' => 'Mac OS X', + 'ppc mac' => 'Power PC Mac', + 'freebsd' => 'FreeBSD', + 'ppc' => 'Macintosh', + 'linux' => 'Linux', + 'debian' => 'Debian', + 'sunos' => 'Sun Solaris', + 'beos' => 'BeOS', + 'apachebench' => 'ApacheBench', + 'aix' => 'AIX', + 'irix' => 'Irix', + 'osf' => 'DEC OSF', + 'hp-ux' => 'HP-UX', + 'netbsd' => 'NetBSD', + 'bsdi' => 'BSDi', + 'openbsd' => 'OpenBSD', + 'gnu' => 'GNU/Linux', + 'unix' => 'Unknown Unix OS', + 'symbian' => 'Symbian OS' +); + + +// The order of this array should NOT be changed. Many browsers return +// multiple browser types so we want to identify the sub-type first. +$browsers = array( + 'OPR' => 'Opera', + 'Flock' => 'Flock', + 'Edge' => 'Edge', + 'Chrome' => 'Chrome', + // Opera 10+ always reports Opera/9.80 and appends Version/ to the user agent string + 'Opera.*?Version' => 'Opera', + 'Opera' => 'Opera', + 'MSIE' => 'Internet Explorer', + 'Internet Explorer' => 'Internet Explorer', + 'Trident.* rv' => 'Internet Explorer', + 'Shiira' => 'Shiira', + 'Firefox' => 'Firefox', + 'Chimera' => 'Chimera', + 'Phoenix' => 'Phoenix', + 'Firebird' => 'Firebird', + 'Camino' => 'Camino', + 'Netscape' => 'Netscape', + 'OmniWeb' => 'OmniWeb', + 'Safari' => 'Safari', + 'Mozilla' => 'Mozilla', + 'Konqueror' => 'Konqueror', + 'icab' => 'iCab', + 'Lynx' => 'Lynx', + 'Links' => 'Links', + 'hotjava' => 'HotJava', + 'amaya' => 'Amaya', + 'IBrowse' => 'IBrowse', + 'Maxthon' => 'Maxthon', + 'Ubuntu' => 'Ubuntu Web Browser' +); + +$mobiles = array( + // legacy array, old values commented out + 'mobileexplorer' => 'Mobile Explorer', +// 'openwave' => 'Open Wave', +// 'opera mini' => 'Opera Mini', +// 'operamini' => 'Opera Mini', +// 'elaine' => 'Palm', + 'palmsource' => 'Palm', +// 'digital paths' => 'Palm', +// 'avantgo' => 'Avantgo', +// 'xiino' => 'Xiino', + 'palmscape' => 'Palmscape', +// 'nokia' => 'Nokia', +// 'ericsson' => 'Ericsson', +// 'blackberry' => 'BlackBerry', +// 'motorola' => 'Motorola' + + // Phones and Manufacturers + 'motorola' => 'Motorola', + 'nokia' => 'Nokia', + 'palm' => 'Palm', + 'iphone' => 'Apple iPhone', + 'ipad' => 'iPad', + 'ipod' => 'Apple iPod Touch', + 'sony' => 'Sony Ericsson', + 'ericsson' => 'Sony Ericsson', + 'blackberry' => 'BlackBerry', + 'cocoon' => 'O2 Cocoon', + 'blazer' => 'Treo', + 'lg' => 'LG', + 'amoi' => 'Amoi', + 'xda' => 'XDA', + 'mda' => 'MDA', + 'vario' => 'Vario', + 'htc' => 'HTC', + 'samsung' => 'Samsung', + 'sharp' => 'Sharp', + 'sie-' => 'Siemens', + 'alcatel' => 'Alcatel', + 'benq' => 'BenQ', + 'ipaq' => 'HP iPaq', + 'mot-' => 'Motorola', + 'playstation portable' => 'PlayStation Portable', + 'playstation 3' => 'PlayStation 3', + 'playstation vita' => 'PlayStation Vita', + 'hiptop' => 'Danger Hiptop', + 'nec-' => 'NEC', + 'panasonic' => 'Panasonic', + 'philips' => 'Philips', + 'sagem' => 'Sagem', + 'sanyo' => 'Sanyo', + 'spv' => 'SPV', + 'zte' => 'ZTE', + 'sendo' => 'Sendo', + 'nintendo dsi' => 'Nintendo DSi', + 'nintendo ds' => 'Nintendo DS', + 'nintendo 3ds' => 'Nintendo 3DS', + 'wii' => 'Nintendo Wii', + 'open web' => 'Open Web', + 'openweb' => 'OpenWeb', + + // Operating Systems + 'android' => 'Android', + 'symbian' => 'Symbian', + 'SymbianOS' => 'SymbianOS', + 'elaine' => 'Palm', + 'series60' => 'Symbian S60', + 'windows ce' => 'Windows CE', + + // Browsers + 'obigo' => 'Obigo', + 'netfront' => 'Netfront Browser', + 'openwave' => 'Openwave Browser', + 'mobilexplorer' => 'Mobile Explorer', + 'operamini' => 'Opera Mini', + 'opera mini' => 'Opera Mini', + 'opera mobi' => 'Opera Mobile', + 'fennec' => 'Firefox Mobile', + + // Other + 'digital paths' => 'Digital Paths', + 'avantgo' => 'AvantGo', + 'xiino' => 'Xiino', + 'novarra' => 'Novarra Transcoder', + 'vodafone' => 'Vodafone', + 'docomo' => 'NTT DoCoMo', + 'o2' => 'O2', + + // Fallback + 'mobile' => 'Generic Mobile', + 'wireless' => 'Generic Mobile', + 'j2me' => 'Generic Mobile', + 'midp' => 'Generic Mobile', + 'cldc' => 'Generic Mobile', + 'up.link' => 'Generic Mobile', + 'up.browser' => 'Generic Mobile', + 'smartphone' => 'Generic Mobile', + 'cellphone' => 'Generic Mobile' +); + +// There are hundreds of bots but these are the most common. +$robots = array( + 'googlebot' => 'Googlebot', + 'msnbot' => 'MSNBot', + 'baiduspider' => 'Baiduspider', + 'bingbot' => 'Bing', + 'slurp' => 'Inktomi Slurp', + 'yahoo' => 'Yahoo', + 'ask jeeves' => 'Ask Jeeves', + 'fastcrawler' => 'FastCrawler', + 'infoseek' => 'InfoSeek Robot 1.0', + 'lycos' => 'Lycos', + 'yandex' => 'YandexBot', + 'mediapartners-google' => 'MediaPartners Google', + 'CRAZYWEBCRAWLER' => 'Crazy Webcrawler', + 'adsbot-google' => 'AdsBot Google', + 'feedfetcher-google' => 'Feedfetcher Google', + 'curious george' => 'Curious George', + 'ia_archiver' => 'Alexa Crawler', + 'MJ12bot' => 'Majestic-12', + 'Uptimebot' => 'Uptimebot' +); diff --git a/application/controllers/index.html b/application/controllers/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/controllers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/core/MY_Controller.php b/application/core/MY_Controller.php new file mode 100644 index 00000000..df7bc3b7 --- /dev/null +++ b/application/core/MY_Controller.php @@ -0,0 +1,107 @@ + + */ + +class MY_Controller extends MX_Controller +{ + + /** + * '*' for all users + * '@' for logged in users + * '0, 1, 2, 4, 8, ...' for access level (power of 2) + */ + protected $access_level = "*"; + + public function __construct() + { + parent::__construct(); + + /* Check permission on construct */ + if (!$this->check_permission()) { + show_error(lang('msg_err_access_denied_message'), 403, lang('msg_err_access_denied_header')); + } + } + + /** + * Check if user access level matches the required access level. + * Required level can be the controller's default level or a custom + * specified level. + * + * @param $required_level : minimum level required to get permission + * @return bool : true if user level is equal or higher than required level, + * false else + */ + protected function check_permission($required_level = NULL) + { + if (!isset($_SESSION['logged_in'])) { + // Tests can accidentally delete $_SESSION, + // this makes sure it always exists. + $_SESSION['logged_in'] = FALSE; + } + if (is_null($required_level)) { + $required_level = $this->access_level; + } + + if ($required_level == "*") { + // page is accessible for all users + return true; + } + else { + // check if user is logged in + // if not, redirect to login page + if ($_SESSION['logged_in'] != true) { + redirect("user/auth/login"); + } + // check if page is accessible for all logged in users + elseif ($required_level == "@") { + return true; + } + // check access level + elseif ($required_level <= $_SESSION['user_access']) { + return true; + } + // no permission + else { + return false; + } + } + } + + + /** + * Display the view, adding header, footer and any other common view part + * + * @param $view_parts : single view or array of view parts to display + * $data : data array to send to the view + */ + public function display_view($view_parts, $data = NULL) + { + // If not defined in $data, set page title to empty string + if (!isset($data['title'])) { + $data['title'] = ''; + } + + // Display common headers + $this->load->view('common/header', $data); + $this->load->view('common/login_bar'); + + if (is_array($view_parts)) { + // Display multiple view parts defined in $data + foreach ($view_parts as $view_part) { + $this->load->view($view_part, $data); + } + } + elseif (is_string($view_parts)) { + // Display unique view part defined in $data + $this->load->view($view_parts, $data); + } + + // Display common footer + $this->load->view('common/footer'); + } +} diff --git a/application/core/MY_Exceptions.php b/application/core/MY_Exceptions.php new file mode 100644 index 00000000..2ba4a32d --- /dev/null +++ b/application/core/MY_Exceptions.php @@ -0,0 +1,49 @@ +'.(is_array($message) ? implode('

', $message) : $message).'

'; + $template = 'html'.DIRECTORY_SEPARATOR.$template; + } + + // Default to application/views/common + $common_templates_path = VIEWPATH.'common'.DIRECTORY_SEPARATOR; + if (!file_exists($common_templates_path)) { + // Select the views in the common module + $common_templates_path = APPPATH.'modules'.DIRECTORY_SEPARATOR.'common'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR; + } + + if (ob_get_level() > $this->ob_level + 1) + { + ob_end_flush(); + } + ob_start(); + if (!is_cli()) { + include($common_templates_path.'header.php'); + include($common_templates_path.'login_bar.php'); + } + include($errors_templates_path.$template.'.php'); + if (!is_cli()) { + include($common_templates_path.'footer.php'); + } + $buffer = ob_get_contents(); + ob_end_clean(); + return $buffer; + } +} \ No newline at end of file diff --git a/application/core/MY_Loader.php b/application/core/MY_Loader.php new file mode 100644 index 00000000..20633702 --- /dev/null +++ b/application/core/MY_Loader.php @@ -0,0 +1,8 @@ + + * + * @author modified and completed by Orif (ViDi) + * @link https://github.com/OrifInformatique/ + * @copyright Copyright (c) 2019, Orif + */ +class MY_Model extends CI_Model +{ + + /* -------------------------------------------------------------- + * VARIABLES + * ------------------------------------------------------------ */ + + /** + * This model's default database table. Automatically + * guessed by pluralising the model name. + */ + protected $_table; + + /** + * The database connection object. Will be set to the default + * connection. This allows individual models to use different DBs + * without overwriting CI's global $this->db connection. + */ + public $_database; + + /** + * This model's default primary key or unique identifier. + * Used by the get(), update() and delete() functions. + */ + protected $primary_key = 'id'; + + /** + * Support for soft deletes and this model's 'deleted' key + */ + protected $soft_delete = FALSE; + protected $soft_delete_key = 'deleted'; + protected $_temporary_with_deleted = FALSE; + protected $_temporary_only_deleted = FALSE; + + /** + * The various callbacks available to the model. Each are + * simple lists of method names (methods will be run on $this). + */ + protected $before_create = array(); + protected $after_create = array(); + protected $before_update = array(); + protected $after_update = array(); + protected $before_get = array(); + protected $after_get = array(); + protected $before_delete = array(); + protected $after_delete = array(); + + protected $callback_parameters = array(); + + /** + * Protected, non-modifiable attributes + */ + protected $protected_attributes = array(); + + /** + * Relationship arrays. Use flat strings for defaults or string + * => array to customise the class name and primary key + */ + protected $belongs_to = array(); + protected $has_many = array(); + + protected $_with = array(); + + /** + * An array of validation rules. This needs to be the same format + * as validation rules passed to the Form_validation library. + */ + protected $validate = array(); + + /** + * Optionally skip the validation. Used in conjunction with + * skip_validation() to skip data validation for any future calls. + */ + protected $skip_validation = FALSE; + + /** + * By default we return our results as objects. If we need to override + * this, we can, or, we could use the `as_array()` and `as_object()` scopes. + */ + protected $return_type = 'object'; + protected $_temporary_return_type = NULL; + + /* -------------------------------------------------------------- + * GENERIC METHODS + * ------------------------------------------------------------ */ + + /** + * Initialise the model, tie into the CodeIgniter superobject and + * try our best to guess the table name. + */ + public function __construct() + { + parent::__construct(); + + $this->load->helper('inflector'); + + $this->_fetch_table(); + + $this->_database = $this->db; + + array_unshift($this->before_create, 'protect_attributes'); + array_unshift($this->before_update, 'protect_attributes'); + + $this->_temporary_return_type = $this->return_type; + } + + /* -------------------------------------------------------------- + * CRUD INTERFACE + * ------------------------------------------------------------ */ + + /** + * Fetch a single record based on the primary key. Returns an object. + */ + public function get($primary_value) + { + return $this->get_by($this->primary_key, $primary_value); + } + + /** + * Fetch a single record based on an arbitrary WHERE call. Can be + * any valid value to $this->_database->where(). + */ + public function get_by() + { + $where = func_get_args(); + + if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE) + { + $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted); + } + + $this->_set_where($where); + + $this->trigger('before_get'); + + $row = $this->_database->get($this->_table) + ->{$this->_return_type()}(); + $this->_temporary_return_type = $this->return_type; + + $row = $this->trigger('after_get', $row); + + $this->_with = array(); + return $row; + } + + /** + * Fetch an array of records based on an array of primary values. + */ + public function get_many($values) + { + $this->_database->where_in($this->primary_key, $values); + + return $this->get_all(); + } + + /** + * Fetch an array of records based on an arbitrary WHERE call. + */ + public function get_many_by() + { + $where = func_get_args(); + + $this->_set_where($where); + + return $this->get_all(); + } + + /** + * Fetch all the records in the table. Can be used as a generic call + * to $this->_database->get() with scoped methods. + */ + public function get_all() + { + $this->trigger('before_get'); + + if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE) + { + $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted); + } + + $result = $this->_database->get($this->_table) + ->{$this->_return_type(1)}(); + $this->_temporary_return_type = $this->return_type; + + foreach ($result as $key => &$row) + { + $row = $this->trigger('after_get', $row, ($key == count($result) - 1)); + } + + $this->_with = array(); + return $result; + } + + /** + * Insert a new row into the table. $data should be an associative array + * of data to be inserted. Returns newly created ID. + */ + public function insert($data, $skip_validation = FALSE) + { + if ($skip_validation === FALSE) + { + $data = $this->validate($data); + } + + if ($data !== FALSE) + { + $data = $this->trigger('before_create', $data); + + $this->_database->insert($this->_table, $data); + $insert_id = $this->_database->insert_id(); + + $this->trigger('after_create', $insert_id); + + return $insert_id; + } + else + { + return FALSE; + } + } + + /** + * Insert multiple rows into the table. Returns an array of multiple IDs. + */ + public function insert_many($data, $skip_validation = FALSE) + { + $ids = array(); + + foreach ($data as $key => $row) + { + $ids[] = $this->insert($row, $skip_validation, ($key == count($data) - 1)); + } + + return $ids; + } + + /** + * Updated a record based on the primary value. + */ + public function update($primary_value, $data, $skip_validation = FALSE) + { + $data = $this->trigger('before_update', $data); + + if ($skip_validation === FALSE) + { + $data = $this->validate($data); + } + + if ($data !== FALSE) + { + $result = $this->_database->where($this->primary_key, $primary_value) + ->set($data) + ->update($this->_table); + + $this->trigger('after_update', array($data, $result)); + + return $result; + } + else + { + return FALSE; + } + } + + /** + * Update many records, based on an array of primary values. + */ + public function update_many($primary_values, $data, $skip_validation = FALSE) + { + $data = $this->trigger('before_update', $data); + + if ($skip_validation === FALSE) + { + $data = $this->validate($data); + } + + if ($data !== FALSE) + { + $result = $this->_database->where_in($this->primary_key, $primary_values) + ->set($data) + ->update($this->_table); + + $this->trigger('after_update', array($data, $result)); + + return $result; + } + else + { + return FALSE; + } + } + + /** + * Updated a record based on an arbitrary WHERE clause. + */ + public function update_by() + { + $args = func_get_args(); + $data = array_pop($args); + + $data = $this->trigger('before_update', $data); + + if ($this->validate($data) !== FALSE) + { + $this->_set_where($args); + $result = $this->_database->set($data) + ->update($this->_table); + $this->trigger('after_update', array($data, $result)); + + return $result; + } + else + { + return FALSE; + } + } + + /** + * Update all records + */ + public function update_all($data) + { + $data = $this->trigger('before_update', $data); + $result = $this->_database->set($data) + ->update($this->_table); + $this->trigger('after_update', array($data, $result)); + + return $result; + } + + /** + * Delete a row from the table by the primary value + * + * @param boolean $force_hard_delete Force deletion from table even if + * soft_delete is set to true. + */ + public function delete($id, $force_hard_delete = false) + { + $this->trigger('before_delete', $id); + + $this->_database->where($this->primary_key, $id); + + if ($this->soft_delete && !$force_hard_delete) { + $result = $this->_database->update($this->_table, array($this->soft_delete_key => TRUE)); + } else { + $result = $this->_database->delete($this->_table); + } + + $this->trigger('after_delete', $result); + + return $result; + } + + /** + * Delete a row from the database table by an arbitrary WHERE clause + */ + public function delete_by() + { + $where = func_get_args(); + + $where = $this->trigger('before_delete', $where); + + $this->_set_where($where); + + + if ($this->soft_delete) + { + $result = $this->_database->update($this->_table, array( $this->soft_delete_key => TRUE )); + } + else + { + $result = $this->_database->delete($this->_table); + } + + $this->trigger('after_delete', $result); + + return $result; + } + + /** + * Delete many rows from the database table by multiple primary values + * + * @param boolean $force_hard_delete Force deletion from table even if + * soft_delete is set to true. + */ + public function delete_many($primary_values, $force_hard_delete = false) + { + $primary_values = $this->trigger('before_delete', $primary_values); + + $this->_database->where_in($this->primary_key, $primary_values); + + if ($this->soft_delete && !$force_hard_delete) { + $result = $this->_database->update($this->_table, array($this->soft_delete_key => TRUE)); + } else { + $result = $this->_database->delete($this->_table); + } + + $this->trigger('after_delete', $result); + + return $result; + } + + /** + * Rollback a soft deletion for a row in the database, by the primary value + */ + public function undelete($id) + { + if ($this->soft_delete) { + /* The data to update is the soft delete key, to reset to false */ + $data = array($this->soft_delete_key => FALSE); + + return $this->update($id, $data); + } else { + return FALSE; + } + } + + /** + * Truncates the table + */ + public function truncate() + { + $result = $this->_database->truncate($this->_table); + + return $result; + } + + /* -------------------------------------------------------------- + * RELATIONSHIPS + * ------------------------------------------------------------ */ + + public function with($relationship) + { + $this->_with[] = $relationship; + + if (!in_array('relate', $this->after_get)) + { + $this->after_get[] = 'relate'; + } + + return $this; + } + + public function with_all() + { + // Add all relationships in _with array + foreach ($this->belongs_to as $key => $value) { + if (is_string($value)) { + $relationship = $value; + } else { + $relationship = $key; + } + + $this->_with[] = $relationship; + } + + foreach ($this->has_many as $key => $value) { + if (is_string($value)) { + $relationship = $value; + } else { + $relationship = $key; + } + + $this->_with[] = $relationship; + } + + if (!in_array('relate', $this->after_get)) { + $this->after_get[] = 'relate'; + } + + return $this; + } + + public function relate($row) + { + if (empty($row)) + { + return $row; + } + + foreach ($this->belongs_to as $key => $value) + { + if (is_string($value)) + { + $relationship = $value; + $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' ); + } + else + { + $relationship = $key; + $options = $value; + } + + if (in_array($relationship, $this->_with)) + { + $this->load->model($options['model'], $relationship . '_model'); + + if (is_object($row)) + { + $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']}); + } + else + { + $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]); + } + } + } + + foreach ($this->has_many as $key => $value) + { + if (is_string($value)) + { + $relationship = $value; + $options = array( 'primary_key' => singular($this->_table) . '_id', 'model' => singular($value) . '_model' ); + } + else + { + $relationship = $key; + $options = $value; + } + + if (in_array($relationship, $this->_with)) + { + $this->load->model($options['model'], $relationship . '_model'); + + if (is_object($row)) + { + $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key}); + } + else + { + $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]); + } + } + } + + return $row; + } + + /* -------------------------------------------------------------- + * UTILITY METHODS + * ------------------------------------------------------------ */ + + /** + * Retrieve and generate a form_dropdown friendly array + */ + function dropdown() + { + $args = func_get_args(); + + if(count($args) == 2) + { + list($key, $value) = $args; + } + else + { + $key = $this->primary_key; + $value = $args[0]; + } + + $this->trigger('before_dropdown', array( $key, $value )); + + if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE) + { + $this->_database->where($this->soft_delete_key, FALSE); + } + + $result = $this->_database->select(array($key, $value)) + ->get($this->_table) + ->result(); + + $options = array(); + + foreach ($result as $row) + { + $options[$row->{$key}] = $row->{$value}; + } + + $options = $this->trigger('after_dropdown', $options); + + return $options; + } + + /** + * Fetch a count of rows based on an arbitrary WHERE call. + */ + public function count_by() + { + if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE) + { + $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted); + } + + $where = func_get_args(); + $this->_set_where($where); + + return $this->_database->count_all_results($this->_table); + } + + /** + * Fetch a total count of rows, disregarding any previous conditions + */ + public function count_all() + { + if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE) + { + $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted); + } + + return $this->_database->count_all($this->_table); + } + + /** + * Tell the class to skip the insert validation + */ + public function skip_validation() + { + $this->skip_validation = TRUE; + return $this; + } + + /** + * Get the skip validation status + */ + public function get_skip_validation() + { + return $this->skip_validation; + } + + /** + * Return the next auto increment of the table. Only tested on MySQL. + */ + public function get_next_id() + { + return (int) $this->_database->select('AUTO_INCREMENT') + ->from('information_schema.TABLES') + ->where('TABLE_NAME', $this->_table) + ->where('TABLE_SCHEMA', $this->_database->database)->get()->row()->AUTO_INCREMENT; + } + + /** + * Getter for the table name + */ + public function table() + { + return $this->_table; + } + + /* -------------------------------------------------------------- + * GLOBAL SCOPES + * ------------------------------------------------------------ */ + + /** + * Return the next call as an array rather than an object + */ + public function as_array() + { + $this->_temporary_return_type = 'array'; + return $this; + } + + /** + * Return the next call as an object rather than an array + */ + public function as_object() + { + $this->_temporary_return_type = 'object'; + return $this; + } + + /** + * Don't care about soft deleted rows on the next call + */ + public function with_deleted() + { + $this->_temporary_with_deleted = TRUE; + return $this; + } + + /** + * Only get deleted rows on the next call + */ + public function only_deleted() + { + $this->_temporary_only_deleted = TRUE; + return $this; + } + + /* -------------------------------------------------------------- + * OBSERVERS + * ------------------------------------------------------------ */ + + /** + * MySQL DATETIME created_at and updated_at + */ + public function created_at($row) + { + if (is_object($row)) + { + $row->created_at = date('Y-m-d H:i:s'); + } + else + { + $row['created_at'] = date('Y-m-d H:i:s'); + } + + return $row; + } + + public function updated_at($row) + { + if (is_object($row)) + { + $row->updated_at = date('Y-m-d H:i:s'); + } + else + { + $row['updated_at'] = date('Y-m-d H:i:s'); + } + + return $row; + } + + /** + * Serialises data for you automatically, allowing you to pass + * through objects and let it handle the serialisation in the background + */ + public function serialize($row) + { + foreach ($this->callback_parameters as $column) + { + $row[$column] = serialize($row[$column]); + } + + return $row; + } + + public function unserialize($row) + { + foreach ($this->callback_parameters as $column) + { + if (is_array($row)) + { + $row[$column] = unserialize($row[$column]); + } + else + { + $row->$column = unserialize($row->$column); + } + } + + return $row; + } + + /** + * Protect attributes by removing them from $row array + */ + public function protect_attributes($row) + { + foreach ($this->protected_attributes as $attr) + { + if (is_object($row)) + { + unset($row->$attr); + } + else + { + unset($row[$attr]); + } + } + + return $row; + } + + /* -------------------------------------------------------------- + * QUERY BUILDER DIRECT ACCESS METHODS + * ------------------------------------------------------------ */ + + /** + * A wrapper to $this->_database->order_by() + */ + public function order_by($criteria, $order = 'ASC') + { + if ( is_array($criteria) ) + { + foreach ($criteria as $key => $value) + { + $this->_database->order_by($key, $value); + } + } + else + { + $this->_database->order_by($criteria, $order); + } + return $this; + } + + /** + * A wrapper to $this->_database->limit() + */ + public function limit($limit, $offset = 0) + { + $this->_database->limit($limit, $offset); + return $this; + } + + /* -------------------------------------------------------------- + * INTERNAL METHODS + * ------------------------------------------------------------ */ + + /** + * Trigger an event and call its observers. Pass through the event name + * (which looks for an instance variable $this->event_name), an array of + * parameters to pass through and an optional 'last in interation' boolean + */ + public function trigger($event, $data = FALSE, $last = TRUE) + { + if (isset($this->$event) && is_array($this->$event)) + { + foreach ($this->$event as $method) + { + if (strpos($method, '(')) + { + preg_match('/([a-zA-Z0-9\_\-]+)(\(([a-zA-Z0-9\_\-\., ]+)\))?/', $method, $matches); + + $method = $matches[1]; + $this->callback_parameters = explode(',', $matches[3]); + } + + $data = call_user_func_array(array($this, $method), array($data, $last)); + } + } + + return $data; + } + + /** + * Run validation on the passed data + */ + public function validate($data) + { + if($this->skip_validation) + { + return $data; + } + + if(!empty($this->validate)) + { + foreach($data as $key => $val) + { + $_POST[$key] = $val; + } + + $this->load->library('form_validation'); + + if(is_array($this->validate)) + { + $this->form_validation->set_rules($this->validate); + + if ($this->form_validation->run() === TRUE) + { + return $data; + } + else + { + return FALSE; + } + } + else + { + if ($this->form_validation->run($this->validate) === TRUE) + { + return $data; + } + else + { + return FALSE; + } + } + } + else + { + return $data; + } + } + + /** + * Guess the table name by pluralising the model name + */ + private function _fetch_table() + { + if ($this->_table == NULL) + { + $this->_table = plural(preg_replace('/(_m|_model)?$/', '', strtolower(get_class($this)))); + } + } + + /** + * Guess the primary key for current table + */ + private function _fetch_primary_key() + { + if($this->primary_key == NULl) + { + $this->primary_key = $this->_database->query("SHOW KEYS FROM `".$this->_table."` WHERE Key_name = 'PRIMARY'")->row()->Column_name; + } + } + + /** + * Set WHERE parameters, cleverly + */ + protected function _set_where($params) + { + if (count($params) == 1 && is_array($params[0])) + { + foreach ($params[0] as $field => $filter) + { + if (is_array($filter)) + { + $this->_database->where_in($field, $filter); + } + else + { + if (is_int($field)) + { + $this->_database->where($filter); + } + else + { + $this->_database->where($field, $filter); + } + } + } + } + else if (count($params) == 1) + { + $this->_database->where($params[0]); + } + else if(count($params) == 2) + { + if (is_array($params[1])) + { + $this->_database->where_in($params[0], $params[1]); + } + else + { + $this->_database->where($params[0], $params[1]); + } + } + else if(count($params) == 3) + { + $this->_database->where($params[0], $params[1], $params[2]); + } + else + { + if (is_array($params[1])) + { + $this->_database->where_in($params[0], $params[1]); + } + else + { + $this->_database->where($params[0], $params[1]); + } + } + } + + /** + * Return the method name for the current return type + */ + protected function _return_type($multi = FALSE) + { + $method = ($multi) ? 'result' : 'row'; + return $this->_temporary_return_type == 'array' ? $method . '_array' : $method; + } + + + /** + * Get validation rules for use in another class, typically in the controller + * to valid a form. + * + * @access public + * @param $rules_set : The set of rules to get, based on the controller + * method calling (see $this->validate array) + * @return validation rules array + */ + public function get_validation_rules($rules_set) + { + return $this->validate[$rules_set]; + } +} diff --git a/application/core/MY_Router.php b/application/core/MY_Router.php new file mode 100644 index 00000000..15cbac14 --- /dev/null +++ b/application/core/MY_Router.php @@ -0,0 +1,8 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/helpers/MY_date_helper.php b/application/helpers/MY_date_helper.php new file mode 100644 index 00000000..9febaaca --- /dev/null +++ b/application/helpers/MY_date_helper.php @@ -0,0 +1,74 @@ + + */ + + +/** +* Check if a given date (for example a date written in a form) is a valid date +* +* @return true if the date is valid, false else +*/ +function validateDate($date, $format) +{ + // Check that $date is a valid date + $d = DateTime::createFromFormat($format, $date); + return $d && $d->format($format) == $date; +} + +/** +* Format a given date or the current date to the php timestamp format +* +* @return The formated date +*/ +function phpDate($date) +{ + if (empty($date) || strtolower($date) == 'now') + { + return now(); + } + else + { + return strtotime($date); + } +} + +/** +* Format a given date or the current date to MySQL DATE type +* +* @return The formated date +*/ +function mysqlDate($date) +{ + if (empty($date) || strtolower($date) == 'now') + { + return date('Y-m-d'); + } + else + { + return nice_date($date, 'Y-m-d'); + } +} + +/** +* Format a given date or the current date to MySQL DATETIME type +* +* @return The formated date +*/ +function mysqlDateTime($date) +{ + if (empty($date) || strtolower($date) == 'now') + { + return date('Y-m-d H:i:s'); + } + else + { + return nice_date($date, 'Y-m-d H:i:s'); + } +} + +/* End of file My_date_helper.php */ \ No newline at end of file diff --git a/application/helpers/index.html b/application/helpers/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/helpers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/hooks/index.html b/application/hooks/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/hooks/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/index.html b/application/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/language/english/index.html b/application/language/english/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/language/english/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/language/french/MY_application_lang.php b/application/language/french/MY_application_lang.php new file mode 100644 index 00000000..6168579b --- /dev/null +++ b/application/language/french/MY_application_lang.php @@ -0,0 +1,36 @@ + + */ + +// Application name +$lang['app_title'] = 'Section informatique
Package de base'; + +// Page titles +$lang['page_prefix'] = 'Pack base'; + +// Date and time formats +$lang['date_format_short'] = 'd.m.Y'; +$lang['datetime_format_short'] = 'd.m.Y H:i'; + +// Buttons +$lang['btn_cancel'] = 'Annuler'; +$lang['btn_add_m'] = 'Nouveau'; +$lang['btn_add_f'] = 'Nouvelle'; +$lang['btn_save'] = 'Enregistrer'; +$lang['btn_disable'] = 'Désactiver'; +$lang['btn_reactivate'] = 'Réactiver'; +$lang['btn_delete'] = 'Supprimer'; +$lang['btn_hard_delete'] = 'Supprimer définitivement'; + +// Messages +$lang['msg_err_access_denied_header'] = 'Accès interdit'; +$lang['msg_err_access_denied_message'] = 'Vous n\'êtes pas autorisé à accéder à cette fonction'; + +// Other texts +$lang['yes'] = 'Oui'; +$lang['no'] = 'Non'; diff --git a/application/language/french/calendar_lang.php b/application/language/french/calendar_lang.php new file mode 100644 index 00000000..f8efd533 --- /dev/null +++ b/application/language/french/calendar_lang.php @@ -0,0 +1,55 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/language/french/migration_lang.php b/application/language/french/migration_lang.php new file mode 100644 index 00000000..77672ca2 --- /dev/null +++ b/application/language/french/migration_lang.php @@ -0,0 +1,18 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/libraries/MY_Form_validation.php b/application/libraries/MY_Form_validation.php new file mode 100644 index 00000000..27241402 --- /dev/null +++ b/application/libraries/MY_Form_validation.php @@ -0,0 +1,8 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/logs/index.html b/application/logs/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/logs/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/models/index.html b/application/models/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/models/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/common/index.html b/application/modules/common/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/common/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/common/views/footer.php b/application/modules/common/views/footer.php new file mode 100644 index 00000000..308b1d01 --- /dev/null +++ b/application/modules/common/views/footer.php @@ -0,0 +1,2 @@ + + diff --git a/application/modules/common/views/header.php b/application/modules/common/views/header.php new file mode 100644 index 00000000..c920fdea --- /dev/null +++ b/application/modules/common/views/header.php @@ -0,0 +1,46 @@ + + + + + + + + + + <?php + if (is_null($title) || $title == '') { + echo lang('page_prefix'); + } else { + echo lang('page_prefix').' - '.$title; + } + ?> + + + " type="image/x-icon" /> + + + + " /> + + + + + + + + + + + " /> + + + CodeIgniter environment variable is set to '.strtoupper(ENVIRONMENT).'. You can change it in .htaccess file.'; + } + ?> \ No newline at end of file diff --git a/application/modules/common/views/index.html b/application/modules/common/views/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/common/views/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/common/views/login_bar.php b/application/modules/common/views/login_bar.php new file mode 100644 index 00000000..6ff398b7 --- /dev/null +++ b/application/modules/common/views/login_bar.php @@ -0,0 +1,43 @@ +config->load('user/MY_user_config'); + $CI->lang->load('user/MY_user'); +} else { + // CI-PHPUnit checks from application/folder instead of module/folder + $CI->config->load('../modules/user/config/MY_user_config'); + $CI->lang->load('../../modules/user/language/french/MY_user'); +} +?> +
+
+
+ " > +
+
+

+
+
+ +
+
+
+
diff --git a/application/modules/index.html b/application/modules/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/config/MY_user_config.php b/application/modules/user/config/MY_user_config.php new file mode 100644 index 00000000..97d4a2d8 --- /dev/null +++ b/application/modules/user/config/MY_user_config.php @@ -0,0 +1,26 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/controllers/Admin.php b/application/modules/user/controllers/Admin.php new file mode 100644 index 00000000..52ad8f4f --- /dev/null +++ b/application/modules/user/controllers/Admin.php @@ -0,0 +1,260 @@ +access_level = $this->config->item('access_lvl_admin'); + + parent::__construct(); + + // Load required items + $this->load->library('form_validation')->model(['user_model', 'user_type_model']); + + // Assign form_validation CI instance to this + $this->form_validation->CI =& $this; + } + + /** + * Displays the list of users + * + * @param boolean $with_deleted = Display archived users or not + * @return void + */ + public function list_user($with_deleted = FALSE) + { + if ($with_deleted) { + $users = $this->user_model->with_deleted()->get_all(); + } else { + $users = $this->user_model->get_all(); + } + + $output = array( + 'users' => $users, + 'user_types' => $this->user_type_model->dropdown('name'), + 'with_deleted' => $with_deleted + ); + $this->display_view('user/admin/list_user', $output); + } + + /** + * Adds or modify a user + * + * @param integer $user_id = The id of the user to modify, leave blank to create a new one + * @return void + */ + public function save_user($user_id = 0) + { + $oldName = NULL; + $oldUsertype = NULL; + if (count($_POST) > 0) { + $user_id = $this->input->post('id'); + $oldName = $this->input->post('user_name'); + if($_SESSION['user_id'] != $user_id) { + $oldUsertype = $this->input->post('user_usertype'); + } + + $this->form_validation->set_rules( + 'id', 'id', + 'callback_cb_not_null_user', + ['cb_not_null_user' => $this->lang->line('msg_err_user_not_exist')] + ); + $this->form_validation->set_rules('user_name', 'lang:user_name', + [ + 'required', 'trim', + 'min_length['.$this->config->item('username_min_length').']', + 'max_length['.$this->config->item('username_max_length').']', + "callback_cb_unique_user[{$user_id}]" + ], + ['cb_unique_user' => $this->lang->line('msg_err_user_not_unique')] + ); + $this->form_validation->set_rules('user_usertype', 'lang:user_usertype', + ['required', 'callback_cb_not_null_user_type'], + ['cb_not_null_user_type' => $this->lang->line('msg_err_user_type_not_exist')] + ); + + if ($user_id == 0) { + $this->form_validation->set_rules('user_password', lang('field_password'), [ + 'required', 'trim', + 'min_length['.$this->config->item('password_min_length').']', + 'max_length['.$this->config->item('password_max_length').']' + ]); + $this->form_validation->set_rules('user_password_again', $this->lang->line('field_password_confirm'), [ + 'required', 'trim', 'matches[user_password]', + 'min_length['.$this->config->item('password_min_length').']', + 'max_length['.$this->config->item('password_max_length').']' + ]); + } + + if ($this->form_validation->run()) { + $user = array( + 'fk_user_type' => $this->input->post('user_usertype'), + 'username' => $this->input->post('user_name') + ); + if ($user_id > 0) { + $this->user_model->update($user_id, $user); + } else { + $password = $this->input->post('user_password'); + $user['password'] = password_hash($password, $this->config->item('password_hash_algorithm')); + $this->user_model->insert($user); + } + redirect('user/admin/list_user'); + } + } + + $output = array( + 'title' => $this->lang->line('title_user_'.((bool)$user_id ? 'update' : 'new')), + 'user' => $this->user_model->with_deleted()->get($user_id), + 'user_types' => $this->user_type_model->dropdown('name'), + 'user_name' => $oldName, + 'user_usertype' => $oldUsertype + ); + + $this->display_view('user/admin/save_user', $output); + } + + /** + * Deletes or deactivate a user depending on $action + * + * @param integer $user_id = ID of the user to affect + * @param integer $action = Action to apply on the user: + * - 0 for displaying the confirmation + * - 1 for deactivating (soft delete) + * - 2 for deleting (hard delete) + * @return void + */ + public function delete_user($user_id, $action = 0) + { + $user = $this->user_model->with_deleted()->get($user_id); + if (is_null($user)) { + redirect('user/admin/list_user'); + } + + switch($action) { + case 0: // Display confirmation + $output = array( + 'user' => $user, + 'title' => lang('title_user_delete') + ); + $this->display_view('user/admin/delete_user', $output); + break; + case 1: // Deactivate (soft delete) user + if ($_SESSION['user_id'] != $user->id) { + $this->user_model->delete($user_id, FALSE); + } + redirect('user/admin/list_user'); + case 2: // Delete user + if ($_SESSION['user_id'] != $user->id) { + $this->user_model->delete($user_id, TRUE); + } + redirect('user/admin/list_user'); + default: // Do nothing + redirect('user/admin/list_user'); + } + } + + /** + * Reactivate a disabled user. + * + * @param integer $user_id = ID of the user to affect + * @return void + */ + public function reactivate_user($user_id) + { + $user = $this->user_model->with_deleted()->get($user_id); + if (is_null($user)) { + redirect('user/admin/list_user'); + } else { + $this->user_model->undelete($user_id); + redirect('user/admin/save_user/'.$user_id); + } + } + + /** + * Displays a form to change a user's password + * + * @param integer $user_id = ID of the user to update + * @return void + */ + public function password_change_user($user_id) + { + if (count($_POST) > 0) { + $this->form_validation->set_rules( + 'id', 'id', + 'callback_cb_not_null_user', + $this->lang->line('msg_err_user_not_exist') + ); + $this->form_validation->set_rules('user_password_new', lang('field_new_password'), [ + 'required', 'trim', + 'min_length['.$this->config->item('password_min_length').']', + 'max_length['.$this->config->item('password_max_length').']' + ]); + $this->form_validation->set_rules('user_password_again', $this->lang->line('field_password_confirm'), [ + 'required', 'trim', 'matches[user_password_new]', + 'min_length['.$this->config->item('password_min_length').']', + 'max_length['.$this->config->item('password_max_length').']' + ]); + + if ($this->form_validation->run()) { + $password = $this->input->post('user_password_new'); + $password = password_hash($password, $this->config->item('password_hash_algorithm')); + $this->user_model->update($user_id, ['password' => $password]); + redirect('user/admin/list_user'); + } + } + + $user = $this->user_model->with_deleted()->get($user_id); + if (is_null($user)) redirect('user/admin/list_user'); + + $output = array( + 'user' => $user, + 'title' => $this->lang->line('title_user_password_reset') + ); + + $this->display_view('user/admin/password_change_user', $output); + } + + /** + * Checks that a username doesn't exist + * + * @param string $username = Username to check + * @param int $user_id = ID of the user if it is an update + * @return boolean = TRUE if the username is unique, FALSE otherwise + */ + public function cb_unique_user($username, $user_id) : bool + { + $user = $this->user_model->with_deleted()->get_by('username', $username); + return is_null($user) || $user->id == $user_id; + } + /** + * Checks that an user exists + * + * @param integer $user_id = Id of the user to check + * @return boolean = TRUE if the id is 0 or if the user exists, FALSE otherwise + */ + public function cb_not_null_user($user_id) : bool + { + return $user_id == 0 || !is_null($this->user_model->with_deleted()->get($user_id)); + } + /** + * Checks that an user type exists + * + * @param integer $user_type_id = Id of the user type to check + * @return boolean = TRUE if the user type exists, FALSE otherwise + */ + public function cb_not_null_user_type($user_type_id) : bool + { + return !is_null($this->user_type_model->get($user_type_id)); + } +} diff --git a/application/modules/user/controllers/Auth.php b/application/modules/user/controllers/Auth.php new file mode 100644 index 00000000..79c4a850 --- /dev/null +++ b/application/modules/user/controllers/Auth.php @@ -0,0 +1,199 @@ +access_level = '*'; + + parent::__construct(); + + // Load required items + $this->load->library('form_validation')->model('user_model'); + + // Assign form_validation CI instance to this + $this->form_validation->CI =& $this; + } + + /** + * Login user and create session variables + * + * @return void + */ + public function login() + { + // If user already logged + if(!(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true)) { + // Store the redirection URL in a session variable + if (!is_null($this->input->post('after_login_redirect'))) { + $_SESSION['after_login_redirect'] = $this->input->post('after_login_redirect'); + } + // If no redirection URL is provided or the redirection URL is the + // login form, redirect to site's root after login + if (!isset($_SESSION['after_login_redirect']) + || $_SESSION['after_login_redirect'] == current_url()) { + + $_SESSION['after_login_redirect'] = base_url(); + } + + // Check if the form has been submitted, else just display the form + if (!is_null($this->input->post('btn_login'))) { + // Define fields validation rules + $validation_rules = array( + array( + 'field' => 'username', + 'label' => 'lang:field_username', + 'rules' => 'trim|required|' + . 'min_length['.$this->config->item('username_min_length').']|' + . 'max_length['.$this->config->item('username_max_length').']' + ), + array( + 'field' => 'password', + 'label' => 'lang:field_password', + 'rules' => 'trim|required|' + . 'min_length['.$this->config->item('password_min_length').']|' + . 'max_length['.$this->config->item('password_max_length').']' + ) + ); + $this->form_validation->set_rules($validation_rules); + + // Check fields validation rules + if ($this->form_validation->run() == true) { + $username = $this->input->post('username'); + $password = $this->input->post('password'); + + if ($this->user_model->check_password($username, $password)) { + // Login success + $user = $this->user_model->with('user_type') + ->get_by('username', $username); + + // Set session variables + $_SESSION['user_id'] = (int)$user->id; + $_SESSION['username'] = (string)$user->username; + $_SESSION['user_access'] = (int)$user->user_type->access_level; + $_SESSION['logged_in'] = (bool)true; + + // Send the user to the redirection URL + redirect($_SESSION['after_login_redirect']); + + } else { + // Login failed + $this->session->set_flashdata('message-danger', lang('msg_err_invalid_password')); + } + } + } + + // Display login page + $output = array('title' => lang('title_page_login')); + $this->display_view('user/auth/login', $output); + } else { + redirect(base_url()); + } + } + + /** + * Logout and destroy session + * + * @return void + */ + public function logout() + { + // Restart session with empty parameters + $_SESSION = []; + session_reset(); + session_unset(); + + redirect(base_url()); + } + + /** + * Displays a form to let user change his password + * + * @return void + */ + public function change_password() + { + // Check if access is allowed + if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) { + + // Check if the form has been submitted, else just display the form + if (!is_null($this->input->post('btn_change_password'))) { + $username = $_SESSION["username"]; + + // Define fields validation rules + $validation_rules = array( + array( + 'field' => 'old_password', + 'label' => 'lang:field_old_password', + 'rules' => 'trim|required|' + . 'min_length['.$this->config->item('password_min_length').']|' + . 'max_length['.$this->config->item('password_max_length').']|' + . 'callback_cb_old_password_check['.$username.']', + 'errors' => array( + 'cb_old_password_check' => lang('msg_err_invalid_old_password') + ) + ), + array( + 'field' => 'new_password', + 'label' => 'lang:field_new_password', + 'rules' => 'trim|required|' + . 'min_length['.$this->config->item('password_min_length').']|' + . 'max_length['.$this->config->item('password_max_length').']' + ), + array( + 'field' => 'confirm_password', + 'label' => 'lang:field_password_confirm', + 'rules' => 'trim|required|' + . 'min_length['.$this->config->item('password_min_length').']|' + . 'max_length['.$this->config->item('password_max_length').']|' + . 'matches[new_password]' + ) + ); + $this->form_validation->set_rules($validation_rules); + + // Check fields validation rules + if ($this->form_validation->run() == true) { + $old_password = $this->input->post('old_password'); + $new_password = $this->input->post('new_password'); + $confirm_password = $this->input->post('confirm_password'); + + $this->load->model('user_model'); + $this->user_model->update($_SESSION['user_id'], + array("password" => password_hash($new_password, $this->config->item('password_hash_algorithm')))); + + // Send the user back to the site's root + redirect(base_url()); + } + } + + // Display the password change form + $output['title'] = $this->lang->line('page_password_change'); + $this->display_view('user/auth/change_password', $output); + } else { + // Access is not allowed + $this->login(); + } + } + + /** + * Callback method for change_password validation rule + * + * @param string $pwd = The previous password + * @param string $user = The username + * @return boolean = Whether or not the combination is correct + */ + public function cb_old_password_check($pwd, $user) + { + return $this->user_model->check_password($user, $pwd); + } +} diff --git a/application/modules/user/controllers/index.html b/application/modules/user/controllers/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/controllers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/database/index.html b/application/modules/user/database/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/database/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/database/user.sql b/application/modules/user/database/user.sql new file mode 100644 index 00000000..9e6f019b --- /dev/null +++ b/application/modules/user/database/user.sql @@ -0,0 +1,99 @@ +-- phpMyAdmin SQL Dump +-- version 4.9.0.1 +-- https://www.phpmyadmin.net/ +-- +-- Version du serveur : 10.4.6-MariaDB +-- Version de PHP : 7.3.9 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET AUTOCOMMIT = 0; +START TRANSACTION; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Structure de la table `user` +-- + +CREATE TABLE `user` ( + `id` int(11) NOT NULL, + `fk_user_type` int(11) NOT NULL, + `username` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `archive` tinyint(4) NOT NULL DEFAULT 0, + `date_creation` timestamp NOT NULL DEFAULT current_timestamp() +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- -------------------------------------------------------- + +-- +-- Structure de la table `user_type` +-- + +CREATE TABLE `user_type` ( + `id` int(11) NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `access_level` int(11) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- +-- Déchargement des données de la table `user_type` +-- + +INSERT INTO `user_type` (`id`, `name`, `access_level`) VALUES +(1, 'Administrateur', 4), +(2, 'Enregistré', 2), +(3, 'Invité', 1); + +-- +-- Index pour les tables déchargées +-- + +-- +-- Index pour la table `user` +-- +ALTER TABLE `user` + ADD PRIMARY KEY (`id`), + ADD KEY `fk_user_user_type1_idx` (`fk_user_type`); + +-- +-- Index pour la table `user_type` +-- +ALTER TABLE `user_type` + ADD PRIMARY KEY (`id`); + +-- +-- AUTO_INCREMENT pour les tables déchargées +-- + +-- +-- AUTO_INCREMENT pour la table `user` +-- +ALTER TABLE `user` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; + +-- +-- AUTO_INCREMENT pour la table `user_type` +-- +ALTER TABLE `user_type` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; + +-- +-- Contraintes pour les tables déchargées +-- + +-- +-- Contraintes pour la table `user` +-- +ALTER TABLE `user` + ADD CONSTRAINT `fk_user_user_type1` FOREIGN KEY (`fk_user_type`) REFERENCES `user_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; +COMMIT; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/application/modules/user/index.html b/application/modules/user/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/language/french/MY_user_lang.php b/application/modules/user/language/french/MY_user_lang.php new file mode 100644 index 00000000..245aaf4f --- /dev/null +++ b/application/modules/user/language/french/MY_user_lang.php @@ -0,0 +1,58 @@ +
' + .'En cas de suppression définitive, toutes les informations concernant cet utilisateur seront supprimées.'; +$lang['user_allready_disabled'] = 'Cet utilisateur est déjà désactivé. Voulez-vous le supprimer définitivement ?'; +$lang['user_update_usertype_himself'] = 'Vous ne pouvez pas modifier votre propre type d\'utilisateur. Cette opération doit être faite par un autre administrateur.'; +$lang['user_delete_himself'] = 'Vous ne pouvez pas désactiver ou supprimer votre propre compte. Cette opération doit être faite par un autre administrateur.'; +$lang['page_my_password_change'] = 'Modification de mon mot de passe'; diff --git a/application/modules/user/language/french/index.html b/application/modules/user/language/french/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/language/french/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/language/index.html b/application/modules/user/language/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/language/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/models/User_model.php b/application/modules/user/models/User_model.php new file mode 100644 index 00000000..d8f6a134 --- /dev/null +++ b/application/modules/user/models/User_model.php @@ -0,0 +1,50 @@ + ['primary_key' => 'fk_user_type', + 'model' => 'user_type_model']]; + protected $soft_delete = TRUE; + protected $soft_delete_key = 'archive'; + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + } + + /** + * Check username and password for login + * + * @param $username + * @param $password + * @return bool true on success, false on failure + */ + public function check_password($username, $password) + { + $user = $this->get_by('username', $username); + + if (!is_null($user) && $user->archive == false) { + // A corresponding active user has been found + // Check password + return password_verify($password, $user->password); + } + else { + // No corresponding active user + return false; + } + } +} \ No newline at end of file diff --git a/application/modules/user/models/User_type_model.php b/application/modules/user/models/User_type_model.php new file mode 100644 index 00000000..c81a284a --- /dev/null +++ b/application/modules/user/models/User_type_model.php @@ -0,0 +1,26 @@ + ['primary_key' => 'fk_user_type', + 'model' => 'user_model']]; + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + } +} \ No newline at end of file diff --git a/application/modules/user/models/index.html b/application/modules/user/models/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/models/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/user/readme.md b/application/modules/user/readme.md new file mode 100644 index 00000000..9696b4f7 --- /dev/null +++ b/application/modules/user/readme.md @@ -0,0 +1,42 @@ +# user module # + +This module contains all elements needed for user administration and authentication. + +## Configuration ## + +This section describes the module's configurations available in the config directory. + +### Access levels ### + +Defines the access levels in powers of 2. +By default, guest, registered, and admin access levels are defined. + +### Validation rules ### + +Defines the min/max length of usernames and passwords. + +### password_hash_algorithm ### + +Defines the algorithm to use for password hashing. Does not automatically update the database. + +## Database and models ## + +An SQL script defines the tables needed for this module. This script can be found in the module's "database" subfolder and can be executed in your database to generate the tables. + +### user ### + +Contains the user's basic informations such as id, user_type, username, password (hashed), archive status and creation date. +The archive status (boolean) is used as a soft delete key. An archived user cannot login anymore but his informations are kept in the database. The admin interface authorises soft or hard deletions. + +### user_type ### + +Defines a users access level, based on users types (roles). + +## Dependencies ## + +This module needs the CodeIgniter sessions system properly configured and working. +It assumes that HMVC, base model, base controller and bootstrap libraries are included in the CodeIgniter project. + +## Authors ## + +- **Orif, domaine informatique** - *Creating and following this module* - [GitHub account](https://github.com/OrifInformatique) diff --git a/application/modules/user/views/admin/delete_user.php b/application/modules/user/views/admin/delete_user.php new file mode 100644 index 00000000..4676686a --- /dev/null +++ b/application/modules/user/views/admin/delete_user.php @@ -0,0 +1,38 @@ + +
+
+
+
+ id){ ?> +
+

username.'"' ?>

+

+
+ archive) { ?> +
+ +
+
+ + + + archive) { ?> + + + + + + + +
+ +
+

username.'"' ?>

+
+
+ +
+
+
+
diff --git a/application/modules/user/views/admin/list_user.php b/application/modules/user/views/admin/list_user.php new file mode 100644 index 00000000..2b1d0de0 --- /dev/null +++ b/application/modules/user/views/admin/list_user.php @@ -0,0 +1,65 @@ + +
+
+
+

+
+
+
+
+ + + +
+
+ + 'toggle_deleted' + ]); ?> +
+
+
+ + + + + + + + + + + + + + + + + + + +
username; ?>fk_user_type]; ?>lang->line($user->archive ? 'no' : 'yes'); ?>×
+
+
+ + diff --git a/application/modules/user/views/admin/password_change_user.php b/application/modules/user/views/admin/password_change_user.php new file mode 100644 index 00000000..52a9e35f --- /dev/null +++ b/application/modules/user/views/admin/password_change_user.php @@ -0,0 +1,59 @@ + +
+ 'user_change_password_form', + 'name' => 'user_change_password_form' + ); + echo form_open('user/admin/password_change_user/'.$user->id, $attributes); + ?> + + +
+
+

+

username ?>

+
+
+ + +
+
+ ', '
'); ?> +
+
+ + +
+
+
+ 'form-label']); ?> + 'form-control', 'id' => 'user_password_new', + 'maxlength' => $this->config->item('password_max_length') + ]); ?> +
+
+
+
+ 'form-label']); ?> + 'form-control', 'id' => 'user_password_new', + 'maxlength' => $this->config->item('password_max_length') + ]); ?> +
+
+
+ + +
+
+ +   + 'btn btn-primary']); ?> +
+
+ + diff --git a/application/modules/user/views/admin/save_user.php b/application/modules/user/views/admin/save_user.php new file mode 100644 index 00000000..f1b3d21c --- /dev/null +++ b/application/modules/user/views/admin/save_user.php @@ -0,0 +1,117 @@ + +
+ +
+
+

+
+
+ + + archive) { ?> +
+ +
+ + + + 'user_form', + 'name' => 'user_form' + ); + echo form_open('user/admin/save_user', $attributes, [ + 'id' => $user->id ?? 0 + ]); + ?> + + + ', '
'); ?> + + +
+
+ 'form-label']); ?> + username ?? '', [ + 'maxlength' => $this->config->item('username_max_length'), + 'class' => 'form-control', 'id' => 'user_name' + ]); ?> +
+
+ 'form-label']); ?> + 'form-control', 'id' => 'user_usertype']; + if(isset($user) && $_SESSION['user_id'] == $user->id){ + $dropdown_options['disabled'] = 'disabled'; + echo form_hidden('user_usertype', $user_usertype ?? $user->fk_user_type ?? NULL); + } + ?> + fk_user_type ?? NULL, $dropdown_options); ?> +
+
+ id){ ?> +
+
+
+
+
+ + + +
+
+ 'form-label']); ?> + 'form-control', 'id' => 'user_password' + ]); ?> +
+
+ 'form-label']); ?> + $this->config->item('password_max_length'), + 'class' => 'form-control', 'id' => 'user_password_again' + ]); ?> +
+
+ +
+ +
+ + + +
+ + + archive) { ?> +
+ + + +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+
+ + 'btn btn-primary']); ?> +
+
+ + diff --git a/application/modules/user/views/auth/change_password.php b/application/modules/user/views/auth/change_password.php new file mode 100644 index 00000000..8ce055a4 --- /dev/null +++ b/application/modules/user/views/auth/change_password.php @@ -0,0 +1,56 @@ +
+
+
+ "form-horizontal", + "id" => "change_password", + "name" => "change_password"); + echo form_open("user/auth/change_password", $attributes); + ?> +
+ + +
+
+
+ +
+
+ + +
+
+
+
+
+
+ +
+
+ + +
+
+
+
+
+
+ +
+
+ + +
+
+
+
+
+ + +
+
+
+ +
+
+
diff --git a/application/modules/user/views/auth/login.php b/application/modules/user/views/auth/login.php new file mode 100644 index 00000000..d0c5e377 --- /dev/null +++ b/application/modules/user/views/auth/login.php @@ -0,0 +1,52 @@ +
+
+
+ "form-horizontal", + "id" => "loginform", + "name" => "loginform"); + echo form_open("user/auth/login", $attributes); + ?> +
+ + + + session->flashdata('message-danger'))){ ?> +
session->flashdata('message-danger'); ?>
+ + +
+
+
+ +
+
+ + +
+
+
+ +
+
+
+ +
+
+ + +
+
+
+ +
+
+ + +
+
+
+ +
+
+
diff --git a/application/modules/user/views/index.html b/application/modules/user/views/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/user/views/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/welcome/controllers/Welcome.php b/application/modules/welcome/controllers/Welcome.php new file mode 100644 index 00000000..143f8120 --- /dev/null +++ b/application/modules/welcome/controllers/Welcome.php @@ -0,0 +1,25 @@ + + * @see https://codeigniter.com/user_guide/general/urls.html + */ + public function index() + { + $this->display_view('welcome_message'); + } +} diff --git a/application/modules/welcome/controllers/index.html b/application/modules/welcome/controllers/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/welcome/controllers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/welcome/index.html b/application/modules/welcome/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/welcome/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/welcome/views/index.html b/application/modules/welcome/views/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/modules/welcome/views/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/modules/welcome/views/welcome_message.php b/application/modules/welcome/views/welcome_message.php new file mode 100644 index 00000000..7794f072 --- /dev/null +++ b/application/modules/welcome/views/welcome_message.php @@ -0,0 +1,15 @@ +
+

Welcome to CodeIgniter with HMVC !

+ +

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

+ +

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

+ application/modules/welcome/views/welcome_message.php + +

The corresponding controller for this page is found at:

+ application/modules/welcome/controllers/Welcome.php + +

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

+ +

Page rendered in {elapsed_time} seconds. ' . CI_VERSION . '' : '' ?>

+
diff --git a/application/tests/.gitignore b/application/tests/.gitignore new file mode 100644 index 00000000..e2e07533 --- /dev/null +++ b/application/tests/.gitignore @@ -0,0 +1 @@ +_ci_phpunit_test/tmp/ diff --git a/application/tests/Bootstrap.php b/application/tests/Bootstrap.php new file mode 100644 index 00000000..f5768bde --- /dev/null +++ b/application/tests/Bootstrap.php @@ -0,0 +1,383 @@ +=')) + { + error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); + } + else + { + error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE); + } + break; + + default: + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'The application environment is not set correctly.'; + exit(1); // EXIT_ERROR +} + +/* + *--------------------------------------------------------------- + * SYSTEM DIRECTORY NAME + *--------------------------------------------------------------- + * + * This variable must contain the name of your "system" directory. + * Set the path if it is not in the same directory as this file. + */ + $system_path = '../../system'; + +/* + *--------------------------------------------------------------- + * APPLICATION DIRECTORY NAME + *--------------------------------------------------------------- + * + * If you want this front controller to use a different "application" + * directory than the default one you can set its name here. The directory + * can also be renamed or relocated anywhere on your server. If you do, + * use an absolute (full) server path. + * For more info please see the user guide: + * + * https://codeigniter.com/user_guide/general/managing_apps.html + * + * NO TRAILING SLASH! + */ + $application_folder = '../../application'; + +/* + *--------------------------------------------------------------- + * VIEW DIRECTORY NAME + *--------------------------------------------------------------- + * + * If you want to move the view directory out of the application + * directory, set the path to it here. The directory can be renamed + * and relocated anywhere on your server. If blank, it will default + * to the standard location inside your application directory. + * If you do move this, use an absolute (full) server path. + * + * NO TRAILING SLASH! + */ + $view_folder = ''; + + +/* + * -------------------------------------------------------------------- + * DEFAULT CONTROLLER + * -------------------------------------------------------------------- + * + * Normally you will set your default controller in the routes.php file. + * You can, however, force a custom routing by hard-coding a + * specific controller class/function here. For most applications, you + * WILL NOT set your routing here, but it's an option for those + * special instances where you might want to override the standard + * routing in a specific front controller that shares a common CI installation. + * + * IMPORTANT: If you set the routing here, NO OTHER controller will be + * callable. In essence, this preference limits your application to ONE + * specific controller. Leave the function name blank if you need + * to call functions dynamically via the URI. + * + * Un-comment the $routing array below to use this feature + */ + // The directory name, relative to the "controllers" directory. Leave blank + // if your controller is not in a sub-directory within the "controllers" one + // $routing['directory'] = ''; + + // The controller class file name. Example: mycontroller + // $routing['controller'] = ''; + + // The controller function you wish to be called. + // $routing['function'] = ''; + + +/* + * ------------------------------------------------------------------- + * CUSTOM CONFIG VALUES + * ------------------------------------------------------------------- + * + * The $assign_to_config array below will be passed dynamically to the + * config class when initialized. This allows you to set custom config + * items or override any default config values found in the config.php file. + * This can be handy as it permits you to share one application between + * multiple front controller files, with each file containing different + * config values. + * + * Un-comment the $assign_to_config array below to use this feature + */ + // $assign_to_config['name_of_config_item'] = 'value of config item'; + + + +// -------------------------------------------------------------------- +// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE +// -------------------------------------------------------------------- + +/* + * --------------------------------------------------------------- + * Resolve the system path for increased reliability + * --------------------------------------------------------------- + */ + + // Set the current directory correctly for CLI requests +// if (defined('STDIN')) +// { + // This is needed for @runInSeparateProcess + chdir(dirname(__FILE__)); +// } + + if (($_temp = realpath($system_path)) !== FALSE) + { + $system_path = $_temp.DIRECTORY_SEPARATOR; + } + else + { + // Ensure there's a trailing slash + $system_path = strtr( + rtrim($system_path, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ).DIRECTORY_SEPARATOR; + } + + // Is the system path correct? + if ( ! is_dir($system_path)) + { + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME); + exit(3); // EXIT_CONFIG + } + +/* + * ------------------------------------------------------------------- + * Now that we know the path, set the main path constants + * ------------------------------------------------------------------- + */ + // The name of THIS file + define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); + + // Path to the test directory containing all the test files. + define('TESTPATH', __dir__.DIRECTORY_SEPARATOR); // Should be the folder this `Bootstrap.php` file is in. + + // Path to the system directory + define('BASEPATH', $system_path); + + // Path to the front controller (this file) directory + define('FCPATH', realpath(dirname(__FILE__).'/../..').DIRECTORY_SEPARATOR); + + // Name of the "system" directory + define('SYSDIR', basename(BASEPATH)); + + // The path to the "application" directory + if (is_dir($application_folder)) + { + if (($_temp = realpath($application_folder)) !== FALSE) + { + $application_folder = $_temp; + } + else + { + $application_folder = strtr( + rtrim($application_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + } + elseif (is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR)) + { + $application_folder = BASEPATH.strtr( + trim($application_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + else + { + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; + exit(3); // EXIT_CONFIG + } + + define('APPPATH', $application_folder.DIRECTORY_SEPARATOR); + + // The path to the "views" directory + if ( ! isset($view_folder[0]) && is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR)) + { + $view_folder = APPPATH.'views'; + } + elseif (is_dir($view_folder)) + { + if (($_temp = realpath($view_folder)) !== FALSE) + { + $view_folder = $_temp; + } + else + { + $view_folder = strtr( + rtrim($view_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + } + elseif (is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR)) + { + $view_folder = APPPATH.strtr( + trim($view_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + else + { + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; + exit(3); // EXIT_CONFIG + } + + define('VIEWPATH', $view_folder.DIRECTORY_SEPARATOR); + +/* + * ------------------------------------------------------------------- + * Enabling Monkey Patching + * ------------------------------------------------------------------- + * + * If you want to use monkey patching, uncomment below code and configure + * for your application. + */ +/* +require __DIR__ . '/_ci_phpunit_test/patcher/bootstrap.php'; +MonkeyPatchManager::init([ + // If you want debug log, set `debug` true, and optionally you can set the log file path + 'debug' => true, + 'log_file' => '/tmp/monkey-patch-debug.log', + // PHP Parser: PREFER_PHP7, PREFER_PHP5, ONLY_PHP7, ONLY_PHP5 + 'php_parser' => 'PREFER_PHP5', + 'cache_dir' => TESTPATH . '_ci_phpunit_test/tmp/cache', + // Directories to patch source files + 'include_paths' => [ + APPPATH, + BASEPATH, + TESTPATH . '_ci_phpunit_test/replacing/', + ], + // Excluding directories to patch + // If you want to patch files inside paths below, you must add the directory starting with '-' + 'exclude_paths' => [ + TESTPATH, + '-' . TESTPATH . '_ci_phpunit_test/replacing/', + ], + // All patchers you use. + 'patcher_list' => [ + 'ExitPatcher', + 'FunctionPatcher', + 'MethodPatcher', + 'ConstantPatcher', + ], + // Additional functions to patch + 'functions_to_patch' => [ + //'random_string', + ], + 'exit_exception_classname' => 'CIPHPUnitTestExitException', +]); +*/ + +/* + * ------------------------------------------------------------------- + * Added for ci-phpunit-test + * ------------------------------------------------------------------- + */ + +// If you want to change the path of tests directory, set TESTPATH +/* +define('TESTPATH', APPPATH.'tests'.DIRECTORY_SEPARATOR); +*/ + +require __DIR__ . '/_ci_phpunit_test/CIPHPUnitTest.php'; + +CIPHPUnitTest::init(); +// Or you can set directories for autoloading +/* +CIPHPUnitTest::init([ + // Directories for autoloading + APPPATH.'models', + APPPATH.'libraries', + APPPATH.'controllers', + APPPATH.'modules', +]); +*/ diff --git a/application/tests/DbTestCase.php b/application/tests/DbTestCase.php new file mode 100644 index 00000000..62df8640 --- /dev/null +++ b/application/tests/DbTestCase.php @@ -0,0 +1,5 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTest +{ + private static $loader_class = 'MX_Loader'; + private static $controller_class; + private static $autoload_dirs; + + /** + * Initialize CIPHPUnitTest + * + * @param array $autoload_dirs directories to search class file for autoloader + */ + public static function init(array $autoload_dirs = null) + { + if (! defined('TESTPATH')) { + define('TESTPATH', APPPATH.'tests'.DIRECTORY_SEPARATOR); + } + + // Fix CLI args + $_server_backup = $_SERVER; + $_SERVER['argv'] = [ + 'index.php', + 'welcome' // Dummy + ]; + $_SERVER['argc'] = 2; + + self::$autoload_dirs = $autoload_dirs; + + $cwd_backup = getcwd(); + + // Load autoloader for ci-phpunit-test + require __DIR__ . '/autoloader.php'; + + require TESTPATH . 'TestCase.php'; + + $db_test_case_file = TESTPATH . 'DbTestCase.php'; + if (is_readable($db_test_case_file)) + { + require $db_test_case_file; + } + + $unit_test_case_file = TESTPATH . 'UnitTestCase.php'; + if (is_readable($unit_test_case_file)) + { + require $unit_test_case_file; + } + + // Replace a few Common functions + require __DIR__ . '/replacing/core/Common.php'; + require BASEPATH . 'core/Common.php'; + + // Workaround for missing CodeIgniter's error handler + // See https://github.com/kenjis/ci-phpunit-test/issues/37 + set_error_handler('_error_handler'); + + // Load new functions of CIPHPUnitTest + require __DIR__ . '/functions.php'; + // Load ci-phpunit-test CI_Loader + require __DIR__ . '/replacing/core/Loader.php'; + // Load ci-phpunit-test CI_Input + require __DIR__ . '/replacing/core/Input.php'; + // Load ci-phpunit-test CI_Output + require __DIR__ . '/replacing/core/Output.php'; + + // Change current directory + chdir(FCPATH); + + /* + * -------------------------------------------------------------------- + * LOAD THE BOOTSTRAP FILE + * -------------------------------------------------------------------- + * + * And away we go... + */ + require __DIR__ . '/replacing/core/CodeIgniter.php'; + + self::replaceHelpers(); + + // Create CodeIgniter instance + if (! self::wiredesignzHmvcInstalled()) + { + new CI_Controller(); + } + else + { + new MX_Controller(); + } + + // This code is here, not to cause errors with HMVC + self::replaceLoader(); + + // Restore $_SERVER. We need this for NetBeans + $_SERVER = $_server_backup; + + // Restore cwd to use `Usage: phpunit [options] ` + chdir($cwd_backup); + } + + /** + * @param bool $use_my_controller + */ + public static function createCodeIgniterInstance($use_my_controller = false) + { + if (! self::wiredesignzHmvcInstalled()) + { + if ($use_my_controller && self::hasMyController()) + { + new self::$controller_class; + } + else + { + new CI_Controller(); + } + } + else + { + new CI(); + new MX_Controller(); + } + } + + private static function hasMyController() + { + if (self::$controller_class !== null) { + return self::$controller_class !== 'CI_Controller'; + } + + $my_controller_file = + APPPATH . 'core/' . config_item('subclass_prefix') . 'Controller.php'; + + if (file_exists($my_controller_file)) + { + $controller_class = config_item('subclass_prefix') . 'Controller'; + if ( ! class_exists($controller_class)) + { + require $my_controller_file; + } + + self::$controller_class = $controller_class; + return true; + } + + self::$controller_class = 'CI_Controller'; + return false; + } + + public static function wiredesignzHmvcInstalled() + { + if (file_exists(APPPATH.'third_party/MX')) + { + return true; + } + + return false; + } + + public static function getAutoloadDirs() + { + return self::$autoload_dirs; + } + + protected static function replaceLoader() + { + $my_loader_file = + APPPATH . 'core/' . config_item('subclass_prefix') . 'Loader.php'; + + if (file_exists($my_loader_file)) + { + self::$loader_class = config_item('subclass_prefix') . 'Loader'; + if ( ! class_exists(self::$loader_class)) + { + require $my_loader_file; + } + } + self::loadLoader(); + } + + protected static function replaceHelpers() + { + $helpers = ['url_helper', 'download_helper']; + foreach ($helpers as $helper) { + static::loadHelper($helper); + } + } + + protected static function loadHelper($helper) + { + $my_helper_file = APPPATH . 'helpers/' . config_item('subclass_prefix') . $helper . '.php'; + if (file_exists($my_helper_file)) + { + require $my_helper_file; + } + require __DIR__ . '/replacing/helpers/' . $helper . '.php'; + } + + public static function setPatcherCacheDir($dir = null) + { + if ($dir === null) + { + $dir = TESTPATH . '_ci_phpunit_test/tmp/cache'; + } + + MonkeyPatchManager::setCacheDir( + $dir + ); + } + + public static function loadLoader() + { + $loader = new self::$loader_class; + load_class_instance('Loader', $loader); + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestAutoloader.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestAutoloader.php new file mode 100644 index 00000000..2c6e4390 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestAutoloader.php @@ -0,0 +1,164 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestAutoloader +{ + private $alias = [ + 'MonkeyPatch', + 'ReflectionHelper', + ]; + + /** + * @var directories to search file + */ + private $dirs = []; + + /** + * @var CIPHPUnitTestFileCache + */ + private $cache; + + /** + * @param CIPHPUnitTestFileCache $cache + * @param array $dirs directories to search file + */ + public function __construct( + CIPHPUnitTestFileCache $cache = null, + array $dirs = null + ) + { + $this->cache = $cache; + if ($dirs === null) + { + $this->dirs = [ + APPPATH.'models', + APPPATH.'libraries', + APPPATH.'controllers', + APPPATH.'modules', + APPPATH.'hooks', + ]; + } + else + { + $this->dirs = $dirs; + } + } + + public function load($class) + { + if ($this->cache) + { + if ($this->loadFromCache($class)) + { + return; + } + } + + $this->loadCIPHPUnitTestAliasClass($class); + $this->loadCIPHPUnitTestClass($class); + $this->loadApplicationClass($class); + } + + protected function loadCIPHPUnitTestAliasClass($class) + { + if (in_array($class, $this->alias)) + { + $dir = __DIR__ . '/alias'; + $this->loadClassFile($dir, $class); + } + } + + protected function loadCIPHPUnitTestClass($class) + { + if (substr($class, 0, 13) !== 'CIPHPUnitTest') + { + return; + } + + if (substr($class, -9) !== 'Exception') + { + $dir = __DIR__; + $this->loadClassFile($dir, $class); + } + else + { + $dir = __DIR__ . '/exceptions'; + $this->loadClassFile($dir, $class); + } + } + + protected function loadApplicationClass($class) + { + foreach ($this->dirs as $dir) + { + if ( ! is_dir($dir)) + { + continue; + } + + if ($this->loadClassFile($dir, $class)) + { + return true; + } + + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator( + $dir, \RecursiveDirectoryIterator::SKIP_DOTS + ), + \RecursiveIteratorIterator::SELF_FIRST + ); + + foreach ($iterator as $file) + { + if ($file->isDir()) + { + if ($this->loadClassFile($file, $class)) + { + return true; + } + } + } + } + } + + protected function loadClassFile($dir, $class) + { + $class_file = $dir . '/' . $class . '.php'; + if (file_exists($class_file)) + { + require $class_file; + if ($this->cache) + { + $this->cache[$class] = $class_file; + } + return true; + } + + return false; + } + + protected function loadFromCache($class) + { + if ($filename = $this->cache[$class]) + { + if (is_readable($filename)) + { + require $filename; + return true; + } + else + { + unset($this->cache[$class]); + } + } + + return false; + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestCase.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestCase.php new file mode 100644 index 00000000..4ac160bb --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestCase.php @@ -0,0 +1,445 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Support PHPUnit 6.0 +if (! class_exists('PHPUnit_Framework_TestCase')) +{ + class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase'); +} + +/** + * @property CIPHPUnitTestRequest $request + * @property CIPHPUnitTestDouble $double + * @property CIPHPUnitTestReflection $reflection + */ +class CIPHPUnitTestCase extends PHPUnit_Framework_TestCase +{ + protected $_error_reporting = -1; + + /** + * If you have a route with closure, PHPUnit can't serialize global variables. + * You would see `Exception: Serialization of 'Closure' is not allowed`. + * + * @var array + */ + protected $backupGlobalsBlacklist = ['RTR']; + + /** + * Detect warnings and notices in a request output + * + * @var bool + */ + protected $strictRequestErrorCheck = true; + + protected $restoreErrorHandler = false; + + /** + * @var CI_Controller CodeIgniter instance + */ + protected $CI; + + protected $class_map = [ + 'request' => 'CIPHPUnitTestRequest', + 'double' => 'CIPHPUnitTestDouble', + 'reflection' => 'CIPHPUnitTestReflection', + ]; + + public function setCI(CI_Controller $CI) + { + $this->CI = $CI; + } + + public function getStrictRequestErrorCheck() + { + return $this->strictRequestErrorCheck; + } + + public function __get($name) + { + if (isset($this->class_map[$name])) + { + $this->$name = new $this->class_map[$name]($this); + return $this->$name; + } + + throw new LogicException('No such property: ' . $name); + } + + public static function setUpBeforeClass() + { + // Fix CLI args, because you may set invalid URI characters + // For example, when you run tests on NetBeans + $_SERVER['argv'] = [ + 'index.php', + ]; + $_SERVER['argc'] = 1; + + // Reset current directroy + chdir(FCPATH); + } + + public static function tearDownAfterClass() + { + CIPHPUnitTestDbConnectionStore::destory(); + } + + /** + * Reset CodeIgniter instance and assign new CodeIgniter instance as $this->CI + * + * @param bool $use_my_controller + */ + public function resetInstance($use_my_controller = false) + { + reset_instance(); + CIPHPUnitTest::createCodeIgniterInstance($use_my_controller); + $this->CI =& get_instance(); + } + + protected function tearDown() + { + $this->disableStrictErrorCheck(); + + if (class_exists('MonkeyPatch', false)) + { + if (MonkeyPatchManager::isEnabled('FunctionPatcher')) + { + try { + MonkeyPatch::verifyFunctionInvocations(); + } catch (Exception $e) { + MonkeyPatch::resetFunctions(); + throw $e; + } + + MonkeyPatch::resetFunctions(); + } + + if (MonkeyPatchManager::isEnabled('ConstantPatcher')) + { + MonkeyPatch::resetConstants(); + } + + if (MonkeyPatchManager::isEnabled('MethodPatcher')) + { + try { + MonkeyPatch::verifyMethodInvocations(); + } catch (Exception $e) { + MonkeyPatch::resetMethods(); + throw $e; + } + + MonkeyPatch::resetMethods(); + } + } + } + + /** + * Request to Controller + * + * @param string $http_method HTTP method + * @param array|string $argv array of controller,method,arg|uri + * @param array $params POST parameters/Query string + */ + public function request($http_method, $argv, $params = []) + { + return $this->request->request($http_method, $argv, $params); + } + + /** + * Disable strict error check + */ + public function disableStrictErrorCheck() + { + if ($this->restoreErrorHandler) { + restore_error_handler(); + $this->restoreErrorHandler = false; + } + } + + /** + * Enable strict error check + */ + public function enableStrictErrorCheck() + { + if ($this->restoreErrorHandler) { + throw new LogicException('Already strict error check mode'); + } + + set_error_handler( + function ($errno, $errstr, $errfile, $errline) { + throw new RuntimeException($errstr . ' on line ' . $errline . ' in file ' . $errfile); + } + ); + + $this->restoreErrorHandler = true; + } + + /** + * Request to Controller using ajax request + * + * @param string $http_method HTTP method + * @param array|string $argv array of controller,method,arg|uri + * @param array $params POST parameters/Query string + */ + public function ajaxRequest($http_method, $argv, $params = []) + { + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest'; + return $this->request($http_method, $argv, $params); + } + + /** + * Get Mock Object + * + * $email = $this->getMockBuilder('CI_Email') + * ->setMethods(['send']) + * ->getMock(); + * $email->method('send')->willReturn(TRUE); + * + * will be + * + * $email = $this->getDouble('CI_Email', ['send' => TRUE]); + * + * @param string $classname + * @param array $params [method_name => return_value] + * @param bool $enable_constructor enable constructor or not + * @return object PHPUnit mock object + */ + public function getDouble($classname, $params, $enable_constructor = false) + { + return $this->double->getDouble($classname, $params, $enable_constructor); + } + + /** + * Verifies that method was called exactly $times times + * + * $loader->expects($this->exactly(2)) + * ->method('view') + * ->withConsecutive( + * ['shop_confirm', $this->anything(), TRUE], + * ['shop_tmpl_checkout', $this->anything()] + * ); + * + * will be + * + * $this->verifyInvokedMultipleTimes( + * $loader, + * 'view', + * 2, + * [ + * ['shop_confirm', $this->anything(), TRUE], + * ['shop_tmpl_checkout', $this->anything()] + * ] + * ); + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param int $times + * @param array $params arguments + */ + public function verifyInvokedMultipleTimes($mock, $method, $times, $params = null) + { + $this->double->verifyInvokedMultipleTimes( + $mock, $method, $times, $params + ); + } + + /** + * Verifies a method was invoked at least once + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param array $params arguments + */ + public function verifyInvoked($mock, $method, $params = null) + { + $this->double->verifyInvoked($mock, $method, $params); + } + + /** + * Verifies that method was invoked only once + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param array $params arguments + */ + public function verifyInvokedOnce($mock, $method, $params = null) + { + $this->double->verifyInvokedOnce($mock, $method, $params); + } + + /** + * Verifies that method was not called + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param array $params arguments + */ + public function verifyNeverInvoked($mock, $method, $params = null) + { + $this->double->verifyNeverInvoked($mock, $method, $params); + } + + public function warningOff() + { + $this->_error_reporting = error_reporting( + E_ALL & ~E_WARNING & ~E_NOTICE + ); + } + + public function warningOn() + { + error_reporting($this->_error_reporting); + } + + /** + * Asserts HTTP response code + * + * @param int $code + */ + public function assertResponseCode($code) + { + $status = $this->request->getStatus(); + $actual = $status['code']; + + $this->assertSame( + $code, + $actual, + 'Status code is not ' . $code . ' but ' . $actual . '.' + ); + } + + /** + * Asserts HTTP response header + * + * @param string $name header name + * @param string $value header value + */ + public function assertResponseHeader($name, $value) + { + $CI =& get_instance(); + $actual = $CI->output->get_header($name); + + if ($actual === null) + { + $this->fail("The '$name' header is not set.\nNote that `assertResponseHeader()` can only assert headers set by `\$this->output->set_header()`"); + } + + $this->assertEquals( + $value, + $actual, + "The '$name' header is not '$value' but '$actual'." + ); + } + + /** + * Asserts HTTP response cookie + * + * @param string $name cookie name + * @param string|array $value cookie value|array of cookie params + * @param bool $allow_duplicate whether to allow duplicated cookies + */ + public function assertResponseCookie($name, $value, $allow_duplicate = false) + { + $CI =& get_instance(); + $cookies = isset($CI->output->_cookies[$name]) + ? $CI->output->_cookies[$name] : null; + + if ($cookies === null) + { + $this->fail("The cookie '$name' is not set.\nNote that `assertResponseCookie()` can only assert cookies set by `\$this->input->set_cookie()`"); + } + + $count = count($cookies); + if ($count > 1 && ! $allow_duplicate) + { + $values = []; + foreach ($cookies as $key => $val) + { + $values[] = "'{$val['value']}'"; + } + $values = implode(' and ', $values); + $this->fail("You have more than one cookie '$name'. The values are $values.\nIf it is okay, please set `true` as the 3rd argument of `assertResponseCookie()`"); + } + + // Get the last cookie + $cookie = $cookies[$count - 1]; + if (is_string($value)) + { + $this->assertEquals( + $value, + $cookie['value'], + "The cookie '$name' value is not '$value' but '{$cookie['value']}'." + ); + return; + } + + // In case of $this->anything() + if ( + $value instanceof PHPUnit_Framework_Constraint_IsAnything + || $value instanceof PHPUnit\Framework\Constraint\IsAnything + ) + { + $this->assertTrue(true); + return; + } + + foreach ($value as $key => $val) + { + $this->assertEquals( + $value[$key], + $cookie[$key], + "The cookie '$name' $key is not '{$value[$key]}' but '{$cookie[$key]}'." + ); + } + } + + /** + * Asserts Redirect + * + * @param string $uri URI to redirect + * @param int $code response code + */ + public function assertRedirect($uri, $code = null) + { + $status = $this->request->getStatus(); + + if ($status['redirect'] === null) + { + $this->fail('redirect() is not called.'); + } + + if (! function_exists('site_url')) + { + $CI =& get_instance(); + $CI->load->helper('url'); + } + + if (! preg_match('#^(\w+:)?//#i', $uri)) + { + $uri = site_url($uri); + } + $absolute_url = $uri; + $expected = 'Redirect to ' . $absolute_url; + + $this->assertSame( + $expected, + $status['redirect'], + 'URL to redirect is not ' . $expected . ' but ' . $status['redirect'] . '.' + ); + + if ($code !== null) + { + $this->assertSame( + $code, + $status['code'], + 'Status code is not ' . $code . ' but ' . $status['code'] . '.' + ); + } + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestDbConnectionStore.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestDbConnectionStore.php new file mode 100644 index 00000000..9825e0d3 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestDbConnectionStore.php @@ -0,0 +1,27 @@ +dsn !== 'sqlite::memory:' && $db->database !== ':memory:') { + $db->close(); + } + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestDbTestCase.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestDbTestCase.php new file mode 100644 index 00000000..f327e132 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestDbTestCase.php @@ -0,0 +1,205 @@ + + * @license MIT License + * @copyright 2016 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * Copyright for Original Code + * + * @author CodeIgniter Dev Team + * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link http://codeigniter.com + * + * @see https://github.com/bcit-ci/CodeIgniter4/blob/59e1587a9875141586f8333ff9cc64cdae2173c4/system/Test/CIDatabaseTestCase.php + */ + +class CIPHPUnitTestDbTestCase extends CIPHPUnitTestCase +{ + protected $db; + + /** + * Stores information needed to remove any + * rows inserted via $this->hasInDatabase(); + * + * @var array + */ + protected $insertCache = []; + + protected function loadDependencies() + { + if ($this->db === null) + { + $CI =& get_instance(); + $CI->load->database(); + $this->db = $CI->db; + } + } + + protected function setUp() + { + $this->loadDependencies(); + } + + //-------------------------------------------------------------------- + + /** + * Takes care of any required cleanup after the test, like + * removing any rows inserted via $this->hasInDatabase() + */ + protected function tearDown() + { + if (! empty($this->insertCache)) + { + foreach ($this->insertCache as $row) + { + $this->db->delete($row[0], $row[1]); + } + } + } + + /** + * Workaround for the following error + * + * Error: Call to a member function quote() on boolean + * vendor/codeigniter/framework/system/database/drivers/pdo/pdo_driver.php:234 + * + * I don't know why, but when I call $this->seeInDatabase() after $this->request(), + * I got it + */ + private function checkDbConnId() + { + if (is_object($this->db->conn_id)) { + return; + } + + $this->db->close(); + $this->db = null; + + $CI =& get_instance(); + $CI->load->database(); + $this->db = $this->CI->db; + } + + //-------------------------------------------------------------------- + // Database Test Helpers + //-------------------------------------------------------------------- + + /** + * Asserts that records that match the conditions in $where do + * not exist in the database. + * + * @param string $table + * @param array $where + * + * @return bool + */ + public function dontSeeInDatabase($table, array $where) + { + $this->checkDbConnId(); + + $this->db->from($table); + $this->db->where($where); + $count = $this->db->count_all_results(); + + $this->assertTrue($count == 0, 'Row was found in database'); + } + + //-------------------------------------------------------------------- + + /** + * Asserts that records that match the conditions in $where DO + * exist in the database. + * + * @param string $table + * @param array $where + * + * @return bool + */ + public function seeInDatabase($table, array $where) + { + $this->checkDbConnId(); + + $this->db->from($table); + $this->db->where($where); + $count = $this->db->count_all_results(); + + $this->assertTrue($count > 0, 'Row not found in database'); + } + + //-------------------------------------------------------------------- + + /** + * Fetches a single column from a database row with criteria + * matching $where. + * + * @param string $table + * @param string $column + * @param array $where + * + * @return bool + */ + public function grabFromDatabase($table, $column, array $where) + { + $this->checkDbConnId(); + + $this->db->select($column); + $this->db->where($where); + $query = $this->db->get($table); + $row = $query->row(); + + return isset($row->$column) ? $row->$column : false; + } + + //-------------------------------------------------------------------- + + /** + * Inserts a row into to the database. This row will be removed + * after the test has run. + * + * @param string $table + * @param array $data + * + */ + public function hasInDatabase($table, array $data) + { + $this->checkDbConnId(); + + $this->insertCache[] = [ + $table, $data + ]; + + $this->db->insert($table, $data); + } + + //-------------------------------------------------------------------- + + /** + * Asserts that the number of rows in the database that match $where + * is equal to $expected. + * + * @param int $expected + * @param string $table + * @param array $where + * + * @return bool + */ + public function seeNumRecords($expected, $table, array $where = []) + { + $this->checkDbConnId(); + + $this->db->from($table); + $this->db->where($where); + $count = $this->db->count_all_results(); + + $this->assertEquals($expected, $count, 'Wrong number of matching rows in database.'); + } + + //-------------------------------------------------------------------- + +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestDouble.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestDouble.php new file mode 100644 index 00000000..37a1d549 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestDouble.php @@ -0,0 +1,162 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestDouble +{ + protected $testCase; + + public function __construct(PHPUnit_Framework_TestCase $testCase) + { + $this->testCase = $testCase; + } + + /** + * Get Mock Object + * + * $email = $this->getMockBuilder('CI_Email') + * ->disableOriginalConstructor() + * ->setMethods(['send']) + * ->getMock(); + * $email->method('send')->willReturn(TRUE); + * + * will be + * + * $email = $this->getDouble('CI_Email', ['send' => TRUE]); + * + * @param string $classname + * @param array $params [method_name => return_value] + * @param mixed $constructor_params false: disable construntor, array: construntor params + * + * @return object PHPUnit mock object + */ + public function getDouble($classname, $params, $constructor_params = false) + { + $methods = array_keys($params); + + // `disableOriginalConstructor()` is the default, because if we call + // construnctor, it may call `$this->load->...` or other CodeIgniter + // methods in it. But we can't use them in + // `$this->request->setCallablePreConstructor()` + $mock = $this->testCase->getMockBuilder($classname); + if ($constructor_params === false) + { + $mock->disableOriginalConstructor(); + } + elseif (is_array($constructor_params)) + { + $mock->setConstructorArgs($constructor_params); + } + $mock = $mock->setMethods($methods)->getMock(); + + foreach ($params as $method => $return) + { + if (is_object($return) && $return instanceof PHPUnit_Framework_MockObject_Stub) { + $mock->expects($this->testCase->any())->method($method) + ->will($return); + } elseif (is_object($return) && $return instanceof Closure) { + $mock->expects($this->testCase->any())->method($method) + ->willReturnCallback($return); + } else { + $mock->expects($this->testCase->any())->method($method) + ->willReturn($return); + } + } + + return $mock; + } + + protected function _verify($mock, $method, $params = null, $expects, $with) + { + $invocation = $mock->expects($expects) + ->method($method); + + if ($params === null) { + return; + } + + call_user_func_array([$invocation, $with], $params); + } + + /** + * Verifies that method was called exactly $times times + * + * $loader->expects($this->exactly(2)) + * ->method('view') + * ->withConsecutive( + * ['shop_confirm', $this->anything(), TRUE], + * ['shop_tmpl_checkout', $this->anything()] + * ); + * + * will be + * + * $this->verifyInvokedMultipleTimes( + * $loader, + * 'view', + * 2, + * [ + * ['shop_confirm', $this->anything(), TRUE], + * ['shop_tmpl_checkout', $this->anything()] + * ] + * ); + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param int $times + * @param array $params arguments + */ + public function verifyInvokedMultipleTimes($mock, $method, $times, $params = null) + { + $this->_verify( + $mock, $method, $params, $this->testCase->exactly($times), 'withConsecutive' + ); + } + + /** + * Verifies a method was invoked at least once + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param array $params arguments + */ + public function verifyInvoked($mock, $method, $params = null) + { + $this->_verify( + $mock, $method, $params, $this->testCase->atLeastOnce(), 'with' + ); + } + + /** + * Verifies that method was invoked only once + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param array $params arguments + */ + public function verifyInvokedOnce($mock, $method, $params = null) + { + $this->_verify( + $mock, $method, $params, $this->testCase->once(), 'with' + ); + } + + /** + * Verifies that method was not called + * + * @param object $mock PHPUnit mock object + * @param string $method + * @param array $params arguments + */ + public function verifyNeverInvoked($mock, $method, $params = null) + { + $this->_verify( + $mock, $method, $params, $this->testCase->never(), 'with' + ); + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestFileCache.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestFileCache.php new file mode 100644 index 00000000..015c1f75 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestFileCache.php @@ -0,0 +1,91 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestFileCache implements ArrayAccess +{ + private $file; + private $map = []; + private $updated = false; + + public function __construct($file) + { + $this->file = $file; + + if (file_exists($this->file)) + { + $this->map = unserialize(file_get_contents($this->file)); + return; + } + + $dir = dirname($this->file); + if (! is_dir($dir)) + { + if (@mkdir($dir, 0777, true) === false) + { + throw new RuntimeException('Failed to create folder: ' . $dir); + } + } + + if (file_put_contents($this->file, '') === false) + { + throw new RuntimeException( + 'Failed to write to cache file: ' . $this->file + ); + } + } + + public function __destruct() + { + if ($this->updated) { + file_put_contents($this->file, serialize($this->map)); + } + } + + /** + * Dump cache data (sorted by key) + * + * @return array + */ + public function dump() + { + $map = $this->map; + ksort($map); + return $map; + } + + public function offsetSet($key, $value) + { + $this->map[$key] = $value; + $this->updated = true; + } + + public function offsetGet($key) + { + if ($this->offsetExists($key)) + { + return $this->map[$key]; + } + else + { + return null; + } + } + + public function offsetExists($key) + { + return isset($this->map[$key]); + } + + public function offsetUnset($key) + { + unset($this->map[$key]); + $this->updated = true; + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestNullCodeIgniter.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestNullCodeIgniter.php new file mode 100644 index 00000000..3597d47a --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestNullCodeIgniter.php @@ -0,0 +1,20 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * Represents CodeIgniter instance is null + */ +class CIPHPUnitTestNullCodeIgniter +{ + public function __get($name) + { + throw new LogicException("CodeIgniter instance is not instantiated yet. You can't use `\$this->$name` at the moment. Please fix your test code."); + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestReflection.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestReflection.php new file mode 100644 index 00000000..dc9303c8 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestReflection.php @@ -0,0 +1,65 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestReflection +{ + /** + * @param object|string $obj object or class name + * @param string $method method name + * @return closure + */ + public static function getPrivateMethodInvoker($obj, $method) + { + $ref_method = new ReflectionMethod($obj, $method); + $ref_method->setAccessible(true); + $obj = (gettype($obj) === 'object') ? $obj : null; + + return function () use ($obj, $ref_method) { + $args = func_get_args(); + return $ref_method->invokeArgs($obj, $args); + }; + } + + protected static function getAccessibleRefProperty($obj, $property) + { + if (is_object($obj)) { + $ref_class = new ReflectionObject($obj); + } else { + $ref_class = new ReflectionClass($obj); + } + + $ref_property = $ref_class->getProperty($property); + $ref_property->setAccessible(true); + + return $ref_property; + } + + /** + * @param object|string $obj object or class name + * @param string $property property name + * @param mixed $value value + */ + public static function setPrivateProperty($obj, $property, $value) + { + $ref_property = self::getAccessibleRefProperty($obj, $property); + $ref_property->setValue($obj, $value); + } + + /** + * @param object|string $obj object or class name + * @param string $property property name + * @return mixed value + */ + public static function getPrivateProperty($obj, $property) + { + $ref_property = self::getAccessibleRefProperty($obj, $property); + return $ref_property->getValue($obj); + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestRequest.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestRequest.php new file mode 100644 index 00000000..b03b62d4 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestRequest.php @@ -0,0 +1,403 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestRequest +{ + /** + * @var TestCase + */ + protected $testCase; + + /** + * @var CIPHPUnitTestSuperGlobal + */ + protected $superGlobal; + + /** + * @var CIPHPUnitTestRouter + */ + protected $router; + + /** + * @var callable[] callable called post controller constructor + */ + protected $callables = []; + + /** + * @var callable[] callable called pre controller constructor + */ + protected $callablePreConstructors = []; + + protected $enableHooks = false; + + /** + * @var CI_Hooks + */ + protected $hooks; + + public function __construct(CIPHPUnitTestCase $testCase) + { + $this->testCase = $testCase; + $this->superGlobal = new CIPHPUnitTestSuperGlobal(); + $this->router = new CIPHPUnitTestRouter(); + } + + /** + * Set HTTP request header + * + * @param string $name header name + * @param string $value value + */ + public function setHeader($name, $value) + { + $this->superGlobal->set_SERVER_HttpHeader($name, $value); + } + + /** + * Set $_FILES + * + * @param array $files + */ + public function setFiles(array $files) + { + $this->superGlobal->set_FILES($files); + } + + /** + * Set (and Reset) callable + * + * @param callable $callable function to run after controller instantiation + */ + public function setCallable(callable $callable) + { + $this->callables = []; + $this->callables[] = $callable; + } + + /** + * Add callable + * + * @param callable $callable function to run after controller instantiation + */ + public function addCallable(callable $callable) + { + $this->callables[] = $callable; + } + + /** + * Set (and Reset) callable pre constructor + * + * @param callable $callable function to run before controller instantiation + */ + public function setCallablePreConstructor(callable $callable) + { + $this->callablePreConstructors = []; + $this->callablePreConstructors[] = $callable; + } + + /** + * Add callable pre constructor + * + * @param callable $callable function to run before controller instantiation + */ + public function addCallablePreConstructor(callable $callable) + { + $this->callablePreConstructors[] = $callable; + } + + /** + * Enable Hooks for Controllres + * This enables only pre_controller, post_controller_constructor, post_controller + */ + public function enableHooks() + { + $this->enableHooks = true; + $this->hooks =& load_class('Hooks', 'core'); + } + + /** + * Request to Controller + * + * @param string $http_method HTTP method + * @param array|string $argv array of controller,method,arg|uri + * @param array|string $params POST params/GET params|raw_input_stream + */ + public function request($http_method, $argv, $params = []) + { + if ($this->testCase->getStrictRequestErrorCheck()) { + $this->testCase->enableStrictErrorCheck(); + } + + if (is_string($argv)) + { + $argv = ltrim($argv, '/'); + } + + // Set super globals + $_SERVER['REQUEST_METHOD'] = $http_method; + $this->superGlobal->set_GET($argv, $params); + $this->superGlobal->set_POST($params); + $this->superGlobal->set_SERVER_REQUEST_URI($argv); + + try { + if (is_array($argv)) + { + $ret = $this->callControllerMethod( + $http_method, $argv, $params + ); + $this->testCase->disableStrictErrorCheck(); + return $ret; + } + else + { + $ret = $this->requestUri($http_method, $argv, $params); + $this->testCase->disableStrictErrorCheck(); + return $ret; + } + } + // redirect() + catch (CIPHPUnitTestRedirectException $e) + { + $this->testCase->disableStrictErrorCheck(); + if ($e->getCode() === 0) + { + set_status_header(200); + } + else + { + set_status_header($e->getCode()); + } + $CI =& get_instance(); + $CI->output->_status['redirect'] = $e->getMessage(); + } + // show_404() + catch (CIPHPUnitTestShow404Exception $e) + { + $this->testCase->disableStrictErrorCheck(); + $this->processError($e); + return $e->getMessage(); + } + // show_error() + catch (CIPHPUnitTestShowErrorException $e) + { + $this->testCase->disableStrictErrorCheck(); + $this->processError($e); + return $e->getMessage(); + } + // exit() + catch (CIPHPUnitTestExitException $e) + { + $this->testCase->disableStrictErrorCheck(); + $output = ob_get_clean(); + return $output; + } + } + + protected function processError(Exception $e) + { + set_status_header($e->getCode()); + } + + /** + * Call Controller Method + * + * @param string $http_method HTTP method + * @param array $argv controller, method [, arg1, ...] + * @param array|string $request_params POST params/GET params|raw_input_stream + */ + protected function callControllerMethod($http_method, $argv, $request_params) + { + $_SERVER['argv'] = array_merge(['index.php'], $argv); + + $class = ucfirst($argv[0]); + $method = $argv[1]; + + // Remove controller and method + array_shift($argv); + array_shift($argv); + +// $request = [ +// 'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'], +// 'class' => $class, +// 'method' => $method, +// 'params' => $argv, +// '$_GET' => $_GET, +// '$_POST' => $_POST, +// ]; +// var_dump($request, $_SERVER['argv']); + + // Reset CodeIgniter instance state + reset_instance(); + + $this->setRawInputStream($request_params); + + // 404 checking + if (! class_exists($class) || ! method_exists($class, $method)) + { + // If 404, CodeIgniter instance is not created yet. So create it here + // Because we need CI->output->_status to store info + $CI =& get_instance(); + if ($CI instanceof CIPHPUnitTestNullCodeIgniter) + { + CIPHPUnitTest::createCodeIgniterInstance(); + } + + show_404($class.'::'.$method . '() is not found'); + } + + $params = $argv; + + return $this->createAndCallController($class, $method, $params, false); + } + + /** + * Request to URI + * + * @param string $http_method HTTP method + * @param string $uri URI string + * @param array|string $request_params POST params/GET params|raw_input_stream + */ + protected function requestUri($http_method, $uri, $request_params) + { + $_SERVER['argv'] = ['index.php', $uri]; + $_SERVER['PATH_INFO'] = '/'.$uri; + + // Force cli mode because if not, it changes URI (and RTR) behavior + $cli = is_cli(); + set_is_cli(TRUE); + + // Reset CodeIgniter instance state + reset_instance(); + + $this->setRawInputStream($request_params); + + // Get route + list($class, $method, $params) = $this->router->getRoute(); + + // Restore cli mode + set_is_cli($cli); + +// $request = [ +// 'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'], +// 'class' => $class, +// 'method' => $method, +// 'params' => $params, +// '$_GET' => $_GET, +// '$_POST' => $_POST, +// ]; +// var_dump($request, $_SERVER['argv']); + + return $this->createAndCallController($class, $method, $params); + } + + protected function callHook($hook) + { + if ($this->enableHooks) + { + return $this->hooks->call_hook($hook); + } + + return false; + } + + protected function setRawInputStream($string) + { + if (is_string($string)) + { + $INPUT =& load_class('Input', 'core'); + CIPHPUnitTestReflection::setPrivateProperty( + $INPUT, + '_raw_input_stream', + $string + ); + } + } + + protected function createAndCallController($class, $method, $params, $call_display = true) + { + ob_start(); + + $this->callHook('pre_controller'); + + // Run callablePreConstructor + if ($this->callablePreConstructors !== []) + { + foreach ($this->callablePreConstructors as $callable) + { + $callable(); + } + } + + // Create controller + if (CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + new CI(); + } + $controller = new $class; + $CI =& get_instance(); + + // Set CodeIgniter instance to TestCase + $this->testCase->setCI($CI); + + if (! isset($CI->output->_status)) + { + // Prevent overwriting, if already set in the $class::__construct() + // Set default response code 200 + set_status_header(200); + } + + // Run callable + if ($this->callables !== []) + { + foreach ($this->callables as $callable) + { + $callable($CI); + } + } + + $this->callHook('post_controller_constructor'); + + // Call controller method + call_user_func_array([$controller, $method], $params); + + $this->callHook('post_controller'); + + if ($call_display && $this->callHook('display_override') === false) + { + $CI->output->_display(); + } + + $output = ob_get_clean(); + + if ($output == '') + { + $output = $CI->output->get_output(); + } + + return $output; + } + + /** + * Get HTTP Status Code Info + * + * @return array ['code' => code, 'text' => text] + * @throws LogicException + */ + public function getStatus() + { + $CI =& get_instance(); + if (! isset($CI->output->_status)) + { + throw new LogicException('Status code is not set. You must call $this->request() first'); + } + + return $CI->output->_status; + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestRouter.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestRouter.php new file mode 100644 index 00000000..98bbbeeb --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestRouter.php @@ -0,0 +1,76 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestRouter +{ + /** + * Get Route including 404 check + * + * @see core/CodeIgniter.php + * + * @return array [class, method, pararms] + */ + public function getRoute() + { + $RTR =& load_class('Router', 'core'); + $URI =& load_class('URI', 'core'); + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + // WARNING: It appears that there are issues with is_callable() even in PHP 5.2! + // Furthermore, there are bug reports and feature/change requests related to it + // that make it unreliable to use in this context. Please, DO NOT change this + // work-around until a better alternative is available. + elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE)) + { + $e404 = TRUE; + } + } + + if ($e404) + { + // If 404, CodeIgniter instance is not created yet. So create it here. + // Because we need CI->output->_status + $CI =& get_instance(); + if ($CI instanceof CIPHPUnitTestNullCodeIgniter) + { + CIPHPUnitTest::createCodeIgniterInstance(); + } + + show_404($RTR->directory.$class.'/'.$method.' is not found'); + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + + return [$class, $method, $params]; + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestSuperGlobal.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestSuperGlobal.php new file mode 100644 index 00000000..2ccb0a85 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestSuperGlobal.php @@ -0,0 +1,198 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestSuperGlobal +{ + public static function set_Global($name, $value) + { + $GLOBALS[$name] = $value; + } + + public function set_POST($params) + { + if (is_array($params)) + { + if ($_SERVER['REQUEST_METHOD'] === 'POST') + { + $_POST = $params; + } + } + } + + public function set_FILES(array $files) + { + if (count($files) > 1) + { + throw new LogicException('Invalid $_FILES: '.var_export($files, true)); + } + + $field = array_keys($files)[0]; + $is_multiple = is_array($files[$field]['tmp_name']); + + if ($is_multiple) + { + throw new LogicException('Cannot handle multiple file upload. $_FILES: '.var_export($files, true)); + } + + // Handle single file + $file =& $files[$field]; + + if (! file_exists($file['tmp_name'])) + { + $file['error'] = UPLOAD_ERR_NO_FILE; + $file['type'] = ''; + $file['size'] = 0; + + $_FILES = $files; + return; + } + + $file['size'] = filesize($file['tmp_name']); + + $upload_max_filesize = $this->convertToBytes(ini_get('upload_max_filesize')); + if ($upload_max_filesize < $file['size']) + { + $file['error'] = UPLOAD_ERR_INI_SIZE; + + $_FILES = $files; + return; + } + + $file['error'] = UPLOAD_ERR_OK; + + $_FILES = $files; + return; + } + + private function convertToBytes($value) + { + if (is_numeric($value)) + { + return $value; + } + else + { + $value_length = strlen($value); + $number = substr($value, 0, $value_length - 1); + $unit = strtolower(substr($value, $value_length - 1)); + + switch ($unit) + { + case 'k': + $number *= 1024; + break; + case 'm': + $number *= 1024 * 1024; + break; + case 'g': + $number *= 1024 * 1024 * 1024; + break; + } + + return $number; + } + } + + public function set_GET(&$argv, $params) + { + if (is_string($argv)) + { + $query_string = $this->getQueryString($argv); + if ($query_string !== null) + { + // Set $_GET if URI string has query string + parse_str($query_string, $_GET); + // Remove query string from URI string + $argv = substr($argv, 0, -strlen($query_string)-1); + } + } + + if (is_array($params)) + { + if ($_SERVER['REQUEST_METHOD'] === 'GET') + { + // if GET params are passed, overwrite $_GET + if ($params !== []) + { + $_GET = $params; + } + } + } + } + + public function set_SERVER_REQUEST_URI($argv) + { + $path = ''; + if (is_string($argv)) + { + $path = $argv; + } + elseif (is_array($argv)) + { + // Generate URI path from array of controller, method, arg, ... + $path = implode('/', $argv); + } + + if ($_GET !== []) + { + $_SERVER['REQUEST_URI'] = + '/' . $path . '?' + . http_build_query($_GET); + } + else + { + $_SERVER['REQUEST_URI'] = '/' . $path; + } + } + + /** + * Parse URI string and Get query string + * + * @param string $uri + * @return string|null + * @throws LogicException + */ + protected function getQueryString($uri) + { + $query_string = parse_url('http://localhost/'.$uri, PHP_URL_QUERY); + + if ($query_string === false) + { + throw new LogicException('Bad URI string: ' . $uri); + } + + return $query_string; + } + + /** + * Set HTTP request header to $_SERVER + * + * @param string $name header name + * @param string $value value + */ + public function set_SERVER_HttpHeader($name, $value) + { + $normalized_name = str_replace('-', '_', strtoupper($name)); + + if ( + $normalized_name === 'CONTENT_LENGTH' + || $normalized_name === 'CONTENT_TYPE' + ) + { + $key = $normalized_name; + } + else + { + $key = 'HTTP_' . $normalized_name; + } + + $_SERVER[$key] = $value; + } +} diff --git a/application/tests/_ci_phpunit_test/CIPHPUnitTestUnitTestCase.php b/application/tests/_ci_phpunit_test/CIPHPUnitTestUnitTestCase.php new file mode 100644 index 00000000..4d651882 --- /dev/null +++ b/application/tests/_ci_phpunit_test/CIPHPUnitTestUnitTestCase.php @@ -0,0 +1,68 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestUnitTestCase extends CIPHPUnitTestCase +{ + /** + * Create a controller instance + * + * @param string $classname + * @return CI_Controller + */ + public function newController($classname) + { + reset_instance(); + $controller = new $classname; + $this->CI =& get_instance(); + return $controller; + } + + /** + * Create a model instance + * + * @param string $classname + * @return CI_Model + */ + public function newModel($classname) + { + $this->resetInstance(); + $this->CI->load->model($classname); + + // Is the model in a sub-folder? + if (($last_slash = strrpos($classname, '/')) !== FALSE) + { + $classname = substr($classname, ++$last_slash); + } + + return $this->CI->$classname; + } + + /** + * Create a library instance + * + * @param string $classname + * @param array $args + * @return object + */ + public function newLibrary($classname, $args = null) + { + $this->resetInstance(); + $this->CI->load->library($classname, $args); + + // Is the library in a sub-folder? + if (($last_slash = strrpos($classname, '/')) !== FALSE) + { + $classname = substr($classname, ++$last_slash); + } + $classname = strtolower($classname); + + return $this->CI->$classname; + } +} diff --git a/application/tests/_ci_phpunit_test/ChangeLog.md b/application/tests/_ci_phpunit_test/ChangeLog.md new file mode 100644 index 00000000..be72d119 --- /dev/null +++ b/application/tests/_ci_phpunit_test/ChangeLog.md @@ -0,0 +1,409 @@ +# Change Log for ci-phpunit-test + +## v0.17.0 (2019/04/28) + +### Fixed + +* Fix bug that you can't use `$this->request()` and `DbTestCase` class at the same time. +* Fix `MonkeyPatch::patchConstant()` when the user does not specify `$class_method`. See [#251](https://github.com/kenjis/ci-phpunit-test/pull/251/files). +* Fix bug that `vendor/kenjis/ci-phpunit-test/update.php` does not work. + +### Added + +* Now Seeder can call dependent seeders. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/master/docs/HowToWriteTests.md#database-seeding). +* `$this->resetInstance()` could create `MY_Controller` instance in stead of `CI_Controller` instance. See [#271](https://github.com/kenjis/ci-phpunit-test/pull/271). +* Now you can change Monkey Patch debug log file path. See [#243](https://github.com/kenjis/ci-phpunit-test/pull/243). + +### Others + +* Compatible with CodeIgniter 3.1.10 + +## v0.16.1 (2018/04/22) + +### Fixed + +* Fix bug that installer replaces file path in `tests/Bootstrap.php` with wrong code which causes Parse error. See [#247](https://github.com/kenjis/ci-phpunit-test/pull/247). +* Fix bug that `$this->request()` can't be called more than once in a test method. See [#248](https://github.com/kenjis/ci-phpunit-test/pull/248). + +### Others + +* Compatible with CodeIgniter 3.1.8 + +## v0.16.0 (2018/03/21) + +### Upgrade Note + +* Now ci-phpunit-test detects all warnings and notices during `$this->request()` execution, and throws exceptions. If you want to disable the checking, you must add `protected $strictRequestErrorCheck = false;` in your test classes. See [#235](https://github.com/kenjis/ci-phpunit-test/pull/235). +* If you use `$this->newModel()`, `$this->newLibrary()`, `$this->newController()` in your test cases, please install `tests/UnitTestCase.php` manually, and change the base classname of the test cases to `UnitTestCase` class. See [#233](https://github.com/kenjis/ci-phpunit-test/pull/233). +* Now ci-phpunit-test replaces `CI_Output`. If you use `MY_Output`, it might delete ci-phpunit-test override for testing. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/master/docs/HowToWriteTests.md#my_output) for the details. + +### Changed + +* Now ci-phpunit-test detects all warnings and notices during `$this->request()` execution, and throws exceptions. +* `$this->newModel()`, `$this->newLibrary()`, `$this->newController()` moved to `UnitTestCase` class. +* Now ci-phpunit-test replaces `CI_Output`. + +### Added + +* Now you can pass more than 5 arguments to `$this->verifyInvoked*()`. See [#192](https://github.com/kenjis/ci-phpunit-test/pull/192). +* Now you can assert whether a response cookie is just present or not. See [#205](https://github.com/kenjis/ci-phpunit-test/pull/205). +* Now you can move tests folder if you define `TESTPATH` in `application/tests/Bootstrap.php`. +* Now you can specify custom `application` and `public` directory when you install via Composer. See [README](https://github.com/kenjis/ci-phpunit-test#installation-via-composer). + +### Fixed + +* Fix bug that `set_status_header()` in controller constructor gets overwritten. See [#194](https://github.com/kenjis/ci-phpunit-test/issues/194). +* Fix bug that `MY_Config` is not loaded in `$this->request()`. See [#196](https://github.com/kenjis/ci-phpunit-test/issues/196). + +### Others + +* Compatible with CodeIgniter 3.1.7 +* Compatible with PHP 7.2 + +## v0.15.0 (2017/04/23) + +### Added + +* Now you can create a mock which has a stubbed method that returns the mock itself with using `$this->getDouble()`. See [#170](https://github.com/kenjis/ci-phpunit-test/pull/170). + +### Others + +* Compatible with CodeIgniter 3.1.4 + +## v0.14.0 (2017/02/09) + +### Upgrade Note for PHPUnit 6.0 users + +* Please update `application/tests/phpunit.xml`. Replace it or apply [this patch](https://github.com/kenjis/ci-phpunit-test/commit/fad5df8f580239a117e71593b373ddbd6deac7af). + +### Added + +* download_helper for testing. +* `$this->newModel()` for model unit testing. See [#156](https://github.com/kenjis/ci-phpunit-test/pull/156). +* `$this->newLibrary()` for library unit testing. See [#161](https://github.com/kenjis/ci-phpunit-test/pull/161). +* Now you can write test code for file uploading in controller testing. See [#157](https://github.com/kenjis/ci-phpunit-test/pull/157). +* Now *Monkey Patching* supports PHP 7.1 new syntax. + +### Fixed + +* Fix bug that `include_paths` and/or `exclude_paths` in *Monkey Patching* may not work correctly on Windows. + +### Others + +* Compatible with CodeIgniter 3.1.3 +* Update nikic/PHP-Parser to v2.1.1 +* Add nikic/PHP-Parser v3.0.3 +* Compatible with PHPUnit 6.0 + +## v0.13.0 (2016/11/20) + +### Upgrade Note + +* If you use database test helpers, please install `tests/DbTestCase.php` manually. + +### Added + +* Database test helpers. See [#133](https://github.com/kenjis/ci-phpunit-test/pull/133). +* Now you can return Closure with `$this->getDouble()`. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/master/docs/FunctionAndClassReference.md#testcasegetdoubleclassname-params-constructor_params--false). +* Now you can set constructor params with `$this->getDouble()`. See [#130](https://github.com/kenjis/ci-phpunit-test/pull/130). +* `$this->newController()` for controller unit testing. See [#147](https://github.com/kenjis/ci-phpunit-test/pull/147). + +### Fixed + +* Fix bug that routes with closure cause serialization errors. See [#139](https://github.com/kenjis/ci-phpunit-test/pull/139). + +### Others + +* Compatible with CodeIgniter 3.1.2 + +## v0.12.2 (2016/07/24) + +### Fixed + +* Fix bug that *Method Patcher* fails dealing with interfaces or abstract classes. +* Fix bug that *Method Patcher* does not work on Windows. + +### Others + +* Update nikic/PHP-Parser to v2.1.0 + +## v0.12.1 (2016/06/11) + +### Fixed + +* Fix bug that *Function Patcher* on `openssl_random_pseudo_bytes()` may cause "Warning: Missing argument 2". See [#119](https://github.com/kenjis/ci-phpunit-test/issues/119). +* Fix bug that installation/update script for Composer installation causes "Notice: Undefined offset: 1". + +## v0.12.0 (2016/04/17) + +### Added + +* Monkey Patching on constants. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.12.0/docs/HowToWriteTests.md#patching-constants). + +### Others + +* Update nikic/PHP-Parser to v2.0.1 + +## v0.11.3 (2016/03/25) + +### Fixed + +* `assertRedirect()` does not work with external redirects. See [#104](https://github.com/kenjis/ci-phpunit-test/pull/104). + +### Others + +* Compatible with CodeIgniter 3.0.6 +* Improved installer. See [#103](https://github.com/kenjis/ci-phpunit-test/pull/103). + +## v0.11.2 (2016/03/17) + +### Others + +* Compatible with CodeIgniter 3.0.5 + +## v0.11.1 (2016/02/22) + +### Fixed + +* Fix bug that `$this->input->get_request_header()` returns the first header value for all tests. See [#92](https://github.com/kenjis/ci-phpunit-test/issues/92). +* Fix bug that config values are not reset between tests. See [#94](https://github.com/kenjis/ci-phpunit-test/issues/94). +* Fix bug that `CI_Output::_display()` is called even if you call a controller method directly (when you pass an array to the 2nd argument of `$this->request()`). + +### Others + +* Improved documentation for `$this->request()`. + +## v0.11.0 (2016/01/20) + +### Upgrade Note + +* Now ci-phpunit-test replaces `CI_Input`. If you use MY_Input, see [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.11.0/docs/HowToWriteTests.md#my_input). +* If you use *Monkey Patching*, please update `tests/Bootstrap.php`. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.11.0/docs/HowToWriteTests.md#upgrade-note-for-v0110). +* If you use PsySH v0.5, please update to v0.6. + +### Added + +* `$this->assertResponseCookie()` to assert HTTP response cookies. See [#88](https://github.com/kenjis/ci-phpunit-test/pull/88). +* Now `$this->request->enableHooks()` calls hook `display_override`. +* `$this->request->addCallablePreConstructor()` to add callable. +* Now *Moneky Patching* can patch code with PHP 7 new syntax. +* `header()` and `setcookie()` are added to *Function Patcher*'s white list. + +### Fixed + +* `_output()` method in controllers does not work in controller testing. + +### Others + +* Compatible with CodeIgniter 3.0.4 +* Update nikic/PHP-Parser to v2.0.0 + +## v0.10.1 (2015/12/31) + +### Fixed + +* Fix bug that global variables for core classes are null. See [#75](https://github.com/kenjis/ci-phpunit-test/issues/75). +* Fix bug that can't use constant in `config.php`. See [#78](https://github.com/kenjis/ci-phpunit-test/issues/78). +* Fix bug that can't autoload library with alternative library name. See [#79](https://github.com/kenjis/ci-phpunit-test/pull/79). +* Fix bug that *Function Patcher* on `openssl_random_pseudo_bytes()` which returns `null` does not work. + +## v0.10.0 (2015/11/27) + +### Fixed + +* Fix wrong implementation of resetting CodeIgniter instance. Now `reset_instance()` removes the existing *CodeIgniter instance*. See [#74](https://github.com/kenjis/ci-phpunit-test/pull/74). + +### Changed + +* Now `$this->getDouble()` does not call the original constructor by default. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/v0.10.0/docs/FunctionAndClassReference.md#testcasegetdoubleclassname-params-enable_constructor--false). +* Now `reset_instance()` removes the existing *CodeIgniter instance*. See [#74](https://github.com/kenjis/ci-phpunit-test/pull/74). + +### Added + +* NetBeans test suite provider `application/tests/_ci_phpunit_test/TestSuiteProvider.php`. To use it, go to *Project Properties* > *Testing*, check *Use Custom Test Suite* checkbox, and select the file. + +## v0.9.1 (2015/11/22) + +### Fixed + +* Fix bug that `phpunit` dies when `Unable to locate the specified class` error. + +### Others + +* Improved documentation. + +## v0.9.0 (2015/11/18) + +### Added + +* `$this->request->addCallable()` to add callable. See [#68](https://github.com/kenjis/ci-phpunit-test/pull/68). +* Autoloading classes in `application/modules` folder. +* You can configure search paths for autoloader. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.9.0/docs/HowToWriteTests.md#autoloader). + +### Others + +* Compatible with CodeIgniter 3.0.3 + +## v0.8.2 (2015/10/09) + +### Fixed + +* Fix bug that monkey patching changes original source code in some cases of heredoc/nowdoc strings. + +### Others + +* Compatible with CodeIgniter 3.0.2 +* Compatible with PHP 7.0.0-RC4 +* Update nikic/PHP-Parser to v1.4.1 + +## v0.8.1 (2015/10/01) + +### Fixed + +* Fix bug that `$route['404_override']` controller/method is called in Bootstrap. See [#63](https://github.com/kenjis/ci-phpunit-test/pull/63). + +## v0.8.0 (2015/09/28) + +### Changed + +* Better support for SQLite in-memory database. Now `reset_instance()` does not close SQLite in-memory database connection. + +### Fixed + +* Fix bug that `$this->getDouble()` can't create mocks which have methods named method. +* Fix bug that monkey patching which returns `null` does not work. + +### Removed + +* Property `$bc_mode_throw_PHPUnit_Framework_Exception` in `CIPHPUnitTestRequest` class (deprecated since v0.4.0). See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.4.0/docs/HowToWriteTests.md#show_error-and-show_404). + +## v0.7.0 (2015/09/09) + +### Upgrade Note + +* Please update `application/tests/phpunit.xml`. Replace it or apply [this patch](https://github.com/kenjis/ci-phpunit-test/commit/7af9e330251e2ab72a631f4d5f92a41c0ad37aca). See [#52](https://github.com/kenjis/ci-phpunit-test/pull/52). + +### Changed + +* Now `$this->warningOff()` turns off Notice, too. + +### Added + +* Now `$this->request()` can create REST request more easily. See [#47](https://github.com/kenjis/ci-phpunit-test/pull/47). +* `$this->request->setHeader()` to set HTTP request header. See [#47](https://github.com/kenjis/ci-phpunit-test/pull/47). +* `$this->assertResponseHeader()` to assert HTTP response header. See [#47](https://github.com/kenjis/ci-phpunit-test/pull/47). +* You can add query string in URI string of `$this->request()`. See [#51](https://github.com/kenjis/ci-phpunit-test/pull/51). +* Autoloading for libraries +* Add `application/libraries/Session/MY_Session.php` as a sample +* `ReflectionHelper` class to access non-public method or property. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/v0.7.0/docs/FunctionAndClassReference.md#class-reflectionhelper). + +### Fixed + +* `$this->request()` returns null when `show_404()` or `show_error()` is called. Now it returns error message. +* `$this->CI` in `TestCase` class after calling `$this->request()` is still the previous instance. [#50](https://github.com/kenjis/ci-phpunit-test/issues/50). +* Autoloader only searches class files only in top level and sub folder for them. [#48](https://github.com/kenjis/ci-phpunit-test/issues/48). +* `set_status_header()` calls `header()` if `is_cli()` returns false. +* Fix `phpunit.xml`. See [#52](https://github.com/kenjis/ci-phpunit-test/pull/52). + +### Removed + +* 4th param `$callable` of `$this->request()` and `$this->ajaxRequest()` (deprecated since v0.3.0) + Use `$this->request->setCallable()` method instead. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/v0.3.0/docs/FunctionAndClassReference.md#testcaserequestmethod-argv-params---callable--null). + +### Others + +* Add documentation for CodeIgniter Rest Server. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.7.0/docs/HowToWriteTests.md#codeigniter-rest-server). +* Compatible with PsySH v0.5.2 + +## v0.6.2 (2015/08/13) + +### Fixed + +* Fix bug that can't test model classes (classes in `application/models` folder) which do not extend `CI_Model` more than once. + +## v0.6.1 (2015/08/12) + +### Changed + +* How to enable Monkey Patching has been changed. `TestCase::$enable_patcher` was removed. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.6.1/docs/HowToWriteTests.md#monkey-patching). + +### Added + +* Monkey Patching on functions. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.6.1/docs/HowToWriteTests.md#patching-functions). +* Monkey Patching on methods in user-defined classes. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.6.1/docs/HowToWriteTests.md#patching-methods-in-user-defined-classes). +* `$this->resetInstance()` for better model testing. See [#40](https://github.com/kenjis/ci-phpunit-test/pull/40). + +### Removed + +* `TestCase::$enable_patcher` (Introduced in v0.5.0) + +### Others + +* Compatible with CodeIgniter 3.0.1 + +## v0.5.0 (2015/07/27) + +### Changed + +* Now ci-phpunit-test replaces `redirect()` function by default. See [#33](https://github.com/kenjis/ci-phpunit-test/pull/33). + +### Added + +* Monkey Patching on `exit()`. ci-phpunit-test could convert `exit()` in your code to Exception on the fly. See [#32](https://github.com/kenjis/ci-phpunit-test/pull/32). +* `$this->request->setCallablePreConstructor()` to inject mocks into your controller constructors. See [#29](https://github.com/kenjis/ci-phpunit-test/pull/29). + +### Fixed + +* Fix bug that PHPUnit debug info of the first test is not outputted. + +### Removed + +* `get_new_instance()` (deprecated since pre v0.1.0) + +## v0.4.0 (2015/07/21) + +### Changed + +* Changed `MY_url_helper.php` as sample. If you use new `MY_url_helper.php`, you must update your tests for `redirect()` using new `$this->assertRedirect()` method. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.4.0/docs/HowToWriteTests.md#redirect) and [#28](https://github.com/kenjis/ci-phpunit-test/pull/28). +* Changed how to test `show_404()` and `show_error()`. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.4.0/docs/HowToWriteTests.md#show_error-and-show_404) and [#28](https://github.com/kenjis/ci-phpunit-test/pull/28). + +### Added + +* `$this->assertResponseCode()` to check response code in controller tests. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/v0.4.0/docs/FunctionAndClassReference.md#testcaseassertresponsecodecode). +* `$this->assertRedirect()` to check if `redirect()` is called in controller tests. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/v0.4.0/docs/FunctionAndClassReference.md#testcaseassertredirecturi-code--null). +* Property `$bc_mode_throw_PHPUnit_Framework_Exception` in `CIPHPUnitTestRequest` class + +### Deprecated + +* Property `$bc_mode_throw_PHPUnit_Framework_Exception` in `CIPHPUnitTestRequest` class + +### Others + +* Improved documentation. See [How to Write Test](https://github.com/kenjis/ci-phpunit-test/blob/v0.4.0/docs/HowToWriteTests.md). + +## v0.3.0 (2015/07/14) + +### Deprecated + +* 4th param `$callable` of `$this->request()` and `$this->ajaxRequest()`. Use `$this->request->setCallable()` method instead. See [Function/Class Reference](https://github.com/kenjis/ci-phpunit-test/blob/v0.3.0/docs/FunctionAndClassReference.md#testcaserequestmethod-argv-params---callable--null). + +### Added + +* `$this->request->setCallable()` See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.3.0/docs/HowToWriteTests.md#request-and-use-mocks). +* You can enable hooks for controller in controller testing. `$this->request->enableHooks()` is added. See [How to Write Tests](https://github.com/kenjis/ci-phpunit-test/blob/v0.3.0/docs/HowToWriteTests.md#controller-with-hooks). + +## v0.2.0 (2015/06/19) + +* Change `MY_url_helper.php` as sample. If you use new `MY_url_helper.php`, you must catch `PHPUnit_Framework_Exception` when you test code using `redirect()`. +* Improve documentation + +## v0.1.1 (2015/06/15) + +* Improve installation. See [Installation](https://github.com/kenjis/ci-phpunit-test#installation). +* Fix bug that Bootstrap outputs 404 page when 404_override +* Fix bug that risky tests occur [#14](https://github.com/kenjis/ci-phpunit-test/issues/14) + +## v0.1.0 (2015/06/12) + +* Initial version +* Compatible with CodeIgniter 3.0.0 diff --git a/application/tests/_ci_phpunit_test/TestSuiteProvider.php b/application/tests/_ci_phpunit_test/TestSuiteProvider.php new file mode 100644 index 00000000..2b64857d --- /dev/null +++ b/application/tests/_ci_phpunit_test/TestSuiteProvider.php @@ -0,0 +1,122 @@ + + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ +/** + * The MIT License + * + * Copyright 2015 Eric VILLARD . + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @package netbeans\phpunit\support + * @author Eric VILLARD + * @copyright (c) 2015 Eric VILLARD + * @license http://opensource.org/licenses/MIT MIT License + */ + +namespace netbeans\phpunit\support; + +use PHPUnit_Framework_TestSuite; +use PHPUnit_Util_Configuration; + +/** + * TestSuiteProvider + * + * @package netbeans\phpunit\support + * @author Eric VILLARD + * @copyright (c) 2015 Eric VILLARD + * @license http://opensource.org/licenses/MIT MIT License + */ +final class TestSuiteProvider +{ + /** + * phpunit configuration file + * + * @var string + */ + private static $file; + + /** + * constructor + */ + private function __construct() {} + + /** + * set the phpunit configuration file + * + * @param string $file the path or filename of the phunit configuration file + */ + public static function setConfigurationFile($file) + { + static::$file = $file; + } + + /** + * get the phpunit test suite instance + * + * @return PHPUnit_Framework_TestSuite returns the phpunit test suite instance + * @throws FileNotFoundException if the file is not found + */ + public static function suite() + { + $file = static::checkConfigurationFile( + static::getConfigurationFile() + ); + + return PHPUnit_Util_Configuration::getInstance($file) + ->getTestSuiteConfiguration(); + } + + /** + * get the phpunit configuration file + * + * @return string + */ + private static function getConfigurationFile() + { + static::$file = isset(static::$file) + ? static::$file + : TESTPATH.'phpunit.xml'; + + return static::$file; + } + + /** + * check the given file + * + * @param string $file file to check + * @return string returns the file if it is valid + * @throws FileNotFoundException if the file is not found + */ + private static function checkConfigurationFile($file) + { + if (!file_exists($file)) { + throw new \RuntimeException("The requested phpunit configuration was not found at $file"); + } + + return $file; + } +} diff --git a/application/tests/_ci_phpunit_test/alias/MonkeyPatch.php b/application/tests/_ci_phpunit_test/alias/MonkeyPatch.php new file mode 100644 index 00000000..0a2ed7fc --- /dev/null +++ b/application/tests/_ci_phpunit_test/alias/MonkeyPatch.php @@ -0,0 +1,5 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Autoloader for ci-phpunit-test +require __DIR__ . '/CIPHPUnitTestAutoloader.php'; +require __DIR__ . '/CIPHPUnitTestFileCache.php'; +$cache = new CIPHPUnitTestFileCache( + __DIR__ . '/tmp/cache/autoload.php' +); +$autoload_dirs = CIPHPUnitTest::getAutoloadDirs(); +$autoloader = new CIPHPUnitTestAutoloader($cache, $autoload_dirs); +spl_autoload_register([$autoloader, 'load']); + +// Register CodeIgniter's tests/mocks/autoloader.php +define('SYSTEM_PATH', BASEPATH); +require TESTPATH .'mocks/autoloader.php'; +spl_autoload_register('autoload'); diff --git a/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestExitException.php b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestExitException.php new file mode 100644 index 00000000..353710b4 --- /dev/null +++ b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestExitException.php @@ -0,0 +1,18 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestExitException extends RuntimeException +{ + public $file; + public $line; + public $class; + public $method; + public $exit_status; +} diff --git a/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestRedirectException.php b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestRedirectException.php new file mode 100644 index 00000000..eaa639b4 --- /dev/null +++ b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestRedirectException.php @@ -0,0 +1,13 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestRedirectException extends RuntimeException +{ +} diff --git a/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestShow404Exception.php b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestShow404Exception.php new file mode 100644 index 00000000..98d0997d --- /dev/null +++ b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestShow404Exception.php @@ -0,0 +1,13 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestShow404Exception extends RuntimeException +{ +} diff --git a/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestShowErrorException.php b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestShowErrorException.php new file mode 100644 index 00000000..8aad5f96 --- /dev/null +++ b/application/tests/_ci_phpunit_test/exceptions/CIPHPUnitTestShowErrorException.php @@ -0,0 +1,13 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class CIPHPUnitTestShowErrorException extends RuntimeException +{ +} diff --git a/application/tests/_ci_phpunit_test/functions.php b/application/tests/_ci_phpunit_test/functions.php new file mode 100644 index 00000000..f44fb2ad --- /dev/null +++ b/application/tests/_ci_phpunit_test/functions.php @@ -0,0 +1,99 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * Inject instance to load_class() function + * + * @param string $classname + * @param object $instance + */ +function load_class_instance($classname, $instance) +{ + load_class($classname, '', NULL, FALSE, $instance); +} + +/** + * Reset CodeIgniter instance + */ +function reset_instance() +{ + // Reset loaded classes + load_class('', '', NULL, TRUE); + is_loaded('', TRUE); + + // Reset config functions + reset_config(); + + // Close db connection + $CI =& get_instance(); + if (isset($CI->db)) + { + if ( + $CI->db->dsn !== 'sqlite::memory:' + && $CI->db->database !== ':memory:' + ) + { + $CI->db->close(); + $CI->db = null; + } + else + { + // Don't close if SQLite in-memory database + // If we close it, all tables and stored data will be gone + load_class_instance('db', $CI->db); + } + } + + // Load core classes + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + $UNI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); +// $URI =& load_class('Utf8', 'core'); +// CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + $RTR =& load_class('Router', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + + CIPHPUnitTest::loadLoader(); + + // Remove CodeIgniter instance + $CI = new CIPHPUnitTestNullCodeIgniter(); +} + +/** + * Set return value of is_cli() function + * + * @param bool $return + */ +function set_is_cli($return) +{ + is_cli($return); +} + +/** + * Reset config functions + */ +function reset_config() +{ + get_config([], TRUE); + config_item(NULL, TRUE); +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Exception/ExitException.php b/application/tests/_ci_phpunit_test/patcher/2.x/Exception/ExitException.php new file mode 100644 index 00000000..8d523a74 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Exception/ExitException.php @@ -0,0 +1,22 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Exception; + +use RuntimeException; + +class ExitException extends RuntimeException +{ + public $file; + public $line; + public $class; + public $method; + public $exit_status; +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/MonkeyPatchManager.php b/application/tests/_ci_phpunit_test/patcher/2.x/MonkeyPatchManager.php new file mode 100644 index 00000000..e54fd845 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/MonkeyPatchManager.php @@ -0,0 +1,331 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch; + +use LogicException; +use RuntimeException; +use PhpParser\ParserFactory; +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +class MonkeyPatchManager +{ + public static $debug = false; + + private static $php_parser = ParserFactory::PREFER_PHP5; + + /** + * The path to the log file if `$debug` is true. + * Will be set in {@link MonkeyPatchManager::setDebug}. + * @var string|null */ + public static $log_file = null; + + private static $load_patchers = false; + private static $exit_exception_classname = + 'Kenjis\MonkeyPatch\Exception\ExitException'; + /** + * @var array list of patcher classname + */ + private static $patcher_list = [ + 'ExitPatcher', + 'FunctionPatcher', + 'MethodPatcher', + 'ConstantPatcher', + ]; + + public static function log($message) + { + if (! self::$debug) + { + return; + } + + $time = date('Y-m-d H:i:s'); + list($usec, $sec) = explode(' ', microtime()); + $usec = substr($usec, 1); + $log = "[$time $usec] $message\n"; + file_put_contents(self::$log_file, $log, FILE_APPEND); + } + + public static function setExitExceptionClassname($name) + { + self::$exit_exception_classname = $name; + } + + public static function getExitExceptionClassname() + { + return self::$exit_exception_classname; + } + + public static function getPhpParser() + { + return self::$php_parser; + } + + protected static function setDebug(array $config) + { + if (isset($config['debug'])) + { + self::$debug = $config['debug']; + } + if (isset($config['log_file'])) + { + self::$log_file = $config['log_file']; + } + if (is_null(self::$log_file)) + { + self::$log_file = __DIR__ . '/debug.log'; + } + } + + protected static function setDir(array $config) + { + if (isset($config['root_dir'])) + { + Cache::setProjectRootDir($config['root_dir']); + } + else + { + // APPPATH is constant in CodeIgniter + Cache::setProjectRootDir(APPPATH . '../'); + } + + if (! isset($config['cache_dir'])) + { + throw new LogicException('You have to set "cache_dir"'); + } + self::setCacheDir($config['cache_dir']); + } + + protected static function setPaths(array $config) + { + if (! isset($config['include_paths'])) + { + throw new LogicException('You have to set "include_paths"'); + } + self::setIncludePaths($config['include_paths']); + + if (isset($config['exclude_paths'])) + { + self::setExcludePaths($config['exclude_paths']); + } + } + + public static function init(array $config) + { + self::setDebug($config); + + if (isset($config['php_parser'])) + { + self::$php_parser = constant('PhpParser\ParserFactory::'.$config['php_parser']); + } + + self::setDir($config); + self::setPaths($config); + + Cache::createTmpListDir(); + + if (isset($config['patcher_list'])) + { + self::setPatcherList($config['patcher_list']); + } + self::checkPatcherListUpdate(); + self::checkPathsUpdate(); + + self::loadPatchers(); + + self::addTmpFunctionBlacklist(); + + if (isset($config['functions_to_patch'])) + { + FunctionPatcher::addWhitelists($config['functions_to_patch']); + } + self::checkFunctionWhitelistUpdate(); + FunctionPatcher::lockFunctionList(); + + if (isset($config['exit_exception_classname'])) + { + self::setExitExceptionClassname($config['exit_exception_classname']); + } + + // Register include stream wrapper for monkey patching + self::wrap(); + } + + protected static function checkPathsUpdate() + { + $cached = Cache::getTmpIncludePaths(); + $current = PathChecker::getIncludePaths(); + + // Updated? + if ($cached !== $current) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpIncludePaths($current); + } + + $cached = Cache::getTmpExcludePaths(); + $current = PathChecker::getExcludePaths(); + + // Updated? + if ($cached !== $current) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpExcludePaths($current); + } + } + + protected static function checkPatcherListUpdate() + { + $cached = Cache::getTmpPatcherList(); + + // Updated? + if ($cached !== self::$patcher_list) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpPatcherList(self::$patcher_list); + } + } + + protected static function checkFunctionWhitelistUpdate() + { + $cached = Cache::getTmpFunctionWhitelist(); + $current = FunctionPatcher::getFunctionWhitelist(); + + // Updated? + if ($cached !== $current) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpFunctionWhitelist($current); + } + } + + protected static function addTmpFunctionBlacklist() + { + $list = file(Cache::getTmpFunctionBlacklistFile()); + foreach ($list as $function) + { + FunctionPatcher::addBlacklist(trim($function)); + } + } + + public static function isEnabled($patcher) + { + return in_array($patcher, self::$patcher_list); + } + + public static function setPatcherList(array $list) + { + if (self::$load_patchers) + { + throw new LogicException("Can't change patcher list after initialisation"); + } + + self::$patcher_list = $list; + } + + public static function setCacheDir($dir) + { + Cache::setCacheDir($dir); + } + + public static function setIncludePaths(array $dir_list) + { + PathChecker::setIncludePaths($dir_list); + } + + public static function setExcludePaths(array $dir_list) + { + PathChecker::setExcludePaths($dir_list); + } + + public static function wrap() + { + IncludeStream::wrap(); + } + + public static function unwrap() + { + IncludeStream::unwrap(); + } + + /** + * @param string $path original source file path + * @return resource + * @throws LogicException + */ + public static function patch($path) + { + if (! is_readable($path)) + { + throw new LogicException("Can't read '$path'"); + } + + // Check cache file + if ($cache_file = Cache::getValidSrcCachePath($path)) + { + self::log('cache_hit: ' . $path); + return fopen($cache_file, 'r'); + } + + self::log('cache_miss: ' . $path); + $source = file_get_contents($path); + + list($new_source, $patched) = self::execPatchers($source); + + // Write to cache file + self::log('write_cache: ' . $path); + Cache::writeSrcCacheFile($path, $new_source); + + $resource = fopen('php://memory', 'rb+'); + fwrite($resource, $new_source); + rewind($resource); + return $resource; + } + + protected static function loadPatchers() + { + if (self::$load_patchers) + { + return; + } + + require __DIR__ . '/Patcher/AbstractPatcher.php'; + require __DIR__ . '/Patcher/Backtrace.php'; + + foreach (self::$patcher_list as $classname) + { + require __DIR__ . '/Patcher/' . $classname . '.php'; + } + + self::$load_patchers = true; + } + + protected static function execPatchers($source) + { + $patched = false; + foreach (self::$patcher_list as $classname) + { + $classname = 'Kenjis\MonkeyPatch\Patcher\\' . $classname; + $patcher = new $classname; + list($source, $patched_this) = $patcher->patch($source); + $patched = $patched || $patched_this; + } + + return [ + $source, + $patched, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/AbstractPatcher.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/AbstractPatcher.php new file mode 100644 index 00000000..75acca42 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/AbstractPatcher.php @@ -0,0 +1,57 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +use PhpParser\ParserFactory; +use PhpParser\Lexer; +use PhpParser\NodeTraverser; +use Kenjis\MonkeyPatch\MonkeyPatchManager; + +abstract class AbstractPatcher +{ + protected $node_visitor; + + public static $replacement; + + public function patch($source) + { + $patched = false; + static::$replacement = []; + + $parser = (new ParserFactory) + ->create( + MonkeyPatchManager::getPhpParser(), + new Lexer( + ['usedAttributes' => ['startTokenPos', 'endTokenPos']] + ) + ); + $traverser = new NodeTraverser; + $traverser->addVisitor($this->node_visitor); + + $ast_orig = $parser->parse($source); + $traverser->traverse($ast_orig); + + if (static::$replacement !== []) + { + $patched = true; + $new_source = static::generateNewSource($source); + } + else + { + $new_source = $source; + } + + return [ + $new_source, + $patched, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/Backtrace.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/Backtrace.php new file mode 100644 index 00000000..547c6ced --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/Backtrace.php @@ -0,0 +1,79 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +use LogicException; + +class Backtrace +{ + private static $map = [ + 'FunctionPatcher' => 1, + 'MethodPatcher' => 0, + 'ConstantPatcher' => 0, + ]; + + public static function getInfo($patcher, $backtrace) + { + if (! isset(self::$map[$patcher])) + { + throw new LogicException("No such a patcher: $patcher"); + } + $offset = self::$map[$patcher]; + + // Supports PHP7 optimization + if (version_compare(PHP_VERSION, '6.0.0', '>')) + { + if ($backtrace[$offset]['function'] === '__callStatic') + { + $offset--; + } + } + + $file = isset($backtrace[$offset]['file']) + ? $backtrace[$offset]['file'] : null; + $line = isset($backtrace[$offset]['line']) + ? $backtrace[$offset]['line'] : null; + + if (isset($backtrace[$offset+2])) + { + $class = isset($backtrace[$offset+2]['class']) + ? $backtrace[$offset+2]['class'] + : null; + $function = $backtrace[$offset+2]['function']; + } + else + { + $class = null; + $function = null; + } + + if (isset($class)) + { + $method = $function; + $class_method = $class . '::' . $function; + $function = null; + } + else + { + $method = null; + $class_method = null; + } + + return [ + 'file' => $file, + 'line' => $line, + 'class' => $class, + 'method' => $method, + 'class_method' => $class_method, + 'function' => $function, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher.php new file mode 100644 index 00000000..44a75ca2 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher.php @@ -0,0 +1,100 @@ + + * @license MIT License + * @copyright 2016 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/ConstantPatcher/NodeVisitor.php'; +require __DIR__ . '/ConstantPatcher/Proxy.php'; + +use LogicException; + +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher\NodeVisitor; + +class ConstantPatcher extends AbstractPatcher +{ + /** + * @var special constant names which we don't patch + */ + private static $blacklist = [ + 'true', + 'false', + 'null', + ]; + + public static $replacement; + + public function __construct() + { + $this->node_visitor = new NodeVisitor(); + } + + /** + * @param string $name constant name + * @return boolean + */ + public static function isBlacklisted($name) + { + if (in_array(strtolower($name), self::$blacklist)) + { + return true; + } + + return false; + } + + protected static function generateNewSource($source) + { + $tokens = token_get_all($source); + $new_source = ''; + $i = -1; + + ksort(self::$replacement); + reset(self::$replacement); + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + + foreach ($tokens as $token) + { + $i++; + + if (is_string($token)) + { + $new_source .= $token; + } + elseif ($i == $replacement['key']) + { + $new_source .= $replacement['value']; + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + } + else + { + $new_source .= $token[1]; + } + } + + if ($replacement !== false) + { + throw new LogicException('Replacement data still remain'); + } + + return $new_source; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher/NodeVisitor.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher/NodeVisitor.php new file mode 100644 index 00000000..d6280206 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher/NodeVisitor.php @@ -0,0 +1,126 @@ + + * @license MIT License + * @copyright 2016 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\ConstantPatcher; + +use PhpParser\Node; +use PhpParser\Node\Expr\ConstFetch; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; +use PhpParser\NodeVisitorAbstract; + +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher; + +class NodeVisitor extends NodeVisitorAbstract +{ + private $disable_const_rewrite_level = 0; + + public function enterNode(Node $node) + { + $callback = [$this, 'before' . ucfirst($node->getType())]; + if (is_callable($callback)) { + call_user_func_array($callback, [$node]); + } + } + + public function leaveNode(Node $node) + { + if (! ($node instanceof ConstFetch)) + { + $callback = [$this, 'rewrite' . ucfirst($node->getType())]; + if (is_callable($callback)) { + call_user_func_array($callback, [$node]); + } + + return; + } + + if ($this->disable_const_rewrite_level > 0) + { + return; + } + + if (! ($node->name instanceof Name)) + { + return; + } + + if (! $node->name->isUnqualified()) + { + return; + } + + if (! ConstantPatcher::isBlacklisted((string) $node->name)) + { + $replacement = new FullyQualified(array()); + $replacement->set( + '\__ConstProxy__::get(\'' . (string) $node->name . '\')' + ); + + $pos = $node->getAttribute('startTokenPos'); + ConstantPatcher::$replacement[$pos] = + '\__ConstProxy__::get(\'' . (string) $node->name .'\')'; + + $node->name = $replacement; + } + } + + /** + * The following logic is from: + * + * Thank you. + * + * The MIT License (MIT) + * Copyright (c) 2016 Badoo Development + */ + // Cannot rewrite constants that are used as default values in function arguments + public function beforeParam() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteParam() + { + $this->disable_const_rewrite_level--; + } + + // Cannot rewrite constants that are used as default values in constant declarations + public function beforeConst() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteConst() + { + $this->disable_const_rewrite_level--; + } + + // Cannot rewrite constants that are used as default values in property declarations + public function beforeStmt_PropertyProperty() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteStmt_PropertyProperty() + { + $this->disable_const_rewrite_level--; + } + + // Cannot rewrite constants that are used as default values in static variable declarations + public function beforeStmt_StaticVar() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteStmt_StaticVar() + { + $this->disable_const_rewrite_level--; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher/Proxy.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher/Proxy.php new file mode 100644 index 00000000..5ae7d3dd --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ConstantPatcher/Proxy.php @@ -0,0 +1,131 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\ConstantPatcher; + +class_alias('Kenjis\MonkeyPatch\Patcher\ConstantPatcher\Proxy', '__ConstProxy__'); + +use LogicException; +use ReflectionConstant; +use ReflectionException; + +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher; +use Kenjis\MonkeyPatch\Patcher\Backtrace; +use Kenjis\MonkeyPatch\MonkeyPatchManager; +use Kenjis\MonkeyPatch\Cache; +use Kenjis\MonkeyPatch\InvocationVerifier; + +class Proxy +{ + private static $patches = []; + private static $patches_to_apply = []; + + /** + * Set a constant patch + * + * @param string $constant constant name + * @param mixed $value value + * @param string $class_method class::method to apply this patch + * + * @throws LogicException + */ + public static function patch($constant, $value, $class_method = null) + { + self::$patches[$constant] = $value; + self::$patches_to_apply[$constant] = strtolower($class_method); + } + + /** + * Clear all patches and invocation data + */ + public static function reset() + { + self::$patches = []; + self::$patches_to_apply = []; + } + + protected static function logInvocation($constant) + { + if (MonkeyPatchManager::$debug) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('ConstantPatcher', $trace); + + $file = $info['file']; + $line = $info['line']; + $method = isset($info['class_method']) ? $info['class_method'] : $info['function']; + + MonkeyPatchManager::log( + 'invoke_const: ' . $constant . ') on line ' . $line . ' in ' . $file . ' by ' . $method . '()' + ); + } + } + + protected static function checkCalledMethod($constant) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('ConstantPatcher', $trace); + + $class = strtolower($info['class']); + $class_method = strtolower($info['class_method']); + + // Patches the constants only in the class + if (strpos(self::$patches_to_apply[$constant], '::') === false) + { + if (self::$patches_to_apply[$constant] !== $class) + { + return false; + } + return true; + } + //Patches the constants only in the class method + else + { + if (self::$patches_to_apply[$constant] !== $class_method) + { + return false; + } + return true; + } + } + + /** + * Get patched constant value + * + * @param string $constant + * @return mixed + */ + public static function get($constant) + { + self::logInvocation($constant); + + if (! empty(self::$patches_to_apply[$constant])) + { + if (! self::checkCalledMethod($constant)) + { + MonkeyPatchManager::log( + 'invoke_const: ' . $constant . ' not patched (out of scope)' + ); + return constant($constant); + } + } + + if (array_key_exists($constant, self::$patches)) + { + MonkeyPatchManager::log('invoke_const: ' . $constant . ' patched'); + return self::$patches[$constant]; + } + + MonkeyPatchManager::log( + 'invoke_const: ' . $constant . ' not patched (no patch)' + ); + return constant($constant); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ExitPatcher.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ExitPatcher.php new file mode 100644 index 00000000..83aae345 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/ExitPatcher.php @@ -0,0 +1,54 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/../Exception/ExitException.php'; + +class ExitPatcher +{ + public static function patch($source) + { + $tokens = token_get_all($source); + + $patched = false; + $new_source = ''; + $i = -1; + + foreach ($tokens as $token) { + $i++; + if (is_string($token)) + { + $new_source .= $token; + } + elseif ($token[0] === T_EXIT) + { + if ($tokens[$i+1] === ';') + { + $new_source .= 'exit__()'; + } + else + { + $new_source .= 'exit__'; + } + $patched = true; + } + else + { + $new_source .= $token[1]; + } + } + + return [ + $new_source, + $patched, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher.php new file mode 100644 index 00000000..b05ab5bb --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher.php @@ -0,0 +1,209 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/FunctionPatcher/NodeVisitor.php'; +require __DIR__ . '/FunctionPatcher/Proxy.php'; + +use LogicException; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher\NodeVisitor; + +class FunctionPatcher extends AbstractPatcher +{ + private static $lock_function_list = false; + + /** + * @var array list of function names (in lower case) which you patch + */ + private static $whitelist = [ + 'mt_rand', + 'rand', + 'uniqid', + 'hash_hmac', + 'md5', + 'sha1', + 'hash', + 'time', + 'microtime', + 'date', + 'function_exists', + 'header', + 'setcookie', + // Functions that have param called by reference + // Need to prepare method in FunctionPatcher\Proxy class + 'openssl_random_pseudo_bytes', + ]; + + /** + * @var array list of function names (in lower case) which can't be patched + */ + private static $blacklist = [ + // Segmentation fault + 'call_user_func_array', + 'exit__', + // Error: Only variables should be assigned by reference + 'get_instance', + 'get_config', + 'load_class', + 'get_mimes', + '_get_validation_object', + // has reference param + 'preg_replace', + 'preg_match', + 'preg_match_all', + 'array_unshift', + 'array_shift', + 'sscanf', + 'ksort', + 'krsort', + 'str_ireplace', + 'str_replace', + 'is_callable', + 'flock', + 'end', + 'idn_to_ascii', + // Special functions for ci-phpunit-test + 'show_404', + 'show_error', + 'redirect', + ]; + + public static $replacement; + + public function __construct() + { + $this->node_visitor = new NodeVisitor(); + } + + protected static function checkLock($error_msg) + { + if (self::$lock_function_list) + { + throw new LogicException($error_msg); + } + } + + public static function addWhitelists(array $function_list) + { + self::checkLock("You can't add to whitelist after initialization"); + + foreach ($function_list as $function_name) + { + self::$whitelist[] = strtolower($function_name); + } + } + + /** + * @return array + */ + public static function getFunctionWhitelist() + { + return self::$whitelist; + } + + public static function addBlacklist($function_name) + { + self::checkLock("You can't add to blacklist after initialization"); + + self::$blacklist[] = strtolower($function_name); + } + + public static function removeBlacklist($function_name) + { + self::checkLock("You can't remove from blacklist after initialization"); + + $key = array_search(strtolower($function_name), self::$blacklist); + array_splice(self::$blacklist, $key, 1); + } + + public static function lockFunctionList() + { + self::$lock_function_list = true; + } + + /** + * @param string $name function name + * @return boolean + */ + public static function isWhitelisted($name) + { + if (in_array(strtolower($name), self::$whitelist)) + { + return true; + } + + return false; + } + + /** + * @param string $name function name + * @return boolean + */ + public static function isBlacklisted($name) + { + if (in_array(strtolower($name), self::$blacklist)) + { + return true; + } + + return false; + } + + protected static function generateNewSource($source) + { + $tokens = token_get_all($source); + $new_source = ''; + $i = -1; + + ksort(self::$replacement); + reset(self::$replacement); + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + + foreach ($tokens as $token) + { + $i++; + + if (is_string($token)) + { + $new_source .= $token; + } + elseif ($i == $replacement['key']) + { + $new_source .= $replacement['value']; + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + } + else + { + $new_source .= $token[1]; + } + } + + if ($replacement !== false) + { + throw new LogicException('Replacement data still remain'); + } + + return $new_source; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher/NodeVisitor.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher/NodeVisitor.php new file mode 100644 index 00000000..b97bfe9b --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher/NodeVisitor.php @@ -0,0 +1,70 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * Copyright for Original Code + * + * @author Adrian Philipp + * @copyright 2014 Adrian Philipp + * @license https://github.com/adri/monkey/blob/dfbb93ae09a2c0712f43eab7ced76d3f49989fbe/LICENSE + * @link https://github.com/adri/monkey + * + * @see https://github.com/adri/monkey/blob/dfbb93ae09a2c0712f43eab7ced76d3f49989fbe/testTest.php + */ + +namespace Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +use ReflectionFunction; +use ReflectionException; + +use PhpParser\Node; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; +use PhpParser\NodeVisitorAbstract; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +class NodeVisitor extends NodeVisitorAbstract +{ + public function leaveNode(Node $node) + { + if (! ($node instanceof FuncCall)) + { + return; + } + + if (! ($node->name instanceof Name)) + { + return; + } + + if (! $node->name->isUnqualified()) + { + return; + } + + if ( + FunctionPatcher::isWhitelisted((string) $node->name) + && ! FunctionPatcher::isBlacklisted((string) $node->name) + ) { + $replacement = new FullyQualified(array()); + $replacement->set( + '\__FuncProxy__::' . (string) $node->name + ); + + $pos = $node->getAttribute('startTokenPos'); + FunctionPatcher::$replacement[$pos] = + '\__FuncProxy__::' . (string) $node->name; + + $node->name = $replacement; + } + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher/Proxy.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher/Proxy.php new file mode 100644 index 00000000..2134e3a3 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/FunctionPatcher/Proxy.php @@ -0,0 +1,282 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +class_alias('Kenjis\MonkeyPatch\Patcher\FunctionPatcher\Proxy', '__FuncProxy__'); + +use LogicException; +use ReflectionFunction; +use ReflectionException; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher; +use Kenjis\MonkeyPatch\Patcher\Backtrace; +use Kenjis\MonkeyPatch\MonkeyPatchManager; +use Kenjis\MonkeyPatch\Cache; +use Kenjis\MonkeyPatch\InvocationVerifier; + +class Proxy +{ + private static $patches = []; + private static $patches_to_apply = []; + private static $expected_invocations = []; + private static $invocations = []; + + /** + * Set a function patch + * + * This method has '__' suffix, because if it matches real function name, + * '__callStatic()' catch it. + * + * @param string $function function name + * @param mixed $return_value return value or callable + * @param string $class_name class::method to apply this patch + * + * @throws LogicException + */ + public static function patch__($function, $return_value, $class_method = null) + { + $function = strtolower($function); + + if (FunctionPatcher::isBlacklisted($function)) + { + $msg = "Can't patch on '$function'. It is in blacklist."; + self::outputMessage($msg); + throw new LogicException($msg); + } + if (! FunctionPatcher::isWhitelisted($function)) + { + $msg = "Can't patch on '$function'. It is not in whitelist. If you want to patch it, please add it to 'functions_to_patch' in 'tests/Bootstrap.php'. But note that there are some limitations. See for details."; + self::outputMessage($msg); + throw new LogicException($msg); + } + + self::$patches[$function] = $return_value; + self::$patches_to_apply[$function] = strtolower($class_method); + } + + /** + * Clear all patches and invocation data + * + * This method has '__' suffix, because if it matches real function name, + * '__callStatic()' catch it. + */ + public static function reset__() + { + self::$patches = []; + self::$patches_to_apply = []; + self::$expected_invocations = []; + self::$invocations = []; + } + + public static function setExpectedInvocations($function, $times, $params) + { + self::$expected_invocations[strtolower($function)][] = [$params, $times]; + } + + public static function verifyInvocations() + { + InvocationVerifier::verify(self::$expected_invocations, self::$invocations); + } + + protected static function logInvocation($function, $arguments) + { + if (MonkeyPatchManager::$debug) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('FunctionPatcher', $trace); + + $file = $info['file']; + $line = $info['line']; + $method = isset($info['class_method']) ? $info['class_method'] : $info['function']; + + $log_args = function () use ($arguments) { + $output = ''; + foreach ($arguments as $arg) { + $output .= var_export($arg, true) . ', '; + } + $output = rtrim($output, ', '); + return $output; + }; + MonkeyPatchManager::log( + 'invoke_func: ' . $function . '(' . $log_args() . ') on line ' . $line . ' in ' . $file . ' by ' . $method . '()' + ); + } + } + + protected static function checkCalledMethod($function) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('FunctionPatcher', $trace); + + $class = strtolower($info['class']); + $class_method = strtolower($info['class_method']); + + // Patches the functions only in the class + if (strpos(self::$patches_to_apply[$function], '::') === false) + { + if (self::$patches_to_apply[$function] !== $class) + { + return false; + } + return true; + } + // Patches the functions only in the class method + else + { + if (self::$patches_to_apply[$function] !== $class_method) + { + return false; + } + return true; + } + } + + public static function __callStatic($function, array $arguments) + { + $function = strtolower($function); + + self::logInvocation($function, $arguments); + self::$invocations[$function][] = $arguments; + + if (isset(self::$patches_to_apply[$function])) + { + if (! self::checkCalledMethod($function)) + { + MonkeyPatchManager::log( + 'invoke_func: ' . $function . '() not patched (out of scope)' + ); + self::checkPassedByReference($function); + return call_user_func_array($function, $arguments); + } + } + + if (array_key_exists($function, self::$patches)) + { + MonkeyPatchManager::log('invoke_func: ' . $function . '() patched'); + + if (is_callable(self::$patches[$function])) + { + $callable = self::$patches[$function]; + + $return = call_user_func_array($callable, $arguments); + if ($return !== __GO_TO_ORIG__) + { + return $return; + } + return call_user_func_array($function, $arguments); + } + + return self::$patches[$function]; + } + + MonkeyPatchManager::log( + 'invoke_func: ' . $function . '() not patched (no patch)' + ); + self::checkPassedByReference($function); + return call_user_func_array($function, $arguments); + } + + protected static function checkPassedByReference($function) + { + $ref_func = new ReflectionFunction($function); + + foreach ($ref_func->getParameters() as $param) + { + if ($param->isPassedByReference()) + { + // Add tmp blacklist + Cache::appendTmpFunctionBlacklist($function); + + // Remove cache file + $backtrace = debug_backtrace(); + $info = Backtrace::getInfo('FunctionPatcher', $backtrace); + $orig_file = $info['file']; + $cache = Cache::removeSrcCacheFile($orig_file); + + $pr_msg = ''; + if (self::isInternalFunction($function)) + { + $pr_msg = "Please send Pull Request to add function '$function' to default config.\n"; + } + + $tmp_blacklist_file = Cache::getTmpFunctionBlacklistFile(); + $msg = + "\n" + . "Can't patch on function '$function'.\n" + . "It has param(s) passed by reference.\n" + . "Added it temporary blacklist file '$tmp_blacklist_file'.\n" + . "And removed cache file '$cache'.\n" + . "$pr_msg" + . "\nPlease run phpunit again."; + + self::outputMessage($msg); + throw new LogicException($msg); + } + } + } + + protected static function outputMessage($msg) + { + $red_begin = "\033[41m\033[37m"; + $red_end = "\033[0m"; + + $msg = str_replace( + ['', ''], [$red_begin, $red_end], $msg + ); + echo $msg . "\n"; + } + + /** + * @param string $name function name + * @return bool + */ + protected static function isInternalFunction($name) + { + try { + $ref_func = new ReflectionFunction($name); + return $ref_func->isInternal(); + } catch (ReflectionException $e) { + // ReflectionException: Function xxx() does not exist + return false; + } + } + + public static function openssl_random_pseudo_bytes( + $length, &$crypto_strong = null + ) + { + $function = 'openssl_random_pseudo_bytes'; + $arguments = [$length, $crypto_strong]; + self::logInvocation($function, $arguments); + self::$invocations[$function][] = $arguments; + + if ($crypto_strong === null) + { + $crypto_strong = true; + } + + if (array_key_exists($function, self::$patches)) + { + if (is_callable(self::$patches[$function])) + { + $callable = self::$patches[$function]; + return call_user_func_array( + $callable, + [$length, &$crypto_strong] + ); + } + + return self::$patches[$function]; + } + + return openssl_random_pseudo_bytes($length, $crypto_strong); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher.php new file mode 100644 index 00000000..3dbbc1e1 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher.php @@ -0,0 +1,125 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/MethodPatcher/NodeVisitor.php'; +require __DIR__ . '/MethodPatcher/PatchManager.php'; + +use LogicException; + +use Kenjis\MonkeyPatch\Patcher\MethodPatcher\NodeVisitor; + +class MethodPatcher extends AbstractPatcher +{ + const CODE = <<<'EOL' +if (($__ret__ = \__PatchManager__::getReturn(__CLASS__, __FUNCTION__, func_get_args())) !== __GO_TO_ORIG__) return $__ret__; +EOL; + const CODENORET = <<<'EOL' +if (($__ret__ = \__PatchManager__::getReturn(__CLASS__, __FUNCTION__, func_get_args())) !== __GO_TO_ORIG__) return; +EOL; + + public static $replacement; + + public function __construct() + { + $this->node_visitor = new NodeVisitor(); + } + + protected static function generateNewSource($source) + { + $tokens = token_get_all($source); + $new_source = ''; + $i = -1; + + ksort(self::$replacement); + reset(self::$replacement); + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + + $start_method = false; + + foreach ($tokens as $key => $token) + { + $i++; + + if ($i == $replacement['key']) + { + $start_method = true; + } + + if (is_string($token)) + { + if ($start_method && $token === '{') + { + if(self::isVoidFunction($tokens, $key)){ + $new_source .= '{ ' . self::CODENORET; + } + else{ + $new_source .= '{ ' . self::CODE; + } + $start_method = false; + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + } + else + { + $new_source .= $token; + } + } + else + { + $new_source .= $token[1]; + } + } + + return $new_source; + } + + /** + * Checks if a function has a void return type + * + * @param $tokens + * @param $key + * @return bool + */ + protected static function isVoidFunction($tokens, $key){ + if($key - 1 <= 0){ + return false; + } + $token = $tokens[$key - 1]; + if(is_array($token)){ + $token = $token[1]; + } + //Loop backwards though the start of the function block till you either find "void" or the end of the + //parameters declaration. + while($token !== ")"){ + if(strpos($token, "void") !== false){ + return true; + } + $token = $tokens[$key - 1]; + if(is_array($token)){ + $token = $token[1]; + } + $key--; + } + return false; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher/NodeVisitor.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher/NodeVisitor.php new file mode 100644 index 00000000..46998b6b --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher/NodeVisitor.php @@ -0,0 +1,31 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\MethodPatcher; + +use PhpParser\Node; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\NodeVisitorAbstract; + +use Kenjis\MonkeyPatch\Patcher\MethodPatcher; + +class NodeVisitor extends NodeVisitorAbstract +{ + public function leaveNode(Node $node) + { + if (! ($node instanceof ClassMethod)) + { + return; + } + + $pos = $node->getAttribute('startTokenPos'); + MethodPatcher::$replacement[$pos] = true; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher/PatchManager.php b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher/PatchManager.php new file mode 100644 index 00000000..3b8b5afc --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/2.x/Patcher/MethodPatcher/PatchManager.php @@ -0,0 +1,114 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\MethodPatcher; + +class_alias('Kenjis\MonkeyPatch\Patcher\MethodPatcher\PatchManager', '__PatchManager__'); + +use Kenjis\MonkeyPatch\MonkeyPatchManager; +use Kenjis\MonkeyPatch\Patcher\Backtrace; +use Kenjis\MonkeyPatch\InvocationVerifier; + +class PatchManager +{ + private static $patches = []; + private static $expected_invocations = []; + private static $invocations = []; + + /** + * Set a method patch + * + * @param string $class + * @param array $params [method_name => return_value] + */ + public static function set($class, $params) + { + self::$patches[$class] = $params; + } + + /** + * Clear all patches and invocation data + */ + public static function clear() + { + self::$patches = []; + self::$expected_invocations = []; + self::$invocations = []; + } + + public static function getReturn($class, $method, $params) + { + if (MonkeyPatchManager::$debug) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('MethodPatcher', $trace); + + $file = $info['file']; + $line = $info['line']; + + if (isset($info['class_method'])) + { + $called_method = $info['class_method']; + } + elseif (isset($info['function'])) + { + $called_method = $info['function']; + } + else + { + $called_method = 'n/a'; + } + + $log_args = function () use ($params) { + $output = ''; + foreach ($params as $arg) { + $output .= var_export($arg, true) . ', '; + } + $output = rtrim($output, ', '); + return $output; + }; + MonkeyPatchManager::log( + 'invoke_method: ' . $class.'::'.$method . '(' . $log_args() . ') on line ' . $line . ' in ' . $file . ' by ' . $called_method + ); +// var_dump($trace); exit; + } + + self::$invocations[$class.'::'.$method][] = $params; + + if ( + isset(self::$patches[$class]) + && array_key_exists($method, self::$patches[$class]) + ) + { + $patch = self::$patches[$class][$method]; + } + else + { + return __GO_TO_ORIG__; + } + + if (is_callable($patch)) + { + return call_user_func_array($patch, $params); + } else { + return $patch; + } + } + + public static function setExpectedInvocations($class_method, $times, $params) + { + self::$expected_invocations[$class_method][] = [$params, $times]; + } + + public static function verifyInvocations() + { + InvocationVerifier::verify(self::$expected_invocations, self::$invocations); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Exception/ExitException.php b/application/tests/_ci_phpunit_test/patcher/3.x/Exception/ExitException.php new file mode 100644 index 00000000..8d523a74 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Exception/ExitException.php @@ -0,0 +1,22 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Exception; + +use RuntimeException; + +class ExitException extends RuntimeException +{ + public $file; + public $line; + public $class; + public $method; + public $exit_status; +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/MonkeyPatchManager.php b/application/tests/_ci_phpunit_test/patcher/3.x/MonkeyPatchManager.php new file mode 100644 index 00000000..e54fd845 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/MonkeyPatchManager.php @@ -0,0 +1,331 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch; + +use LogicException; +use RuntimeException; +use PhpParser\ParserFactory; +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +class MonkeyPatchManager +{ + public static $debug = false; + + private static $php_parser = ParserFactory::PREFER_PHP5; + + /** + * The path to the log file if `$debug` is true. + * Will be set in {@link MonkeyPatchManager::setDebug}. + * @var string|null */ + public static $log_file = null; + + private static $load_patchers = false; + private static $exit_exception_classname = + 'Kenjis\MonkeyPatch\Exception\ExitException'; + /** + * @var array list of patcher classname + */ + private static $patcher_list = [ + 'ExitPatcher', + 'FunctionPatcher', + 'MethodPatcher', + 'ConstantPatcher', + ]; + + public static function log($message) + { + if (! self::$debug) + { + return; + } + + $time = date('Y-m-d H:i:s'); + list($usec, $sec) = explode(' ', microtime()); + $usec = substr($usec, 1); + $log = "[$time $usec] $message\n"; + file_put_contents(self::$log_file, $log, FILE_APPEND); + } + + public static function setExitExceptionClassname($name) + { + self::$exit_exception_classname = $name; + } + + public static function getExitExceptionClassname() + { + return self::$exit_exception_classname; + } + + public static function getPhpParser() + { + return self::$php_parser; + } + + protected static function setDebug(array $config) + { + if (isset($config['debug'])) + { + self::$debug = $config['debug']; + } + if (isset($config['log_file'])) + { + self::$log_file = $config['log_file']; + } + if (is_null(self::$log_file)) + { + self::$log_file = __DIR__ . '/debug.log'; + } + } + + protected static function setDir(array $config) + { + if (isset($config['root_dir'])) + { + Cache::setProjectRootDir($config['root_dir']); + } + else + { + // APPPATH is constant in CodeIgniter + Cache::setProjectRootDir(APPPATH . '../'); + } + + if (! isset($config['cache_dir'])) + { + throw new LogicException('You have to set "cache_dir"'); + } + self::setCacheDir($config['cache_dir']); + } + + protected static function setPaths(array $config) + { + if (! isset($config['include_paths'])) + { + throw new LogicException('You have to set "include_paths"'); + } + self::setIncludePaths($config['include_paths']); + + if (isset($config['exclude_paths'])) + { + self::setExcludePaths($config['exclude_paths']); + } + } + + public static function init(array $config) + { + self::setDebug($config); + + if (isset($config['php_parser'])) + { + self::$php_parser = constant('PhpParser\ParserFactory::'.$config['php_parser']); + } + + self::setDir($config); + self::setPaths($config); + + Cache::createTmpListDir(); + + if (isset($config['patcher_list'])) + { + self::setPatcherList($config['patcher_list']); + } + self::checkPatcherListUpdate(); + self::checkPathsUpdate(); + + self::loadPatchers(); + + self::addTmpFunctionBlacklist(); + + if (isset($config['functions_to_patch'])) + { + FunctionPatcher::addWhitelists($config['functions_to_patch']); + } + self::checkFunctionWhitelistUpdate(); + FunctionPatcher::lockFunctionList(); + + if (isset($config['exit_exception_classname'])) + { + self::setExitExceptionClassname($config['exit_exception_classname']); + } + + // Register include stream wrapper for monkey patching + self::wrap(); + } + + protected static function checkPathsUpdate() + { + $cached = Cache::getTmpIncludePaths(); + $current = PathChecker::getIncludePaths(); + + // Updated? + if ($cached !== $current) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpIncludePaths($current); + } + + $cached = Cache::getTmpExcludePaths(); + $current = PathChecker::getExcludePaths(); + + // Updated? + if ($cached !== $current) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpExcludePaths($current); + } + } + + protected static function checkPatcherListUpdate() + { + $cached = Cache::getTmpPatcherList(); + + // Updated? + if ($cached !== self::$patcher_list) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpPatcherList(self::$patcher_list); + } + } + + protected static function checkFunctionWhitelistUpdate() + { + $cached = Cache::getTmpFunctionWhitelist(); + $current = FunctionPatcher::getFunctionWhitelist(); + + // Updated? + if ($cached !== $current) + { + MonkeyPatchManager::log('clear_src_cache: from ' . __METHOD__); + Cache::clearSrcCache(); + Cache::writeTmpFunctionWhitelist($current); + } + } + + protected static function addTmpFunctionBlacklist() + { + $list = file(Cache::getTmpFunctionBlacklistFile()); + foreach ($list as $function) + { + FunctionPatcher::addBlacklist(trim($function)); + } + } + + public static function isEnabled($patcher) + { + return in_array($patcher, self::$patcher_list); + } + + public static function setPatcherList(array $list) + { + if (self::$load_patchers) + { + throw new LogicException("Can't change patcher list after initialisation"); + } + + self::$patcher_list = $list; + } + + public static function setCacheDir($dir) + { + Cache::setCacheDir($dir); + } + + public static function setIncludePaths(array $dir_list) + { + PathChecker::setIncludePaths($dir_list); + } + + public static function setExcludePaths(array $dir_list) + { + PathChecker::setExcludePaths($dir_list); + } + + public static function wrap() + { + IncludeStream::wrap(); + } + + public static function unwrap() + { + IncludeStream::unwrap(); + } + + /** + * @param string $path original source file path + * @return resource + * @throws LogicException + */ + public static function patch($path) + { + if (! is_readable($path)) + { + throw new LogicException("Can't read '$path'"); + } + + // Check cache file + if ($cache_file = Cache::getValidSrcCachePath($path)) + { + self::log('cache_hit: ' . $path); + return fopen($cache_file, 'r'); + } + + self::log('cache_miss: ' . $path); + $source = file_get_contents($path); + + list($new_source, $patched) = self::execPatchers($source); + + // Write to cache file + self::log('write_cache: ' . $path); + Cache::writeSrcCacheFile($path, $new_source); + + $resource = fopen('php://memory', 'rb+'); + fwrite($resource, $new_source); + rewind($resource); + return $resource; + } + + protected static function loadPatchers() + { + if (self::$load_patchers) + { + return; + } + + require __DIR__ . '/Patcher/AbstractPatcher.php'; + require __DIR__ . '/Patcher/Backtrace.php'; + + foreach (self::$patcher_list as $classname) + { + require __DIR__ . '/Patcher/' . $classname . '.php'; + } + + self::$load_patchers = true; + } + + protected static function execPatchers($source) + { + $patched = false; + foreach (self::$patcher_list as $classname) + { + $classname = 'Kenjis\MonkeyPatch\Patcher\\' . $classname; + $patcher = new $classname; + list($source, $patched_this) = $patcher->patch($source); + $patched = $patched || $patched_this; + } + + return [ + $source, + $patched, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/AbstractPatcher.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/AbstractPatcher.php new file mode 100644 index 00000000..75acca42 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/AbstractPatcher.php @@ -0,0 +1,57 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +use PhpParser\ParserFactory; +use PhpParser\Lexer; +use PhpParser\NodeTraverser; +use Kenjis\MonkeyPatch\MonkeyPatchManager; + +abstract class AbstractPatcher +{ + protected $node_visitor; + + public static $replacement; + + public function patch($source) + { + $patched = false; + static::$replacement = []; + + $parser = (new ParserFactory) + ->create( + MonkeyPatchManager::getPhpParser(), + new Lexer( + ['usedAttributes' => ['startTokenPos', 'endTokenPos']] + ) + ); + $traverser = new NodeTraverser; + $traverser->addVisitor($this->node_visitor); + + $ast_orig = $parser->parse($source); + $traverser->traverse($ast_orig); + + if (static::$replacement !== []) + { + $patched = true; + $new_source = static::generateNewSource($source); + } + else + { + $new_source = $source; + } + + return [ + $new_source, + $patched, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/Backtrace.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/Backtrace.php new file mode 100644 index 00000000..547c6ced --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/Backtrace.php @@ -0,0 +1,79 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +use LogicException; + +class Backtrace +{ + private static $map = [ + 'FunctionPatcher' => 1, + 'MethodPatcher' => 0, + 'ConstantPatcher' => 0, + ]; + + public static function getInfo($patcher, $backtrace) + { + if (! isset(self::$map[$patcher])) + { + throw new LogicException("No such a patcher: $patcher"); + } + $offset = self::$map[$patcher]; + + // Supports PHP7 optimization + if (version_compare(PHP_VERSION, '6.0.0', '>')) + { + if ($backtrace[$offset]['function'] === '__callStatic') + { + $offset--; + } + } + + $file = isset($backtrace[$offset]['file']) + ? $backtrace[$offset]['file'] : null; + $line = isset($backtrace[$offset]['line']) + ? $backtrace[$offset]['line'] : null; + + if (isset($backtrace[$offset+2])) + { + $class = isset($backtrace[$offset+2]['class']) + ? $backtrace[$offset+2]['class'] + : null; + $function = $backtrace[$offset+2]['function']; + } + else + { + $class = null; + $function = null; + } + + if (isset($class)) + { + $method = $function; + $class_method = $class . '::' . $function; + $function = null; + } + else + { + $method = null; + $class_method = null; + } + + return [ + 'file' => $file, + 'line' => $line, + 'class' => $class, + 'method' => $method, + 'class_method' => $class_method, + 'function' => $function, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher.php new file mode 100644 index 00000000..44a75ca2 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher.php @@ -0,0 +1,100 @@ + + * @license MIT License + * @copyright 2016 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/ConstantPatcher/NodeVisitor.php'; +require __DIR__ . '/ConstantPatcher/Proxy.php'; + +use LogicException; + +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher\NodeVisitor; + +class ConstantPatcher extends AbstractPatcher +{ + /** + * @var special constant names which we don't patch + */ + private static $blacklist = [ + 'true', + 'false', + 'null', + ]; + + public static $replacement; + + public function __construct() + { + $this->node_visitor = new NodeVisitor(); + } + + /** + * @param string $name constant name + * @return boolean + */ + public static function isBlacklisted($name) + { + if (in_array(strtolower($name), self::$blacklist)) + { + return true; + } + + return false; + } + + protected static function generateNewSource($source) + { + $tokens = token_get_all($source); + $new_source = ''; + $i = -1; + + ksort(self::$replacement); + reset(self::$replacement); + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + + foreach ($tokens as $token) + { + $i++; + + if (is_string($token)) + { + $new_source .= $token; + } + elseif ($i == $replacement['key']) + { + $new_source .= $replacement['value']; + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + } + else + { + $new_source .= $token[1]; + } + } + + if ($replacement !== false) + { + throw new LogicException('Replacement data still remain'); + } + + return $new_source; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher/NodeVisitor.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher/NodeVisitor.php new file mode 100644 index 00000000..832ba3c5 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher/NodeVisitor.php @@ -0,0 +1,123 @@ + + * @license MIT License + * @copyright 2016 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\ConstantPatcher; + +use PhpParser\Node; +use PhpParser\Node\Expr\ConstFetch; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; +use PhpParser\NodeVisitorAbstract; + +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher; + +class NodeVisitor extends NodeVisitorAbstract +{ + private $disable_const_rewrite_level = 0; + + public function enterNode(Node $node) + { + $callback = [$this, 'before' . ucfirst($node->getType())]; + if (is_callable($callback)) { + call_user_func_array($callback, [$node]); + } + } + + public function leaveNode(Node $node) + { + if (! ($node instanceof ConstFetch)) + { + $callback = [$this, 'rewrite' . ucfirst($node->getType())]; + if (is_callable($callback)) { + call_user_func_array($callback, [$node]); + } + + return; + } + + if ($this->disable_const_rewrite_level > 0) + { + return; + } + + if (! ($node->name instanceof Name)) + { + return; + } + + if (! $node->name->isUnqualified()) + { + return; + } + + if (! ConstantPatcher::isBlacklisted((string) $node->name)) + { + $replacement = new FullyQualified('\__ConstProxy__::get(\'' . (string) $node->name . '\')'); + + $pos = $node->getAttribute('startTokenPos'); + ConstantPatcher::$replacement[$pos] = + '\__ConstProxy__::get(\'' . (string) $node->name .'\')'; + + $node->name = $replacement; + } + } + + /** + * The following logic is from: + * + * Thank you. + * + * The MIT License (MIT) + * Copyright (c) 2016 Badoo Development + */ + // Cannot rewrite constants that are used as default values in function arguments + public function beforeParam() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteParam() + { + $this->disable_const_rewrite_level--; + } + + // Cannot rewrite constants that are used as default values in constant declarations + public function beforeConst() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteConst() + { + $this->disable_const_rewrite_level--; + } + + // Cannot rewrite constants that are used as default values in property declarations + public function beforeStmt_PropertyProperty() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteStmt_PropertyProperty() + { + $this->disable_const_rewrite_level--; + } + + // Cannot rewrite constants that are used as default values in static variable declarations + public function beforeStmt_StaticVar() + { + $this->disable_const_rewrite_level++; + } + + public function rewriteStmt_StaticVar() + { + $this->disable_const_rewrite_level--; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher/Proxy.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher/Proxy.php new file mode 100644 index 00000000..5ae7d3dd --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ConstantPatcher/Proxy.php @@ -0,0 +1,131 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\ConstantPatcher; + +class_alias('Kenjis\MonkeyPatch\Patcher\ConstantPatcher\Proxy', '__ConstProxy__'); + +use LogicException; +use ReflectionConstant; +use ReflectionException; + +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher; +use Kenjis\MonkeyPatch\Patcher\Backtrace; +use Kenjis\MonkeyPatch\MonkeyPatchManager; +use Kenjis\MonkeyPatch\Cache; +use Kenjis\MonkeyPatch\InvocationVerifier; + +class Proxy +{ + private static $patches = []; + private static $patches_to_apply = []; + + /** + * Set a constant patch + * + * @param string $constant constant name + * @param mixed $value value + * @param string $class_method class::method to apply this patch + * + * @throws LogicException + */ + public static function patch($constant, $value, $class_method = null) + { + self::$patches[$constant] = $value; + self::$patches_to_apply[$constant] = strtolower($class_method); + } + + /** + * Clear all patches and invocation data + */ + public static function reset() + { + self::$patches = []; + self::$patches_to_apply = []; + } + + protected static function logInvocation($constant) + { + if (MonkeyPatchManager::$debug) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('ConstantPatcher', $trace); + + $file = $info['file']; + $line = $info['line']; + $method = isset($info['class_method']) ? $info['class_method'] : $info['function']; + + MonkeyPatchManager::log( + 'invoke_const: ' . $constant . ') on line ' . $line . ' in ' . $file . ' by ' . $method . '()' + ); + } + } + + protected static function checkCalledMethod($constant) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('ConstantPatcher', $trace); + + $class = strtolower($info['class']); + $class_method = strtolower($info['class_method']); + + // Patches the constants only in the class + if (strpos(self::$patches_to_apply[$constant], '::') === false) + { + if (self::$patches_to_apply[$constant] !== $class) + { + return false; + } + return true; + } + //Patches the constants only in the class method + else + { + if (self::$patches_to_apply[$constant] !== $class_method) + { + return false; + } + return true; + } + } + + /** + * Get patched constant value + * + * @param string $constant + * @return mixed + */ + public static function get($constant) + { + self::logInvocation($constant); + + if (! empty(self::$patches_to_apply[$constant])) + { + if (! self::checkCalledMethod($constant)) + { + MonkeyPatchManager::log( + 'invoke_const: ' . $constant . ' not patched (out of scope)' + ); + return constant($constant); + } + } + + if (array_key_exists($constant, self::$patches)) + { + MonkeyPatchManager::log('invoke_const: ' . $constant . ' patched'); + return self::$patches[$constant]; + } + + MonkeyPatchManager::log( + 'invoke_const: ' . $constant . ' not patched (no patch)' + ); + return constant($constant); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ExitPatcher.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ExitPatcher.php new file mode 100644 index 00000000..83aae345 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/ExitPatcher.php @@ -0,0 +1,54 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/../Exception/ExitException.php'; + +class ExitPatcher +{ + public static function patch($source) + { + $tokens = token_get_all($source); + + $patched = false; + $new_source = ''; + $i = -1; + + foreach ($tokens as $token) { + $i++; + if (is_string($token)) + { + $new_source .= $token; + } + elseif ($token[0] === T_EXIT) + { + if ($tokens[$i+1] === ';') + { + $new_source .= 'exit__()'; + } + else + { + $new_source .= 'exit__'; + } + $patched = true; + } + else + { + $new_source .= $token[1]; + } + } + + return [ + $new_source, + $patched, + ]; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher.php new file mode 100644 index 00000000..b05ab5bb --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher.php @@ -0,0 +1,209 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/FunctionPatcher/NodeVisitor.php'; +require __DIR__ . '/FunctionPatcher/Proxy.php'; + +use LogicException; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher\NodeVisitor; + +class FunctionPatcher extends AbstractPatcher +{ + private static $lock_function_list = false; + + /** + * @var array list of function names (in lower case) which you patch + */ + private static $whitelist = [ + 'mt_rand', + 'rand', + 'uniqid', + 'hash_hmac', + 'md5', + 'sha1', + 'hash', + 'time', + 'microtime', + 'date', + 'function_exists', + 'header', + 'setcookie', + // Functions that have param called by reference + // Need to prepare method in FunctionPatcher\Proxy class + 'openssl_random_pseudo_bytes', + ]; + + /** + * @var array list of function names (in lower case) which can't be patched + */ + private static $blacklist = [ + // Segmentation fault + 'call_user_func_array', + 'exit__', + // Error: Only variables should be assigned by reference + 'get_instance', + 'get_config', + 'load_class', + 'get_mimes', + '_get_validation_object', + // has reference param + 'preg_replace', + 'preg_match', + 'preg_match_all', + 'array_unshift', + 'array_shift', + 'sscanf', + 'ksort', + 'krsort', + 'str_ireplace', + 'str_replace', + 'is_callable', + 'flock', + 'end', + 'idn_to_ascii', + // Special functions for ci-phpunit-test + 'show_404', + 'show_error', + 'redirect', + ]; + + public static $replacement; + + public function __construct() + { + $this->node_visitor = new NodeVisitor(); + } + + protected static function checkLock($error_msg) + { + if (self::$lock_function_list) + { + throw new LogicException($error_msg); + } + } + + public static function addWhitelists(array $function_list) + { + self::checkLock("You can't add to whitelist after initialization"); + + foreach ($function_list as $function_name) + { + self::$whitelist[] = strtolower($function_name); + } + } + + /** + * @return array + */ + public static function getFunctionWhitelist() + { + return self::$whitelist; + } + + public static function addBlacklist($function_name) + { + self::checkLock("You can't add to blacklist after initialization"); + + self::$blacklist[] = strtolower($function_name); + } + + public static function removeBlacklist($function_name) + { + self::checkLock("You can't remove from blacklist after initialization"); + + $key = array_search(strtolower($function_name), self::$blacklist); + array_splice(self::$blacklist, $key, 1); + } + + public static function lockFunctionList() + { + self::$lock_function_list = true; + } + + /** + * @param string $name function name + * @return boolean + */ + public static function isWhitelisted($name) + { + if (in_array(strtolower($name), self::$whitelist)) + { + return true; + } + + return false; + } + + /** + * @param string $name function name + * @return boolean + */ + public static function isBlacklisted($name) + { + if (in_array(strtolower($name), self::$blacklist)) + { + return true; + } + + return false; + } + + protected static function generateNewSource($source) + { + $tokens = token_get_all($source); + $new_source = ''; + $i = -1; + + ksort(self::$replacement); + reset(self::$replacement); + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + + foreach ($tokens as $token) + { + $i++; + + if (is_string($token)) + { + $new_source .= $token; + } + elseif ($i == $replacement['key']) + { + $new_source .= $replacement['value']; + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + } + else + { + $new_source .= $token[1]; + } + } + + if ($replacement !== false) + { + throw new LogicException('Replacement data still remain'); + } + + return $new_source; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher/NodeVisitor.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher/NodeVisitor.php new file mode 100644 index 00000000..16e5910e --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher/NodeVisitor.php @@ -0,0 +1,67 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * Copyright for Original Code + * + * @author Adrian Philipp + * @copyright 2014 Adrian Philipp + * @license https://github.com/adri/monkey/blob/dfbb93ae09a2c0712f43eab7ced76d3f49989fbe/LICENSE + * @link https://github.com/adri/monkey + * + * @see https://github.com/adri/monkey/blob/dfbb93ae09a2c0712f43eab7ced76d3f49989fbe/testTest.php + */ + +namespace Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +use ReflectionFunction; +use ReflectionException; + +use PhpParser\Node; +use PhpParser\Node\Expr\FuncCall; +use PhpParser\Node\Name; +use PhpParser\Node\Name\FullyQualified; +use PhpParser\NodeVisitorAbstract; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +class NodeVisitor extends NodeVisitorAbstract +{ + public function leaveNode(Node $node) + { + if (! ($node instanceof FuncCall)) + { + return; + } + + if (! ($node->name instanceof Name)) + { + return; + } + + if (! $node->name->isUnqualified()) + { + return; + } + + if ( + FunctionPatcher::isWhitelisted((string) $node->name) + && ! FunctionPatcher::isBlacklisted((string) $node->name) + ) { + $replacement = new FullyQualified('\__FuncProxy__::' . (string) $node->name); + + $pos = $node->getAttribute('startTokenPos'); + FunctionPatcher::$replacement[$pos] = + '\__FuncProxy__::' . (string) $node->name; + + $node->name = $replacement; + } + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher/Proxy.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher/Proxy.php new file mode 100644 index 00000000..5b75bdd8 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/FunctionPatcher/Proxy.php @@ -0,0 +1,282 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\FunctionPatcher; + +class_alias('Kenjis\MonkeyPatch\Patcher\FunctionPatcher\Proxy', '__FuncProxy__'); + +use LogicException; +use ReflectionFunction; +use ReflectionException; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher; +use Kenjis\MonkeyPatch\Patcher\Backtrace; +use Kenjis\MonkeyPatch\MonkeyPatchManager; +use Kenjis\MonkeyPatch\Cache; +use Kenjis\MonkeyPatch\InvocationVerifier; + +class Proxy +{ + private static $patches = []; + private static $patches_to_apply = []; + private static $expected_invocations = []; + private static $invocations = []; + + /** + * Set a function patch + * + * This method has '__' suffix, because if it matches real function name, + * '__callStatic()' catch it. + * + * @param string $function function name + * @param mixed $return_value return value or callable + * @param string $class_name class::method to apply this patch + * + * @throws LogicException + */ + public static function patch__($function, $return_value, $class_method = null) + { + $function = strtolower($function); + + if (FunctionPatcher::isBlacklisted($function)) + { + $msg = "Can't patch on '$function'. It is in blacklist."; + self::outputMessage($msg); + throw new LogicException($msg); + } + if (! FunctionPatcher::isWhitelisted($function)) + { + $msg = "Can't patch on '$function'. It is not in whitelist. If you want to patch it, please add it to 'functions_to_patch' in 'tests/Bootstrap.php'. But note that there are some limitations. See for details."; + self::outputMessage($msg); + throw new LogicException($msg); + } + + self::$patches[$function] = $return_value; + self::$patches_to_apply[$function] = strtolower($class_method); + } + + /** + * Clear all patches and invocation data + * + * This method has '__' suffix, because if it matches real function name, + * '__callStatic()' catch it. + */ + public static function reset__() + { + self::$patches = []; + self::$patches_to_apply = []; + self::$expected_invocations = []; + self::$invocations = []; + } + + public static function setExpectedInvocations($function, $times, $params) + { + self::$expected_invocations[strtolower($function)][] = [$params, $times]; + } + + public static function verifyInvocations() + { + InvocationVerifier::verify(self::$expected_invocations, self::$invocations); + } + + protected static function logInvocation($function, $arguments) + { + if (MonkeyPatchManager::$debug) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('FunctionPatcher', $trace); + + $file = $info['file']; + $line = $info['line']; + $method = isset($info['class_method']) ? $info['class_method'] : $info['function']; + + $log_args = function () use ($arguments) { + $output = ''; + foreach ($arguments as $arg) { + $output .= var_export($arg, true) . ', '; + } + $output = rtrim($output, ', '); + return $output; + }; + MonkeyPatchManager::log( + 'invoke_func: ' . $function . '(' . $log_args() . ') on line ' . $line . ' in ' . $file . ' by ' . $method . '()' + ); + } + } + + protected static function checkCalledMethod($function) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('FunctionPatcher', $trace); + + $class = strtolower($info['class']); + $class_method = strtolower($info['class_method']); + + // Patches the functions only in the class + if (strpos(self::$patches_to_apply[$function], '::') === false) + { + if (self::$patches_to_apply[$function] !== $class) + { + return false; + } + return true; + } + //Patches the functions only in the class method + else + { + if (self::$patches_to_apply[$function] !== $class_method) + { + return false; + } + return true; + } + } + + public static function __callStatic($function, array $arguments) + { + $function = strtolower($function); + + self::logInvocation($function, $arguments); + self::$invocations[$function][] = $arguments; + + if (isset(self::$patches_to_apply[$function])) + { + if (! self::checkCalledMethod($function)) + { + MonkeyPatchManager::log( + 'invoke_func: ' . $function . '() not patched (out of scope)' + ); + self::checkPassedByReference($function); + return call_user_func_array($function, $arguments); + } + } + + if (array_key_exists($function, self::$patches)) + { + MonkeyPatchManager::log('invoke_func: ' . $function . '() patched'); + + if (is_callable(self::$patches[$function])) + { + $callable = self::$patches[$function]; + + $return = call_user_func_array($callable, $arguments); + if ($return !== __GO_TO_ORIG__) + { + return $return; + } + return call_user_func_array($function, $arguments); + } + + return self::$patches[$function]; + } + + MonkeyPatchManager::log( + 'invoke_func: ' . $function . '() not patched (no patch)' + ); + self::checkPassedByReference($function); + return call_user_func_array($function, $arguments); + } + + protected static function checkPassedByReference($function) + { + $ref_func = new ReflectionFunction($function); + + foreach ($ref_func->getParameters() as $param) + { + if ($param->isPassedByReference()) + { + // Add tmp blacklist + Cache::appendTmpFunctionBlacklist($function); + + // Remove cache file + $backtrace = debug_backtrace(); + $info = Backtrace::getInfo('FunctionPatcher', $backtrace); + $orig_file = $info['file']; + $cache = Cache::removeSrcCacheFile($orig_file); + + $pr_msg = ''; + if (self::isInternalFunction($function)) + { + $pr_msg = "Please send Pull Request to add function '$function' to default config.\n"; + } + + $tmp_blacklist_file = Cache::getTmpFunctionBlacklistFile(); + $msg = + "\n" + . "Can't patch on function '$function'.\n" + . "It has param(s) passed by reference.\n" + . "Added it temporary blacklist file '$tmp_blacklist_file'.\n" + . "And removed cache file '$cache'.\n" + . "$pr_msg" + . "\nPlease run phpunit again."; + + self::outputMessage($msg); + throw new LogicException($msg); + } + } + } + + protected static function outputMessage($msg) + { + $red_begin = "\033[41m\033[37m"; + $red_end = "\033[0m"; + + $msg = str_replace( + ['', ''], [$red_begin, $red_end], $msg + ); + echo $msg . "\n"; + } + + /** + * @param string $name function name + * @return bool + */ + protected static function isInternalFunction($name) + { + try { + $ref_func = new ReflectionFunction($name); + return $ref_func->isInternal(); + } catch (ReflectionException $e) { + // ReflectionException: Function xxx() does not exist + return false; + } + } + + public static function openssl_random_pseudo_bytes( + $length, &$crypto_strong = null + ) + { + $function = 'openssl_random_pseudo_bytes'; + $arguments = [$length, $crypto_strong]; + self::logInvocation($function, $arguments); + self::$invocations[$function][] = $arguments; + + if ($crypto_strong === null) + { + $crypto_strong = true; + } + + if (array_key_exists($function, self::$patches)) + { + if (is_callable(self::$patches[$function])) + { + $callable = self::$patches[$function]; + return call_user_func_array( + $callable, + [$length, &$crypto_strong] + ); + } + + return self::$patches[$function]; + } + + return openssl_random_pseudo_bytes($length, $crypto_strong); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher.php new file mode 100644 index 00000000..3dbbc1e1 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher.php @@ -0,0 +1,125 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher; + +require __DIR__ . '/MethodPatcher/NodeVisitor.php'; +require __DIR__ . '/MethodPatcher/PatchManager.php'; + +use LogicException; + +use Kenjis\MonkeyPatch\Patcher\MethodPatcher\NodeVisitor; + +class MethodPatcher extends AbstractPatcher +{ + const CODE = <<<'EOL' +if (($__ret__ = \__PatchManager__::getReturn(__CLASS__, __FUNCTION__, func_get_args())) !== __GO_TO_ORIG__) return $__ret__; +EOL; + const CODENORET = <<<'EOL' +if (($__ret__ = \__PatchManager__::getReturn(__CLASS__, __FUNCTION__, func_get_args())) !== __GO_TO_ORIG__) return; +EOL; + + public static $replacement; + + public function __construct() + { + $this->node_visitor = new NodeVisitor(); + } + + protected static function generateNewSource($source) + { + $tokens = token_get_all($source); + $new_source = ''; + $i = -1; + + ksort(self::$replacement); + reset(self::$replacement); + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + + $start_method = false; + + foreach ($tokens as $key => $token) + { + $i++; + + if ($i == $replacement['key']) + { + $start_method = true; + } + + if (is_string($token)) + { + if ($start_method && $token === '{') + { + if(self::isVoidFunction($tokens, $key)){ + $new_source .= '{ ' . self::CODENORET; + } + else{ + $new_source .= '{ ' . self::CODE; + } + $start_method = false; + $replacement['key'] = key(self::$replacement); + $replacement['value'] = current(self::$replacement); + next(self::$replacement); + if ($replacement['key'] === null) + { + $replacement = false; + } + } + else + { + $new_source .= $token; + } + } + else + { + $new_source .= $token[1]; + } + } + + return $new_source; + } + + /** + * Checks if a function has a void return type + * + * @param $tokens + * @param $key + * @return bool + */ + protected static function isVoidFunction($tokens, $key){ + if($key - 1 <= 0){ + return false; + } + $token = $tokens[$key - 1]; + if(is_array($token)){ + $token = $token[1]; + } + //Loop backwards though the start of the function block till you either find "void" or the end of the + //parameters declaration. + while($token !== ")"){ + if(strpos($token, "void") !== false){ + return true; + } + $token = $tokens[$key - 1]; + if(is_array($token)){ + $token = $token[1]; + } + $key--; + } + return false; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher/NodeVisitor.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher/NodeVisitor.php new file mode 100644 index 00000000..46998b6b --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher/NodeVisitor.php @@ -0,0 +1,31 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\MethodPatcher; + +use PhpParser\Node; +use PhpParser\Node\Stmt\ClassMethod; +use PhpParser\NodeVisitorAbstract; + +use Kenjis\MonkeyPatch\Patcher\MethodPatcher; + +class NodeVisitor extends NodeVisitorAbstract +{ + public function leaveNode(Node $node) + { + if (! ($node instanceof ClassMethod)) + { + return; + } + + $pos = $node->getAttribute('startTokenPos'); + MethodPatcher::$replacement[$pos] = true; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher/PatchManager.php b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher/PatchManager.php new file mode 100644 index 00000000..3b8b5afc --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/3.x/Patcher/MethodPatcher/PatchManager.php @@ -0,0 +1,114 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch\Patcher\MethodPatcher; + +class_alias('Kenjis\MonkeyPatch\Patcher\MethodPatcher\PatchManager', '__PatchManager__'); + +use Kenjis\MonkeyPatch\MonkeyPatchManager; +use Kenjis\MonkeyPatch\Patcher\Backtrace; +use Kenjis\MonkeyPatch\InvocationVerifier; + +class PatchManager +{ + private static $patches = []; + private static $expected_invocations = []; + private static $invocations = []; + + /** + * Set a method patch + * + * @param string $class + * @param array $params [method_name => return_value] + */ + public static function set($class, $params) + { + self::$patches[$class] = $params; + } + + /** + * Clear all patches and invocation data + */ + public static function clear() + { + self::$patches = []; + self::$expected_invocations = []; + self::$invocations = []; + } + + public static function getReturn($class, $method, $params) + { + if (MonkeyPatchManager::$debug) + { + $trace = debug_backtrace(); + $info = Backtrace::getInfo('MethodPatcher', $trace); + + $file = $info['file']; + $line = $info['line']; + + if (isset($info['class_method'])) + { + $called_method = $info['class_method']; + } + elseif (isset($info['function'])) + { + $called_method = $info['function']; + } + else + { + $called_method = 'n/a'; + } + + $log_args = function () use ($params) { + $output = ''; + foreach ($params as $arg) { + $output .= var_export($arg, true) . ', '; + } + $output = rtrim($output, ', '); + return $output; + }; + MonkeyPatchManager::log( + 'invoke_method: ' . $class.'::'.$method . '(' . $log_args() . ') on line ' . $line . ' in ' . $file . ' by ' . $called_method + ); +// var_dump($trace); exit; + } + + self::$invocations[$class.'::'.$method][] = $params; + + if ( + isset(self::$patches[$class]) + && array_key_exists($method, self::$patches[$class]) + ) + { + $patch = self::$patches[$class][$method]; + } + else + { + return __GO_TO_ORIG__; + } + + if (is_callable($patch)) + { + return call_user_func_array($patch, $params); + } else { + return $patch; + } + } + + public static function setExpectedInvocations($class_method, $times, $params) + { + self::$expected_invocations[$class_method][] = [$params, $times]; + } + + public static function verifyInvocations() + { + InvocationVerifier::verify(self::$expected_invocations, self::$invocations); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/Cache.php b/application/tests/_ci_phpunit_test/patcher/Cache.php new file mode 100644 index 00000000..7d5ee385 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/Cache.php @@ -0,0 +1,282 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch; + +use RuntimeException; + +use RecursiveIteratorIterator; +use RecursiveDirectoryIterator; + +class Cache +{ + private static $project_root; + private static $cache_dir; + private static $src_cache_dir; + private static $tmp_function_blacklist_file; + private static $tmp_function_whitelist_file; + private static $tmp_patcher_list_file; + private static $tmp_include_paths_file; + private static $tmp_exclude_paths_file; + + public static function setProjectRootDir($dir) + { + self::$project_root = realpath($dir); + if (self::$project_root === false) + { + throw new LogicException("No such directory: $dir"); + } + } + + public static function setCacheDir($dir) + { + self::createDir($dir); + self::$cache_dir = realpath($dir); + + if (self::$cache_dir === false) + { + throw new LogicException("No such directory: $dir"); + } + + self::$src_cache_dir = self::$cache_dir . '/src'; + self::$tmp_function_whitelist_file = + self::$cache_dir . '/conf/func_whiltelist.php'; + self::$tmp_function_blacklist_file = + self::$cache_dir . '/conf/func_blacklist.php'; + self::$tmp_patcher_list_file = + self::$cache_dir . '/conf/patcher_list.php'; + self::$tmp_include_paths_file = + self::$cache_dir . '/conf/include_paths.php'; + self::$tmp_exclude_paths_file = + self::$cache_dir . '/conf/exclude_paths.php'; + } + + public static function getCacheDir() + { + return self::$cache_dir; + } + + public static function getSrcCacheFilePath($path) + { + $len = strlen(self::$project_root); + $relative_path = substr($path, $len); + + if ($relative_path === false) + { + return false; + } + + return self::$src_cache_dir . '/' . $relative_path; + } + + protected static function createDir($dir) + { + if (! is_dir($dir)) + { + if (! @mkdir($dir, 0777, true)) + { + throw new RuntimeException('Failed to create folder: ' . $dir); + } + } + } + + /** + * @param string $path original source file path + * @return string|false + */ + public static function getValidSrcCachePath($path) + { + $cache_file = self::getSrcCacheFilePath($path); + + if ( + is_readable($cache_file) && filemtime($cache_file) > filemtime($path) + ) + { + return $cache_file; + } + + return false; + } + + /** + * Write to src cache file + * + * @param string $path original source file path + * @param string $source source code + */ + public static function writeSrcCacheFile($path, $source) + { + $cache_file = self::getSrcCacheFilePath($path); + if ($cache_file !== false) + { + self::writeCacheFile($cache_file, $source); + } + } + + /** + * Write to cache file + * + * @param string $path file path + * @param string $contents file contents + */ + public static function writeCacheFile($path, $contents) + { + $dir = dirname($path); + self::createDir($dir); + file_put_contents($path, $contents); + } + + public static function getTmpFunctionBlacklistFile() + { + return self::$tmp_function_blacklist_file; + } + + public static function createTmpListDir() + { + if (is_readable(self::$tmp_function_blacklist_file)) + { + return; + } + + $dir = dirname(self::$tmp_function_blacklist_file); + self::createDir($dir); + + touch(self::$tmp_function_blacklist_file); + } + + public static function appendTmpFunctionBlacklist($function) + { + file_put_contents( + self::getTmpFunctionBlacklistFile(), $function . "\n", FILE_APPEND + ); + } + + protected static function writeTmpConfFile($filename, array $list) + { + $contents = implode("\n", $list); + file_put_contents( + self::$$filename, $contents + ); + } + + public static function writeTmpFunctionWhitelist(array $functions) + { + return self::writeTmpConfFile( + 'tmp_function_whitelist_file', $functions + ); + } + + public static function writeTmpPatcherList(array $patchers) + { + return self::writeTmpConfFile( + 'tmp_patcher_list_file', $patchers + ); + } + + public static function writeTmpIncludePaths(array $paths) + { + return self::writeTmpConfFile( + 'tmp_include_paths_file', $paths + ); + } + + public static function writeTmpExcludePaths(array $paths) + { + return self::writeTmpConfFile( + 'tmp_exclude_paths_file', $paths + ); + } + + protected static function getTmpConfFile($filename) + { + if (is_readable(self::$$filename)) + { + return file( + self::$$filename, + FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES + ); + } + return []; + } + + public static function getTmpFunctionWhitelist() + { + return self::getTmpConfFile('tmp_function_whitelist_file'); + } + + public static function getTmpPatcherList() + { + return self::getTmpConfFile('tmp_patcher_list_file'); + } + + public static function getTmpIncludePaths() + { + return self::getTmpConfFile('tmp_include_paths_file'); + } + + public static function getTmpExcludePaths() + { + return self::getTmpConfFile('tmp_exclude_paths_file'); + } + + /** + * @param string $orig_file original source file + * @return string removed cache file + */ + public static function removeSrcCacheFile($orig_file) + { + $cache = self::getSrcCacheFilePath($orig_file); + @unlink($cache); + MonkeyPatchManager::log('remove_src_cache: ' . $cache); + return $cache; + } + + public static function clearSrcCache() + { + self::recursiveUnlink(self::$src_cache_dir); + MonkeyPatchManager::log('clear_src_cache: cleared ' . self::$src_cache_dir); + } + + public static function clearCache() + { + self::recursiveUnlink(self::$cache_dir); + MonkeyPatchManager::log('clear_cache: cleared ' . self::$cache_dir); + } + + /** + * Recursive Unlink + * + * @param string $dir + */ + protected static function recursiveUnlink($dir) + { + if (! is_dir($dir)) + { + return; + } + + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator( + $dir, RecursiveDirectoryIterator::SKIP_DOTS + ), + RecursiveIteratorIterator::CHILD_FIRST + ); + + foreach ($iterator as $file) { + if ($file->isDir()) { + rmdir($file); + } else { + unlink($file); + } + } + + rmdir($dir); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/IncludeStream.php b/application/tests/_ci_phpunit_test/patcher/IncludeStream.php new file mode 100644 index 00000000..ec7e9859 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/IncludeStream.php @@ -0,0 +1,276 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * Copyright for Original Code + * + * @author Ignas Rudaitis + * @copyright 2010-2015 Ignas Rudaitis + * @license http://www.opensource.org/licenses/mit-license.html + * @link http://antecedent.github.com/patchwork + * + * @see https://github.com/antecedent/patchwork/blob/1.3.5/src/Preprocessor/Stream.php + */ + +namespace Kenjis\MonkeyPatch; + +class IncludeStream +{ + const STREAM_OPEN_FOR_INCLUDE = 128; + const STAT_MTIME_NUMERIC_OFFSET = 9; + const STAT_MTIME_ASSOC_OFFSET = 'mtime'; + + protected static $protocols = array('file', 'phar'); + + public $context; + public $resource; + + public static function wrap() + { + foreach (static::$protocols as $protocol) { + stream_wrapper_unregister($protocol); + stream_wrapper_register($protocol, get_called_class()); + } + } + + public static function unwrap() + { + foreach (static::$protocols as $protocol) { + stream_wrapper_restore($protocol); + } + } + + protected function shouldPreprocess($path) + { + return PathChecker::check($path); + } + + protected function preprocessAndOpen($path) + { + return MonkeyPatchManager::patch($path); + } + + public function stream_open($path, $mode, $options, &$openedPath) + { + $this->unwrap(); + + MonkeyPatchManager::log('stream_open: ' . $path); + + $including = (bool) ($options & self::STREAM_OPEN_FOR_INCLUDE); + if ($including && $this->shouldPreprocess($path)) { + $this->resource = $this->preprocessAndOpen($path); + $this->wrap(); + return true; + } + if (isset($this->context)) { + $this->resource = fopen($path, $mode, $options, $this->context); + } else { + $this->resource = fopen($path, $mode, $options); + } + $this->wrap(); + return $this->resource !== false; + } + + public function stream_close() + { + return fclose($this->resource); + } + + public function stream_eof() + { + return feof($this->resource); + } + + public function stream_flush() + { + return fflush($this->resource); + } + + public function stream_read($count) + { + return fread($this->resource, $count); + } + + public function stream_seek($offset, $whence = SEEK_SET) + { + return fseek($this->resource, $offset, $whence) === 0; + } + + public function stream_stat() + { + $result = fstat($this->resource); + if ($result) { + $result[self::STAT_MTIME_ASSOC_OFFSET]++; + $result[self::STAT_MTIME_NUMERIC_OFFSET]++; + } + return $result; + } + + public function stream_tell() + { + return ftell($this->resource); + } + + public function url_stat($path, $flags) + { + $this->unwrap(); + if ($flags & STREAM_URL_STAT_QUIET) { + set_error_handler(function() {}); + } + $result = stat($path); + if ($flags & STREAM_URL_STAT_QUIET) { + restore_error_handler(); + } + $this->wrap(); + if ($result) { + $result[self::STAT_MTIME_ASSOC_OFFSET]++; + $result[self::STAT_MTIME_NUMERIC_OFFSET]++; + } + return $result; + } + + public function dir_closedir() + { + closedir($this->resource); + return true; + } + + public function dir_opendir($path, $options) + { + $this->unwrap(); + if (isset($this->context)) { + $this->resource = opendir($path, $this->context); + } else { + $this->resource = opendir($path); + } + $this->wrap(); + return $this->resource !== false; + } + + public function dir_readdir() + { + return readdir($this->resource); + } + + public function dir_rewinddir() + { + rewinddir($this->resource); + return true; + } + + public function mkdir($path, $mode, $options) + { + $this->unwrap(); + if (isset($this->context)) { + $result = mkdir($path, $mode, $options, $this->context); + } else { + $result = mkdir($path, $mode, $options); + } + $this->wrap(); + return $result; + } + + public function rename($path_from, $path_to) + { + $this->unwrap(); + if (isset($this->context)) { + $result = rename($path_from, $path_to, $this->context); + } else { + $result = rename($path_from, $path_to); + } + $this->wrap(); + return $result; + } + + public function rmdir($path, $options) + { + $this->unwrap(); + if (isset($this->context)) { + $result = rmdir($path, $this->context); + } else { + $result = rmdir($path); + } + $this->wrap(); + return $result; + } + + public function stream_cast($cast_as) + { + return $this->resource; + } + + public function stream_lock($operation) + { + return flock($this->resource, $operation); + } + + public function stream_set_option($option, $arg1, $arg2) + { + switch ($option) { + case STREAM_OPTION_BLOCKING: + return stream_set_blocking($this->resource, $arg1); + case STREAM_OPTION_READ_TIMEOUT: + return stream_set_timeout($this->resource, $arg1, $arg2); + case STREAM_OPTION_WRITE_BUFFER: + return stream_set_write_buffer($this->resource, $arg1); + case STREAM_OPTION_READ_BUFFER: + return stream_set_read_buffer($this->resource, $arg1); + } + } + + public function stream_write($data) + { + return fwrite($this->resource, $data); + } + + public function unlink($path) + { + $this->unwrap(); + if (isset($this->context)) { + $result = unlink($path, $this->context); + } else { + $result = unlink($path); + } + $this->wrap(); + return $result; + } + + public function stream_metadata($path, $option, $value) + { + $this->unwrap(); + switch ($option) { + case STREAM_META_TOUCH: + if (empty($value)) { + $result = touch($path); + } else { + $result = touch($path, $value[0], $value[1]); + } + break; + case STREAM_META_OWNER_NAME: + case STREAM_META_OWNER: + $result = chown($path, $value); + break; + case STREAM_META_GROUP_NAME: + case STREAM_META_GROUP: + $result = chgrp($path, $value); + break; + case STREAM_META_ACCESS: + $result = chmod($path, $value); + break; + } + $this->wrap(); + return $result; + } + + public function stream_truncate($new_size) + { + return ftruncate($this->resource, $new_size); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/InvocationVerifier.php b/application/tests/_ci_phpunit_test/patcher/InvocationVerifier.php new file mode 100644 index 00000000..2e375969 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/InvocationVerifier.php @@ -0,0 +1,79 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch; + +use PHPUnit_Framework_TestCase; + +class InvocationVerifier +{ + public static function verify(array $expected_invocations, array $invocations) + { + if ($expected_invocations === []) + { + return; + } + + foreach ($expected_invocations as $class_method => $data) + { + foreach ($data as $params_times) + { + list($expected_params, $expected_times) = $params_times; + + $invoked = isset($invocations[$class_method]); + if ($invoked === false) + { + $actual_times = 0; + } + elseif ($expected_params === null) + { + $actual_times = count($invocations[$class_method]); + } + else + { + $count = 0; + foreach ($invocations[$class_method] as $actual_params) + { + if ($actual_params == $expected_params) + { + $count++; + } + } + $actual_times = $count; + } + + if ($expected_times === 0) + { + PHPUnit_Framework_TestCase::assertEquals( + $expected_times, + $actual_times, + $class_method . '() expected to be not invoked, but invoked ' . $actual_times . ' times.' + ); + } + elseif ($expected_times === '+') + { + PHPUnit_Framework_TestCase::assertGreaterThanOrEqual( + 1, + $actual_times, + $class_method . '() expected to be invoked at least one time, but invoked ' . $actual_times . ' times.' + ); + } + else + { + PHPUnit_Framework_TestCase::assertEquals( + $expected_times, + $actual_times, + $class_method . '() expected to be invoked ' . $expected_times . ' times, but invoked ' . $actual_times . ' times.' + ); + } + } + } + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/MonkeyPatch.php b/application/tests/_ci_phpunit_test/patcher/MonkeyPatch.php new file mode 100644 index 00000000..7e6ea488 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/MonkeyPatch.php @@ -0,0 +1,156 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch; + +use Kenjis\MonkeyPatch\Patcher\FunctionPatcher\Proxy; +use Kenjis\MonkeyPatch\Patcher\ConstantPatcher\Proxy as ConstProxy; +use Kenjis\MonkeyPatch\Patcher\MethodPatcher\PatchManager; + +class MonkeyPatch +{ + /** + * Patch on function + * + * @param string $function function name + * @param mixed $return_value return value + * @param string $class_name class::method to apply this patch + */ + public static function patchFunction($function, $return_value, $class_method = null) + { + Proxy::patch__($function, $return_value, $class_method); + } + + /** + * Reset all patched fuctions + */ + public static function resetFunctions() + { + Proxy::reset__(); + } + + /** + * Patch on constant + * + * @param type $constant + * @param type $value + * @param type $class_method + */ + public static function patchConstant($constant, $value, $class_method = null) + { + ConstProxy::patch($constant, $value, $class_method); + } + + /** + * Reset all patched constants + */ + public static function resetConstants() + { + ConstProxy::reset(); + } + + /** + * Patch on class method + * + * @param string $class + * @param array $params [method_name => return_value] + */ + public static function patchMethod($class, $params) + { + PatchManager::set($class, $params); + } + + /** + * Reset all patched class method + */ + public static function resetMethods() + { + PatchManager::clear(); + } + + protected static function getClassname($class_method) + { + if (strpos($class_method, '::') === false) + { + return 'Kenjis\MonkeyPatch\Patcher\FunctionPatcher\Proxy'; + } + else + { + return 'Kenjis\MonkeyPatch\Patcher\MethodPatcher\PatchManager'; + } + } + + /** + * @param string $class_method class::method or function name + * @param int $times times + * @param array $params parameters + */ + public static function verifyInvokedMultipleTimes( + $class_method, $times, array $params = null + ) + { + $classname = self::getClassname($class_method); + $classname::setExpectedInvocations( + $class_method, $times, $params + ); + } + + /** + * @param string $class_method class::method or function name + * @param array $params parameters + */ + public static function verifyInvoked($class_method, array $params = null) + { + $classname = self::getClassname($class_method); + $classname::setExpectedInvocations( + $class_method, '+', $params + ); + } + + /** + * @param string $class_method class::method or function name + * @param array $params parameters + */ + public static function verifyInvokedOnce($class_method, array $params = null) + { + $classname = self::getClassname($class_method); + $classname::setExpectedInvocations( + $class_method, 1, $params + ); + } + + /** + * @param string $class_method class::method or function name + * @param array $params parameters + */ + public static function verifyNeverInvoked($class_method, array $params = null) + { + $classname = self::getClassname($class_method); + $classname::setExpectedInvocations( + $class_method, 0, $params + ); + } + + /** + * Run function verifcations + */ + public static function verifyFunctionInvocations() + { + Proxy::verifyInvocations(); + } + + /** + * Run method verifcations + */ + public static function verifyMethodInvocations() + { + PatchManager::verifyInvocations(); + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/PathChecker.php b/application/tests/_ci_phpunit_test/patcher/PathChecker.php new file mode 100644 index 00000000..d428ced9 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/PathChecker.php @@ -0,0 +1,119 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +namespace Kenjis\MonkeyPatch; + +use RuntimeException; + +class PathChecker +{ + private static $include_paths = []; + private static $exclude_paths = []; + + /** + * @param array $paths directory or file path + * @return array + * @throws RuntimeException + */ + protected static function normalizePaths(array $paths) + { + $new_paths = []; + $excluded = false; + foreach ($paths as $path) + { + // Path starting with '-' has special meaning (excluding it) + if (substr($path, 0, 1) === '-') + { + $excluded = true; + $path = ltrim($path, '-'); + } + + $real_path = realpath($path); + if ($real_path === FALSE) + { + throw new RuntimeException($path . ' does not exist?'); + } + if (is_dir($real_path)) + { + // Must use DIRECTORY_SEPARATOR for Windows + $real_path = $real_path . DIRECTORY_SEPARATOR; + } + $new_paths[] = $excluded ? '-'.$real_path : $real_path; + } + array_unique($new_paths, SORT_STRING); + sort($new_paths, SORT_STRING); + return $new_paths; + } + + public static function setIncludePaths(array $dir) + { + self::$include_paths = self::normalizePaths($dir); + } + + public static function setExcludePaths(array $dir) + { + self::$exclude_paths = self::normalizePaths($dir); + } + + public static function getIncludePaths() + { + return self::$include_paths; + } + + public static function getExcludePaths() + { + return self::$exclude_paths; + } + + public static function check($path) + { + // Windows + if (DIRECTORY_SEPARATOR === '\\') { + $path = str_replace('/', '\\', $path); + } + + // Whitelist first + $is_white = false; + foreach (self::$include_paths as $white_dir) { + $len = strlen($white_dir); + if (substr($path, 0, $len) === $white_dir) + { + $is_white = true; + } + } + if ($is_white === false) + { + return false; + } + + // Then blacklist + foreach (self::$exclude_paths as $black_dir) { + // Check excluded path that starts with '-'. + // '-' is smaller than '/', so this checking always comes first. + if (substr($black_dir, 0, 1) === '-') + { + $black_dir = ltrim($black_dir, '-'); + $len = strlen($black_dir); + if (substr($path, 0, $len) === $black_dir) + { + return true; + } + } + + $len = strlen($black_dir); + if (substr($path, 0, $len) === $black_dir) + { + return false; + } + } + + return true; + } +} diff --git a/application/tests/_ci_phpunit_test/patcher/bootstrap.php b/application/tests/_ci_phpunit_test/patcher/bootstrap.php new file mode 100644 index 00000000..25cd96d2 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/bootstrap.php @@ -0,0 +1,74 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// If you use Composer +if (class_exists('PhpParser\Autoloader')) { + if (method_exists('PhpParser\Node\Name','set')) { + // PHP-Parser 2.x + require __DIR__ . '/2.x/MonkeyPatchManager.php'; + } else { + // PHP-Parser 3.x + require __DIR__ . '/3.x/MonkeyPatchManager.php'; + } +} +// If you don't use Composer +else { + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + // Use PHP-Parser 3.x + require __DIR__ . '/third_party/PHP-Parser-3.0.3/lib/bootstrap.php'; + require __DIR__ . '/3.x/MonkeyPatchManager.php'; + } else { + // Use PHP-Parser 2.x + require __DIR__ . '/third_party/PHP-Parser-2.1.1/lib/bootstrap.php'; + require __DIR__ . '/2.x/MonkeyPatchManager.php'; + } +} + +require __DIR__ . '/IncludeStream.php'; +require __DIR__ . '/PathChecker.php'; +require __DIR__ . '/MonkeyPatch.php'; +require __DIR__ . '/Cache.php'; +require __DIR__ . '/InvocationVerifier.php'; + +require __DIR__ . '/functions/exit__.php'; + +const __GO_TO_ORIG__ = '__GO_TO_ORIG__'; + +class_alias('Kenjis\MonkeyPatch\MonkeyPatchManager', 'MonkeyPatchManager'); + +// And you have to configure for your application +//MonkeyPatchManager::init([ +// // PHP Parser: PREFER_PHP7, PREFER_PHP5, ONLY_PHP7, ONLY_PHP5 +// 'php_parser' => 'PREFER_PHP5', +// // Project root directory +// 'root_dir' => APPPATH . '../', +// // Cache directory +// 'cache_dir' => TESTPATH . '_ci_phpunit_test/tmp/cache', +// // Directories to patch on source files +// 'include_paths' => [ +// APPPATH, +// BASEPATH, +// ], +// // Excluding directories to patch +// 'exclude_paths' => [ +// TESTPATH, +// ], +// // All patchers you use +// 'patcher_list' => [ +// 'ExitPatcher', +// 'FunctionPatcher', +// 'MethodPatcher', +// 'ConstantPatcher', +// ], +// // Additional functions to patch +// 'functions_to_patch' => [ +// //'random_string', +// ], +//]); diff --git a/application/tests/_ci_phpunit_test/patcher/functions/exit__.php b/application/tests/_ci_phpunit_test/patcher/functions/exit__.php new file mode 100644 index 00000000..c0740e89 --- /dev/null +++ b/application/tests/_ci_phpunit_test/patcher/functions/exit__.php @@ -0,0 +1,37 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +function exit__($status = null) +{ + $trace = debug_backtrace(); + $file = $trace[0]['file']; + $line = $trace[0]['line']; + $class = isset($trace[1]['class']) ? $trace[1]['class'] : null; + $method = $trace[1]['function']; + + if ($class === null) + { + $message = 'exit() called in ' . $method . '() function'; + } + else + { + $message = 'exit() called in ' . $class . '::' . $method . '()'; + } + + $exception_name = Kenjis\MonkeyPatch\MonkeyPatchManager::getExitExceptionClassname(); + $exception = new $exception_name($message); + $exception->file = $file; + $exception->line = $line; + $exception->class = $class; + $exception->method = $method; + $exception->exit_status = $status; + + throw $exception; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/CodeIgniter.php new file mode 100644 index 00000000..63197a02 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/Common.php b/application/tests/_ci_phpunit_test/replacing/core/Common.php new file mode 100644 index 00000000..2d98d1d6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class the class name being requested + * @param string $directory the directory where the class should be found + * @param mixed $param an optional argument to pass to the class constructor + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/Input.php b/application/tests/_ci_phpunit_test/replacing/core/Input.php new file mode 100644 index 00000000..3cd93cbb --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/Input.php @@ -0,0 +1,952 @@ +_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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/Loader.php b/application/tests/_ci_phpunit_test/replacing/core/Loader.php new file mode 100644 index 00000000..41983cbf --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/Loader.php @@ -0,0 +1,1487 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + { + $result = DB($params, $query_builder); + CIPHPUnitTestDbConnectionStore::add($result); + return $result; + } + + // 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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 + * + * modified by ci-phpunit-test + */ + 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); + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/Output.php b/application/tests/_ci_phpunit_test/replacing/core/Output.php new file mode 100644 index 00000000..ac94798c --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/Output.php @@ -0,0 +1,864 @@ +_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 = (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) + { + // Combine headers already sent with our batched headers + $headers = array_merge( + // We only need [x][0] from our multi-dimensional array + array_map('array_shift', $this->headers), + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.0-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.0-Common.php new file mode 100644 index 00000000..ee786f27 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.0-Common.php @@ -0,0 +1,383 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class + * @param string $directory + * @param array $param + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + if ($exit_status > 125) // 125 is EXIT__AUTO_MAX + { + $exit_status = 1; // EXIT_ERROR + } + + $status_code = 500; + } + else + { + $exit_status = 1; // EXIT_ERROR + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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', + + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported' + ); + + 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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + if (strpos(PHP_SAPI, 'cgi') === 0) + { + header('Status: '.$code.' '.$text, TRUE); + } + else + { + $server_protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); + } +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.0-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.0-Loader.php new file mode 100644 index 00000000..032bfa51 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.0-Loader.php @@ -0,0 +1,1390 @@ + 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 string $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 string $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 + * + * modified by ci-phpunit-test + */ + 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)) + { + show_error('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); + } + +// if ( ! class_exists('CI_Model', FALSE)) +// { + load_class('Model', 'core'); +// } + + $model = ucfirst(strtolower($model)); + + 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'); + + $this->_ci_models[] = $name; + $CI->$name = new $model(); + return $this; + } + + // couldn't find the model + show_error('Unable to locate the model you have specified: '.$model); + } + + // -------------------------------------------------------------------- + + /** + * 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_object_to_array($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 = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + foreach ($vars as $key => $val) + { + $this->_ci_cached_vars[$key] = $val; + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Clear Cached Variables + * + * Clears the cached variables. + * + * @return object + */ + 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()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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 $driver) + { + $this->driver($driver); + } + + 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. + */ + if (is_array($_ci_vars)) + { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); + } + extract($this->_ci_cached_vars); + + /* + * Buffer the output + * + * We buffer the output for two reasons: + * 1. Speed. You get a significant speed boost. + * 2. So that the final rendered template can be post-processed by + * the output class. Why do we need post processing? For one thing, + * in order to show the elapsed page load time. Unless we can + * intercept the content right before it's sent to the browser and + * then stop the timer it won't be accurate. + */ + ob_start(); + + // If the PHP installation does not support short tags we'll + // do a little string replacement, changing the short tags + // to standard PHP echo statements. + if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE && function_usable('eval')) + { + 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 + * + * modified by ci-phpunit-test + */ + 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? +// if (class_exists($class, FALSE)) +// { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; +// } + // 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 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// 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; + } + else + { + log_message('debug', APPPATH.'libraries/'.$file_path.$subclass.'.php 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'])) + { + foreach ($autoload['drivers'] as $item) + { + $this->driver($item); + } + } + + // 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 + foreach ($autoload['libraries'] as $item) + { + $this->library($item); + } + } + + // Autoload models + if (isset($autoload['model'])) + { + $this->model($autoload['model']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.1-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.1-Loader.php new file mode 100644 index 00000000..da605e2c --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.1-Loader.php @@ -0,0 +1,1401 @@ + 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 string $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 string $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 + * + * modified by ci-phpunit-test + */ + 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); + } + +// if ( ! class_exists('CI_Model', FALSE)) +// { + load_class('Model', 'core'); +// } + + $model = ucfirst(strtolower($model)); + if ( ! class_exists($model)) + { + 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; + $CI->$name = new $model(); + 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_object_to_array($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 = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + 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()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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 $driver) + { + $this->driver($driver); + } + + 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. + */ + if (is_array($_ci_vars)) + { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); + } + extract($this->_ci_cached_vars); + + /* + * Buffer the output + * + * We buffer the output for two reasons: + * 1. Speed. You get a significant speed boost. + * 2. So that the final rendered template can be post-processed by + * the output class. Why do we need post processing? For one thing, + * in order to show the elapsed page load time. Unless we can + * intercept the content right before it's sent to the browser and + * then stop the timer it won't be accurate. + */ + ob_start(); + + // If the PHP installation does not support short tags we'll + // do a little string replacement, changing the short tags + // to standard PHP echo statements. + if ( ! 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 + * + * modified by ci-phpunit-test + */ + 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? +// if (class_exists($class, FALSE)) +// { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; +// } + // 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 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// 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; + } + else + { + 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'])) + { + foreach ($autoload['drivers'] as $item) + { + $this->driver($item); + } + } + + // 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']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-CodeIgniter.php new file mode 100644 index 00000000..b3760f0b --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-CodeIgniter.php @@ -0,0 +1,563 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return object + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + // WARNING: It appears that there are issues with is_callable() even in PHP 5.2! + // Furthermore, there are bug reports and feature/change requests related to it + // that make it unreliable to use in this context. Please, DO NOT change this + // work-around until a better alternative is available. + elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE)) + { + $e404 = TRUE; + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-Input.php new file mode 100644 index 00000000..e2cd31f6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-Input.php @@ -0,0 +1,910 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) + { + if (is_array($name)) + { + // always leave 'name' in last place, as the loop will break otherwise, due to $$item + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') 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'); + } + + if ($secure === FALSE && config_item('cookie_secure') === TRUE) + { + $secure = config_item('cookie_secure'); + } + + if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE) + { + $httponly = config_item('cookie_httponly'); + } + + if ( ! is_numeric($expire)) + { + $expire = time() - 86500; + } + else + { + $expire = ($expire > 0) ? time() + $expire : 0; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * 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 ($i = 0; $i < 8; $i++) + { + $netaddr[$i] = intval($netaddr[$i], 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 = NULL; + 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->headers; + } + + // In Apache, you can simply call apache_request_headers() + if (function_exists('apache_request_headers')) + { + return $this->headers = apache_request_headers(); + } + + $this->headers['Content-Type'] = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : @getenv('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] = $this->_fetch_from_array($_SERVER, $key, $xss_clean); + } + } + + return $this->headers; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-Loader.php new file mode 100644 index 00000000..3ab33cde --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.3-Loader.php @@ -0,0 +1,1401 @@ + 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 string $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 string $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 + * + * modified by ci-phpunit-test + */ + 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); + } + +// if ( ! class_exists('CI_Model', FALSE)) +// { + load_class('Model', 'core'); +// } + + $model = ucfirst($model); + if ( ! class_exists($model)) + { + 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; + $CI->$name = new $model(); + 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_object_to_array($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 = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + 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()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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 $driver) + { + $this->driver($driver); + } + + 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. + */ + if (is_array($_ci_vars)) + { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); + } + extract($this->_ci_cached_vars); + + /* + * Buffer the output + * + * We buffer the output for two reasons: + * 1. Speed. You get a significant speed boost. + * 2. So that the final rendered template can be post-processed by + * the output class. Why do we need post processing? For one thing, + * in order to show the elapsed page load time. Unless we can + * intercept the content right before it's sent to the browser and + * then stop the timer it won't be accurate. + */ + ob_start(); + + // If the PHP installation does not support short tags we'll + // do a little string replacement, changing the short tags + // to standard PHP echo statements. + if ( ! 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 + * + * modified by ci-phpunit-test + */ + 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// 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; + } + else + { + 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'])) + { + foreach ($autoload['drivers'] as $item) + { + $this->driver($item); + } + } + + // 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']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-CodeIgniter.php new file mode 100644 index 00000000..5df0a770 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-CodeIgniter.php @@ -0,0 +1,563 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return object + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + // WARNING: It appears that there are issues with is_callable() even in PHP 5.2! + // Furthermore, there are bug reports and feature/change requests related to it + // that make it unreliable to use in this context. Please, DO NOT change this + // work-around until a better alternative is available. + elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE)) + { + $e404 = TRUE; + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-Input.php new file mode 100644 index 00000000..ab1f8f4a --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-Input.php @@ -0,0 +1,912 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) + { + if (is_array($name)) + { + // always leave 'name' in last place, as the loop will break otherwise, due to $$item + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') 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'); + } + + if ($secure === FALSE && config_item('cookie_secure') === TRUE) + { + $secure = config_item('cookie_secure'); + } + + if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE) + { + $httponly = config_item('cookie_httponly'); + } + + if ( ! is_numeric($expire)) + { + $expire = time() - 86500; + } + else + { + $expire = ($expire > 0) ? time() + $expire : 0; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * 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 ($i = 0; $i < 8; $i++) + { + $netaddr[$i] = intval($netaddr[$i], 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 = NULL; + 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->headers; + } + + // In Apache, you can simply call apache_request_headers() + if (function_exists('apache_request_headers')) + { + return $this->headers = apache_request_headers(); + } + + $this->headers['Content-Type'] = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : @getenv('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] = $this->_fetch_from_array($_SERVER, $key, $xss_clean); + } + } + + return $this->headers; + } + + // -------------------------------------------------------------------- + + /** + * 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 + * + * modified by ci-phpunit-test + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-Loader.php new file mode 100644 index 00000000..d2d66dff --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.4-Loader.php @@ -0,0 +1,1431 @@ + 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 string $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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $model = ucfirst($model); + if ( ! class_exists($model)) + { + 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; + $CI->$name = new $model(); + 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_object_to_array($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 = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + 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()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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 $driver) + { + $this->driver($driver); + } + + 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. + */ + if (is_array($_ci_vars)) + { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); + } + extract($this->_ci_cached_vars); + + /* + * Buffer the output + * + * We buffer the output for two reasons: + * 1. Speed. You get a significant speed boost. + * 2. So that the final rendered template can be post-processed by + * the output class. Why do we need post processing? For one thing, + * in order to show the elapsed page load time. Unless we can + * intercept the content right before it's sent to the browser and + * then stop the timer it won't be accurate. + */ + ob_start(); + + // If the PHP installation does not support short tags we'll + // do a little string replacement, changing the short tags + // to standard PHP echo statements. + if ( ! 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 + * + * modified by ci-phpunit-test + */ + 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// 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; + } + else + { + 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'])) + { + foreach ($autoload['drivers'] as $item) + { + $this->driver($item); + } + } + + // 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']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.5-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.5-CodeIgniter.php new file mode 100644 index 00000000..13c7b6ea --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.5-CodeIgniter.php @@ -0,0 +1,563 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + // WARNING: It appears that there are issues with is_callable() even in PHP 5.2! + // Furthermore, there are bug reports and feature/change requests related to it + // that make it unreliable to use in this context. Please, DO NOT change this + // work-around until a better alternative is available. + elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE)) + { + $e404 = TRUE; + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.5-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.5-Loader.php new file mode 100644 index 00000000..6dc490cd --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.5-Loader.php @@ -0,0 +1,1443 @@ + 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 string $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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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_object_to_array($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 = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + 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()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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. + */ + if (is_array($_ci_vars)) + { + foreach (array_keys($_ci_vars) as $key) + { + if (strncmp($key, '_ci_', 4) === 0) + { + unset($_ci_vars[$key]); + } + } + + $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 + * + * modified by ci-phpunit-test + */ + 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// 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; + } + else + { + 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']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.0.6-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.6-CodeIgniter.php new file mode 100644 index 00000000..44700b11 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.0.6-CodeIgniter.php @@ -0,0 +1,563 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + // WARNING: It appears that there are issues with is_callable() even in PHP 5.2! + // Furthermore, there are bug reports and feature/change requests related to it + // that make it unreliable to use in this context. Please, DO NOT change this + // work-around until a better alternative is available. + elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE)) + { + $e404 = TRUE; + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-CodeIgniter.php new file mode 100644 index 00000000..cdf043e1 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-CodeIgniter.php @@ -0,0 +1,563 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + // WARNING: It appears that there are issues with is_callable() even in PHP 5.2! + // Furthermore, there are bug reports and feature/change requests related to it + // that make it unreliable to use in this context. Please, DO NOT change this + // work-around until a better alternative is available. + elseif ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($class)), TRUE)) + { + $e404 = TRUE; + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Common.php new file mode 100644 index 00000000..ee786f27 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Common.php @@ -0,0 +1,383 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class + * @param string $directory + * @param array $param + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + if ($exit_status > 125) // 125 is EXIT__AUTO_MAX + { + $exit_status = 1; // EXIT_ERROR + } + + $status_code = 500; + } + else + { + $exit_status = 1; // EXIT_ERROR + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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', + + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported' + ); + + 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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + if (strpos(PHP_SAPI, 'cgi') === 0) + { + header('Status: '.$code.' '.$text, TRUE); + } + else + { + $server_protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); + } +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Input.php new file mode 100644 index 00000000..5d30d09a --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Input.php @@ -0,0 +1,914 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) + { + if (is_array($name)) + { + // always leave 'name' in last place, as the loop will break otherwise, due to $$item + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') 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'); + } + + if ($secure === FALSE && config_item('cookie_secure') === TRUE) + { + $secure = config_item('cookie_secure'); + } + + if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE) + { + $httponly = config_item('cookie_httponly'); + } + + if ( ! is_numeric($expire)) + { + $expire = time() - 86500; + } + else + { + $expire = ($expire > 0) ? time() + $expire : 0; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * 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[$i] = 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 = NULL; + 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 + * + * modified by ci-phpunit-test + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Loader.php new file mode 100644 index 00000000..601b0e0d --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.0-Loader.php @@ -0,0 +1,1443 @@ + 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 string $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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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_object_to_array($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 = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + 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()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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. + */ + if (is_array($_ci_vars)) + { + foreach (array_keys($_ci_vars) as $key) + { + if (strncmp($key, '_ci_', 4) === 0) + { + unset($_ci_vars[$key]); + } + } + + $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 + * + * modified by ci-phpunit-test + */ + 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// 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; + } + else + { + 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']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-CodeIgniter.php new file mode 100644 index 00000000..1d41f78d --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-CodeIgniter.php @@ -0,0 +1 @@ +../CodeIgniter.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Common.php new file mode 100644 index 00000000..158b5f52 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Common.php @@ -0,0 +1 @@ +../Common.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Input.php new file mode 100644 index 00000000..b673abf9 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Input.php @@ -0,0 +1 @@ +../Input.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Loader.php new file mode 100644 index 00000000..1019bc51 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Loader.php @@ -0,0 +1 @@ +../Loader.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Output.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Output.php new file mode 100644 index 00000000..ab1d7014 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.10-Output.php @@ -0,0 +1 @@ +../Output.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-CodeIgniter.php new file mode 100644 index 00000000..10dd984d --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-CodeIgniter.php @@ -0,0 +1,578 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method)) && strcasecmp($class, $method) === 0) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Common.php new file mode 100644 index 00000000..fddd5582 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Common.php @@ -0,0 +1,389 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class + * @param string $directory + * @param array $param + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + if ($exit_status > 125) // 125 is EXIT__AUTO_MAX + { + $exit_status = 1; // EXIT_ERROR + } + + $status_code = 500; + } + else + { + $exit_status = 1; // EXIT_ERROR + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + if (strpos(PHP_SAPI, 'cgi') === 0) + { + header('Status: '.$code.' '.$text, TRUE); + } + else + { + $server_protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); + } +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Input.php new file mode 100644 index 00000000..1549a2a6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Input.php @@ -0,0 +1,954 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) + { + if (is_array($name)) + { + // always leave 'name' in last place, as the loop will break otherwise, due to $$item + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') 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'); + } + + if ($secure === FALSE && config_item('cookie_secure') === TRUE) + { + $secure = config_item('cookie_secure'); + } + + if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE) + { + $httponly = config_item('cookie_httponly'); + } + + if ( ! is_numeric($expire)) + { + $expire = time() - 86500; + } + else + { + $expire = ($expire > 0) ? time() + $expire : 0; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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[$i] = 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Loader.php new file mode 100644 index 00000000..aeb3b5f4 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.2-Loader.php @@ -0,0 +1,1511 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function view($view, $vars = array(), $return = FALSE) + { + return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return)); + } + + // -------------------------------------------------------------------- + + /** + * Generic File Loader + * + * @param string $path File path + * @param bool $return Whether to return the file output + * @return object|string + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function vars($vars, $val = '') + { + if (is_string($vars)) + { + $vars = array($vars => $val); + } + + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) && count($vars) > 0) + { + foreach ($vars as $key => $val) + { + $this->_ci_cached_vars[$key] = $val; + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Clear Cached Variables + * + * Clears the cached variables. + * + * @return CI_Loader + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + public function helper($helpers = array()) + { + foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) + { + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // Is this a helper extension request? + $ext_helper = config_item('subclass_prefix').$helper; + $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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + */ + if (is_array($_ci_vars)) + { + foreach (array_keys($_ci_vars) as $key) + { + if (strncmp($key, '_ci_', 4) === 0) + { + unset($_ci_vars[$key]); + } + } + + $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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name); +// } + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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; + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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']); + } + } + + // -------------------------------------------------------------------- + + /** + * CI Object to Array translator + * + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. + * + * @param object $object Object data to translate + * @return array + * + * @codeCoverageIgnore + */ + protected function _ci_object_to_array($object) + { + return is_object($object) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * CI Component getter + * + * Get a reference to a specific library or model. + * + * @param string $component Component name + * @return bool + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } + + // -------------------------------------------------------------------- + + /** + * Prep filename + * + * This function prepares filenames of various items to + * make their loading more reliable. + * + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension + * @return array + * + * @codeCoverageIgnore + */ + protected function _ci_prep_filename($filename, $extension) + { + if ( ! is_array($filename)) + { + return array(strtolower(str_replace(array($extension, '.php'), '', $filename).$extension)); + } + else + { + foreach ($filename as $key => $val) + { + $filename[$key] = strtolower(str_replace(array($extension, '.php'), '', $val).$extension); + } + + return $filename; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-CodeIgniter.php new file mode 100644 index 00000000..104e0946 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method)) && strcasecmp($class, $method) === 0) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Common.php new file mode 100644 index 00000000..fddd5582 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Common.php @@ -0,0 +1,389 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class + * @param string $directory + * @param array $param + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + if ($exit_status > 125) // 125 is EXIT__AUTO_MAX + { + $exit_status = 1; // EXIT_ERROR + } + + $status_code = 500; + } + else + { + $exit_status = 1; // EXIT_ERROR + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + if (strpos(PHP_SAPI, 'cgi') === 0) + { + header('Status: '.$code.' '.$text, TRUE); + } + else + { + $server_protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); + } +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Input.php new file mode 100644 index 00000000..70768845 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Input.php @@ -0,0 +1,954 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) + { + if (is_array($name)) + { + // always leave 'name' in last place, as the loop will break otherwise, due to $$item + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') 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'); + } + + if ($secure === FALSE && config_item('cookie_secure') === TRUE) + { + $secure = config_item('cookie_secure'); + } + + if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE) + { + $httponly = config_item('cookie_httponly'); + } + + if ( ! is_numeric($expire)) + { + $expire = time() - 86500; + } + else + { + $expire = ($expire > 0) ? time() + $expire : 0; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Loader.php new file mode 100644 index 00000000..ee30ddc0 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.3-Loader.php @@ -0,0 +1,1484 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name); +// } + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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; + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 prexied with '_ci_'). + * + * @param mixed $vars + * @return array + * + * @codeCoverageIgnore + */ + protected function _ci_prepare_view_vars($vars) + { + if ( ! is_array($vars)) + { + $vars = is_object($vars) + ? get_object_vars($object) + : 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-CodeIgniter.php new file mode 100644 index 00000000..41d702bd --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method)) && strcasecmp($class, $method) === 0) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Common.php new file mode 100644 index 00000000..9aa9c42f --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class + * @param string $directory + * @param array $param + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Input.php new file mode 100644 index 00000000..2e076232 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Input.php @@ -0,0 +1,952 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Loader.php new file mode 100644 index 00000000..3b30a8d4 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.4-Loader.php @@ -0,0 +1,1483 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name); +// } + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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; + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-CodeIgniter.php new file mode 100644 index 00000000..dbeee8de --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Common.php new file mode 100644 index 00000000..2d98d1d6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class the class name being requested + * @param string $directory the directory where the class should be found + * @param mixed $param an optional argument to pass to the class constructor + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Input.php new file mode 100644 index 00000000..2e076232 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Input.php @@ -0,0 +1,952 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Loader.php new file mode 100644 index 00000000..3b30a8d4 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.5-Loader.php @@ -0,0 +1,1483 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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); + } + + // 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'; + + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + return $this->_ci_init_library($class, '', $params, $object_name); + } + } + +// log_message('debug', $class.' class already loaded. Second attempt ignored.'); +// return; + } + // 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 + * + * modified by ci-phpunit-test + */ + 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'); + } + + // Before we deem this to be a duplicate request, let's see + // if a custom object name is being supplied. If so, we'll + // return a new instance of the object + if ($object_name !== NULL) + { + $CI =& get_instance(); + if ( ! isset($CI->$object_name)) + { + 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); + } +// else +// { +// log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name); +// } + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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; + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-CodeIgniter.php new file mode 100644 index 00000000..c7a0eb57 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Common.php new file mode 100644 index 00000000..2d98d1d6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class the class name being requested + * @param string $directory the directory where the class should be found + * @param mixed $param an optional argument to pass to the class constructor + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Input.php new file mode 100644 index 00000000..2e076232 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Input.php @@ -0,0 +1,952 @@ +_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_enable_xss = (config_item('global_xss_filtering') === TRUE); + $this->_enable_csrf = (config_item('csrf_protection') === TRUE); + $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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Loader.php new file mode 100644 index 00000000..4359d162 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.6-Loader.php @@ -0,0 +1,1479 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 string $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 + * + * modified by ci-phpunit-test + */ + 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"); + } + } + 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); + } + } +// } + + $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; + $CI->$name = new $model(); + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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 + * + * modified by ci-phpunit-test + */ + 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); + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-CodeIgniter.php new file mode 100644 index 00000000..a8f999a0 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Common.php new file mode 100644 index 00000000..2d98d1d6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class the class name being requested + * @param string $directory the directory where the class should be found + * @param mixed $param an optional argument to pass to the class constructor + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Input.php new file mode 100644 index 00000000..bfcfb18e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Input.php @@ -0,0 +1,952 @@ +_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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Loader.php new file mode 100644 index 00000000..1cf542da --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Loader.php @@ -0,0 +1,1485 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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 + * + * modified by ci-phpunit-test + */ + 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); + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Output.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Output.php new file mode 100644 index 00000000..23050d72 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.7-Output.php @@ -0,0 +1,864 @@ +_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 = (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) + { + // Combine headers already sent with our batched headers + $headers = array_merge( + // We only need [x][0] from our multi-dimensional array + array_map('array_shift', $this->headers), + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-CodeIgniter.php new file mode 100644 index 00000000..d68921dd --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Common.php new file mode 100644 index 00000000..2d98d1d6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class the class name being requested + * @param string $directory the directory where the class should be found + * @param mixed $param an optional argument to pass to the class constructor + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Input.php new file mode 100644 index 00000000..bfcfb18e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Input.php @@ -0,0 +1,952 @@ +_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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Loader.php new file mode 100644 index 00000000..1cf542da --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Loader.php @@ -0,0 +1,1485 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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 + * + * modified by ci-phpunit-test + */ + 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); + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Output.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Output.php new file mode 100644 index 00000000..23050d72 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.8-Output.php @@ -0,0 +1,864 @@ +_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 = (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) + { + // Combine headers already sent with our batched headers + $headers = array_merge( + // We only need [x][0] from our multi-dimensional array + array_map('array_shift', $this->headers), + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-CodeIgniter.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-CodeIgniter.php new file mode 100644 index 00000000..c64e989b --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-CodeIgniter.php @@ -0,0 +1,581 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('BM', $BM); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('EXT', $EXT); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('CFG', $CFG); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('UNI', $UNI); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('URI', $URI); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + CIPHPUnitTestSuperGlobal::set_Global('RTR', $RTR); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('OUT', $OUT); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('SEC', $SEC); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('IN', $IN); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + CIPHPUnitTestSuperGlobal::set_Global('LANG', $LANG); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + * + * modified by ci-phpunit-test + */ + function &get_instance() + { + if (! CIPHPUnitTest::wiredesignzHmvcInstalled()) + { + return CI_Controller::get_instance(); + } + else + { + return CI::$APP; + } + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + + // ci-phpunit-test + return; + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Common.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Common.php new file mode 100644 index 00000000..2d98d1d6 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Common.php @@ -0,0 +1,386 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +// Load this file before loading "system/core/Common.php" + +/** + * Class registry + * + * @staticvar array $_classes + * + * @param string $class the class name being requested + * @param string $directory the directory where the class should be found + * @param mixed $param an optional argument to pass to the class constructor + * @param bool $reset + * @param object $obj + * + * @return object + */ +function &load_class( + $class, + $directory = 'libraries', + $param = NULL, + $reset = FALSE, + $obj = NULL +) +{ + static $_classes = array(); + + if ($reset) + { + // If Utf8 is instantiated twice, + // error "Constant UTF8_ENABLED already defined" occurs + $UTF8 = $_classes['Utf8']; + $_classes = array( + 'Utf8' => $UTF8 + ); + $obj = new stdClass(); + return $obj; + } + + // Register object directly + if ($obj) + { + is_loaded($class); + + $_classes[$class] = $obj; + return $_classes[$class]; + } + + // 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 then show_error() in order to avoid a + // self-referencing loop with the Exceptions class + set_status_header(503); + + // changed by ci-phpunit-test + $msg = 'Unable to locate the specified class: '.$class.'.php'; +// exit(5); // EXIT_UNK_CLASS + throw new CIPHPUnitTestExitException($msg); + } + + // Keep track of what we just loaded + is_loaded($class); + + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); + return $_classes[$class]; +} + +/** + * Keeps track of which libraries have been loaded. + * + * @staticvar array $_is_loaded + * + * @param string $class + * @param bool $reset + * + * @return array + */ +function &is_loaded($class = '', $reset = FALSE) +{ + static $_is_loaded = array(); + + if ($reset) + { + $_is_loaded = array(); + return $_is_loaded; + } + + if ($class !== '') + { + $_is_loaded[strtolower($class)] = $class; + } + + return $_is_loaded; +} + +function is_cli($return = null) +{ + static $_return = TRUE; + + if ($return !== null) + { + $_return = $return; + } + + return $_return; +} + +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 + } + + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShowErrorException($message, $status_code); +} + +function show_404($page = '', $log_error = TRUE) +{ + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestShow404Exception($page, 404); +} + +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); + } + } + + // Save status code in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_status = [ + 'code' => $code, + 'text' => $text, + 'redirect' => null, + ]; + + // Everything is done, so return + // added by ci-phpunit-test + if (ENVIRONMENT === 'testing') + { + return; + } + + 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'), TRUE)) + ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($server_protocol.' '.$code.' '.$text, TRUE, $code); +} + +/** + * Loads the main config.php file + * + * @staticvar array $config + * + * @param array $replace + * @param bool $reset + * + * @return array + */ +function &get_config(Array $replace = array(), $reset = FALSE) +{ + static $config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + get_config(); + return $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; +} + +/** + * Returns the specified config item + * + * @staticvar array $_config + * + * @param string $item + * @param bool $reset + * + * @return type + */ +function config_item($item, $reset = FALSE) +{ + static $_config; + + // Reset static variable + // added by ci-phpunit-test + if ($reset) + { + $config = null; + return; + } + + 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; +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Input.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Input.php new file mode 100644 index 00000000..bfcfb18e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Input.php @@ -0,0 +1,952 @@ +_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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + * @return void + * + * modified by ci-phpunit-test + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + +// setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + + // Save cookie in Output object + // added by ci-phpunit-test + $CI =& get_instance(); + $output = $CI->output; + $output->_cookies[$prefix.$name][] = [ + 'value' => $value, + 'expire' => $expire, + 'path' => $path, + 'domain' => $domain, + 'secure' => $secure, + 'httponly' => $httponly, + ]; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the IP Address + * + * Determines and validates the visitor's IP address. + * + * @return string IP address + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 = NULL; + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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; + } + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Loader.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Loader.php new file mode 100644 index 00000000..ec807650 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Loader.php @@ -0,0 +1,1487 @@ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * @codeCoverageIgnore + */ + 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) + { + $result = DB($params, $query_builder); + CIPHPUnitTestDbConnectionStore::add($result); + return $result; + } + + // 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + public function get_vars() + { + return $this->_ci_cached_vars; + } + + // -------------------------------------------------------------------- + + /** + * Helper Loader + * + * @param string|string[] $helpers Helper name(s) + * @return object + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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. + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$subdir.$class.'.php')) + { + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } + + // 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 + * + * modified by ci-phpunit-test + */ + 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); + } + } + + // Replace library in ci-phpuni-test + if (file_exists(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php')) + { + include_once(TESTPATH.'_ci_phpunit_test/replacing/libraries/'.$file_path.$library_name.'.php'); + } + else + { + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + 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 + * + * @codeCoverageIgnore + */ + protected function &_ci_get_component($component) + { + $CI =& get_instance(); + return $CI->$component; + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Output.php b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Output.php new file mode 100644 index 00000000..23050d72 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/core/old/3.1.9-Output.php @@ -0,0 +1,864 @@ +_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 = (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) + { + // Combine headers already sent with our batched headers + $headers = array_merge( + // We only need [x][0] from our multi-dimensional array + array_map('array_shift', $this->headers), + 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 + * + * modified by ci-phpunit-test + */ + 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 + * + * modified by ci-phpunit-test + */ + 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); + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/download_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/download_helper.php new file mode 100644 index 00000000..d692e687 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/download_helper.php @@ -0,0 +1,164 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter Download Helpers + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/download_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('force_download')) +{ + /** + * Force Download + * + * Generates headers that force a download to happen + * + * @param string filename + * @param mixed the data to be downloaded + * @param bool whether to try and send the actual file MIME type + * @return void + */ + function force_download($filename = '', $data = '', $set_mime = FALSE) + { + if ($filename === '' OR $data === '') + { + return; + } + elseif ($data === NULL) + { + if ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE) + { + return; + } + + $filepath = $filename; + $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename)); + $filename = end($filename); + } + else + { + $filesize = strlen($data); + } + + // Set the default MIME type to send + $mime = 'application/octet-stream'; + + $x = explode('.', $filename); + $extension = end($x); + + if ($set_mime === TRUE) + { + if (count($x) === 1 OR $extension === '') + { + /* If we're going to detect the MIME type, + * we'll need a file extension. + */ + return; + } + + // Load the mime types + $mimes =& get_mimes(); + + // Only change the default MIME if we can find one + if (isset($mimes[$extension])) + { + $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension]; + } + } + + /* It was reported that browsers on Android 2.1 (and possibly older as well) + * need to have the filename extension upper-cased in order to be able to + * download it. + * + * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/ + */ + if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) + { + $x[count($x) - 1] = strtoupper($extension); + $filename = implode('.', $x); + } + + if ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE) + { + return; + } + + if (ENVIRONMENT !== 'testing') + { + // Clean output buffer + if (ob_get_level() !== 0 && @ob_end_clean() === FALSE) + { + @ob_clean(); + } + + // Generate the server headers + header('Content-Type: '.$mime); + header('Content-Disposition: attachment; filename="'.$filename.'"'); + header('Expires: 0'); + header('Content-Transfer-Encoding: binary'); + header('Content-Length: '.$filesize); + header('Cache-Control: private, no-transform, no-store, must-revalidate'); + } + + if (ENVIRONMENT === 'testing') + { + $CI =& get_instance(); + $CI->output->set_header('Content-Type: '.$mime); + $CI->output->set_header('Content-Disposition: attachment; filename="'.$filename.'"'); + $CI->output->set_header('Expires: 0'); + $CI->output->set_header('Content-Transfer-Encoding: binary'); + $CI->output->set_header('Content-Length: '.$filesize); + $CI->output->set_header('Cache-Control: private, no-transform, no-store, must-revalidate'); + + while (ob_get_level() > 2) + { + ob_end_clean(); + } + } + + // If we have raw data - just dump it + if ($data !== NULL) + { + if (ENVIRONMENT !== 'testing') + { + exit($data); + } + else + { + echo($data); + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } + + // Flush 1MB chunks of data + while ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE) + { + echo $data; + } + + fclose($fp); + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.10-download_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.10-download_helper.php new file mode 100644 index 00000000..c4b11e09 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.10-download_helper.php @@ -0,0 +1 @@ +../download_helper.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.10-url_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.10-url_helper.php new file mode 100644 index 00000000..bf540cd1 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.10-url_helper.php @@ -0,0 +1 @@ +../url_helper.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.6-download_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.6-download_helper.php new file mode 100644 index 00000000..d692e687 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.6-download_helper.php @@ -0,0 +1,164 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter Download Helpers + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/download_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('force_download')) +{ + /** + * Force Download + * + * Generates headers that force a download to happen + * + * @param string filename + * @param mixed the data to be downloaded + * @param bool whether to try and send the actual file MIME type + * @return void + */ + function force_download($filename = '', $data = '', $set_mime = FALSE) + { + if ($filename === '' OR $data === '') + { + return; + } + elseif ($data === NULL) + { + if ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE) + { + return; + } + + $filepath = $filename; + $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename)); + $filename = end($filename); + } + else + { + $filesize = strlen($data); + } + + // Set the default MIME type to send + $mime = 'application/octet-stream'; + + $x = explode('.', $filename); + $extension = end($x); + + if ($set_mime === TRUE) + { + if (count($x) === 1 OR $extension === '') + { + /* If we're going to detect the MIME type, + * we'll need a file extension. + */ + return; + } + + // Load the mime types + $mimes =& get_mimes(); + + // Only change the default MIME if we can find one + if (isset($mimes[$extension])) + { + $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension]; + } + } + + /* It was reported that browsers on Android 2.1 (and possibly older as well) + * need to have the filename extension upper-cased in order to be able to + * download it. + * + * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/ + */ + if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) + { + $x[count($x) - 1] = strtoupper($extension); + $filename = implode('.', $x); + } + + if ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE) + { + return; + } + + if (ENVIRONMENT !== 'testing') + { + // Clean output buffer + if (ob_get_level() !== 0 && @ob_end_clean() === FALSE) + { + @ob_clean(); + } + + // Generate the server headers + header('Content-Type: '.$mime); + header('Content-Disposition: attachment; filename="'.$filename.'"'); + header('Expires: 0'); + header('Content-Transfer-Encoding: binary'); + header('Content-Length: '.$filesize); + header('Cache-Control: private, no-transform, no-store, must-revalidate'); + } + + if (ENVIRONMENT === 'testing') + { + $CI =& get_instance(); + $CI->output->set_header('Content-Type: '.$mime); + $CI->output->set_header('Content-Disposition: attachment; filename="'.$filename.'"'); + $CI->output->set_header('Expires: 0'); + $CI->output->set_header('Content-Transfer-Encoding: binary'); + $CI->output->set_header('Content-Length: '.$filesize); + $CI->output->set_header('Cache-Control: private, no-transform, no-store, must-revalidate'); + + while (ob_get_level() > 2) + { + ob_end_clean(); + } + } + + // If we have raw data - just dump it + if ($data !== NULL) + { + if (ENVIRONMENT !== 'testing') + { + exit($data); + } + else + { + echo($data); + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } + + // Flush 1MB chunks of data + while ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE) + { + echo $data; + } + + fclose($fp); + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.6-url_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.6-url_helper.php new file mode 100644 index 00000000..b794553e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.6-url_helper.php @@ -0,0 +1,82 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter URL Helpers with little modification for testing + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/url_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('redirect')) +{ + 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': + if (ENVIRONMENT !== 'testing') + { + header('Refresh:0;url='.$uri); + } + break; + default: + if (ENVIRONMENT !== 'testing') + { + header('Location: '.$uri, TRUE, $code); + } + break; + } + + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestRedirectException('Redirect to ' . $uri, $code); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.7-download_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.7-download_helper.php new file mode 100644 index 00000000..d692e687 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.7-download_helper.php @@ -0,0 +1,164 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter Download Helpers + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/download_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('force_download')) +{ + /** + * Force Download + * + * Generates headers that force a download to happen + * + * @param string filename + * @param mixed the data to be downloaded + * @param bool whether to try and send the actual file MIME type + * @return void + */ + function force_download($filename = '', $data = '', $set_mime = FALSE) + { + if ($filename === '' OR $data === '') + { + return; + } + elseif ($data === NULL) + { + if ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE) + { + return; + } + + $filepath = $filename; + $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename)); + $filename = end($filename); + } + else + { + $filesize = strlen($data); + } + + // Set the default MIME type to send + $mime = 'application/octet-stream'; + + $x = explode('.', $filename); + $extension = end($x); + + if ($set_mime === TRUE) + { + if (count($x) === 1 OR $extension === '') + { + /* If we're going to detect the MIME type, + * we'll need a file extension. + */ + return; + } + + // Load the mime types + $mimes =& get_mimes(); + + // Only change the default MIME if we can find one + if (isset($mimes[$extension])) + { + $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension]; + } + } + + /* It was reported that browsers on Android 2.1 (and possibly older as well) + * need to have the filename extension upper-cased in order to be able to + * download it. + * + * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/ + */ + if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) + { + $x[count($x) - 1] = strtoupper($extension); + $filename = implode('.', $x); + } + + if ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE) + { + return; + } + + if (ENVIRONMENT !== 'testing') + { + // Clean output buffer + if (ob_get_level() !== 0 && @ob_end_clean() === FALSE) + { + @ob_clean(); + } + + // Generate the server headers + header('Content-Type: '.$mime); + header('Content-Disposition: attachment; filename="'.$filename.'"'); + header('Expires: 0'); + header('Content-Transfer-Encoding: binary'); + header('Content-Length: '.$filesize); + header('Cache-Control: private, no-transform, no-store, must-revalidate'); + } + + if (ENVIRONMENT === 'testing') + { + $CI =& get_instance(); + $CI->output->set_header('Content-Type: '.$mime); + $CI->output->set_header('Content-Disposition: attachment; filename="'.$filename.'"'); + $CI->output->set_header('Expires: 0'); + $CI->output->set_header('Content-Transfer-Encoding: binary'); + $CI->output->set_header('Content-Length: '.$filesize); + $CI->output->set_header('Cache-Control: private, no-transform, no-store, must-revalidate'); + + while (ob_get_level() > 2) + { + ob_end_clean(); + } + } + + // If we have raw data - just dump it + if ($data !== NULL) + { + if (ENVIRONMENT !== 'testing') + { + exit($data); + } + else + { + echo($data); + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } + + // Flush 1MB chunks of data + while ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE) + { + echo $data; + } + + fclose($fp); + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.7-url_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.7-url_helper.php new file mode 100644 index 00000000..b794553e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.7-url_helper.php @@ -0,0 +1,82 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter URL Helpers with little modification for testing + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/url_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('redirect')) +{ + 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': + if (ENVIRONMENT !== 'testing') + { + header('Refresh:0;url='.$uri); + } + break; + default: + if (ENVIRONMENT !== 'testing') + { + header('Location: '.$uri, TRUE, $code); + } + break; + } + + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestRedirectException('Redirect to ' . $uri, $code); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.8-download_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.8-download_helper.php new file mode 100644 index 00000000..d692e687 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.8-download_helper.php @@ -0,0 +1,164 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter Download Helpers + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/download_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('force_download')) +{ + /** + * Force Download + * + * Generates headers that force a download to happen + * + * @param string filename + * @param mixed the data to be downloaded + * @param bool whether to try and send the actual file MIME type + * @return void + */ + function force_download($filename = '', $data = '', $set_mime = FALSE) + { + if ($filename === '' OR $data === '') + { + return; + } + elseif ($data === NULL) + { + if ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE) + { + return; + } + + $filepath = $filename; + $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename)); + $filename = end($filename); + } + else + { + $filesize = strlen($data); + } + + // Set the default MIME type to send + $mime = 'application/octet-stream'; + + $x = explode('.', $filename); + $extension = end($x); + + if ($set_mime === TRUE) + { + if (count($x) === 1 OR $extension === '') + { + /* If we're going to detect the MIME type, + * we'll need a file extension. + */ + return; + } + + // Load the mime types + $mimes =& get_mimes(); + + // Only change the default MIME if we can find one + if (isset($mimes[$extension])) + { + $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension]; + } + } + + /* It was reported that browsers on Android 2.1 (and possibly older as well) + * need to have the filename extension upper-cased in order to be able to + * download it. + * + * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/ + */ + if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) + { + $x[count($x) - 1] = strtoupper($extension); + $filename = implode('.', $x); + } + + if ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE) + { + return; + } + + if (ENVIRONMENT !== 'testing') + { + // Clean output buffer + if (ob_get_level() !== 0 && @ob_end_clean() === FALSE) + { + @ob_clean(); + } + + // Generate the server headers + header('Content-Type: '.$mime); + header('Content-Disposition: attachment; filename="'.$filename.'"'); + header('Expires: 0'); + header('Content-Transfer-Encoding: binary'); + header('Content-Length: '.$filesize); + header('Cache-Control: private, no-transform, no-store, must-revalidate'); + } + + if (ENVIRONMENT === 'testing') + { + $CI =& get_instance(); + $CI->output->set_header('Content-Type: '.$mime); + $CI->output->set_header('Content-Disposition: attachment; filename="'.$filename.'"'); + $CI->output->set_header('Expires: 0'); + $CI->output->set_header('Content-Transfer-Encoding: binary'); + $CI->output->set_header('Content-Length: '.$filesize); + $CI->output->set_header('Cache-Control: private, no-transform, no-store, must-revalidate'); + + while (ob_get_level() > 2) + { + ob_end_clean(); + } + } + + // If we have raw data - just dump it + if ($data !== NULL) + { + if (ENVIRONMENT !== 'testing') + { + exit($data); + } + else + { + echo($data); + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } + + // Flush 1MB chunks of data + while ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE) + { + echo $data; + } + + fclose($fp); + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.8-url_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.8-url_helper.php new file mode 100644 index 00000000..b794553e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.8-url_helper.php @@ -0,0 +1,82 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter URL Helpers with little modification for testing + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/url_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('redirect')) +{ + 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': + if (ENVIRONMENT !== 'testing') + { + header('Refresh:0;url='.$uri); + } + break; + default: + if (ENVIRONMENT !== 'testing') + { + header('Location: '.$uri, TRUE, $code); + } + break; + } + + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestRedirectException('Redirect to ' . $uri, $code); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.9-download_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.9-download_helper.php new file mode 100644 index 00000000..d692e687 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.9-download_helper.php @@ -0,0 +1,164 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter Download Helpers + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/download_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('force_download')) +{ + /** + * Force Download + * + * Generates headers that force a download to happen + * + * @param string filename + * @param mixed the data to be downloaded + * @param bool whether to try and send the actual file MIME type + * @return void + */ + function force_download($filename = '', $data = '', $set_mime = FALSE) + { + if ($filename === '' OR $data === '') + { + return; + } + elseif ($data === NULL) + { + if ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE) + { + return; + } + + $filepath = $filename; + $filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename)); + $filename = end($filename); + } + else + { + $filesize = strlen($data); + } + + // Set the default MIME type to send + $mime = 'application/octet-stream'; + + $x = explode('.', $filename); + $extension = end($x); + + if ($set_mime === TRUE) + { + if (count($x) === 1 OR $extension === '') + { + /* If we're going to detect the MIME type, + * we'll need a file extension. + */ + return; + } + + // Load the mime types + $mimes =& get_mimes(); + + // Only change the default MIME if we can find one + if (isset($mimes[$extension])) + { + $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension]; + } + } + + /* It was reported that browsers on Android 2.1 (and possibly older as well) + * need to have the filename extension upper-cased in order to be able to + * download it. + * + * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/ + */ + if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT'])) + { + $x[count($x) - 1] = strtoupper($extension); + $filename = implode('.', $x); + } + + if ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE) + { + return; + } + + if (ENVIRONMENT !== 'testing') + { + // Clean output buffer + if (ob_get_level() !== 0 && @ob_end_clean() === FALSE) + { + @ob_clean(); + } + + // Generate the server headers + header('Content-Type: '.$mime); + header('Content-Disposition: attachment; filename="'.$filename.'"'); + header('Expires: 0'); + header('Content-Transfer-Encoding: binary'); + header('Content-Length: '.$filesize); + header('Cache-Control: private, no-transform, no-store, must-revalidate'); + } + + if (ENVIRONMENT === 'testing') + { + $CI =& get_instance(); + $CI->output->set_header('Content-Type: '.$mime); + $CI->output->set_header('Content-Disposition: attachment; filename="'.$filename.'"'); + $CI->output->set_header('Expires: 0'); + $CI->output->set_header('Content-Transfer-Encoding: binary'); + $CI->output->set_header('Content-Length: '.$filesize); + $CI->output->set_header('Cache-Control: private, no-transform, no-store, must-revalidate'); + + while (ob_get_level() > 2) + { + ob_end_clean(); + } + } + + // If we have raw data - just dump it + if ($data !== NULL) + { + if (ENVIRONMENT !== 'testing') + { + exit($data); + } + else + { + echo($data); + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } + + // Flush 1MB chunks of data + while ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE) + { + echo $data; + } + + fclose($fp); + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + throw new CIPHPUnitTestExitException('exit() from force_download()'); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.9-url_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.9-url_helper.php new file mode 100644 index 00000000..b794553e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/old/3.1.9-url_helper.php @@ -0,0 +1,82 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter URL Helpers with little modification for testing + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/url_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('redirect')) +{ + 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': + if (ENVIRONMENT !== 'testing') + { + header('Refresh:0;url='.$uri); + } + break; + default: + if (ENVIRONMENT !== 'testing') + { + header('Location: '.$uri, TRUE, $code); + } + break; + } + + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestRedirectException('Redirect to ' . $uri, $code); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/helpers/url_helper.php b/application/tests/_ci_phpunit_test/replacing/helpers/url_helper.php new file mode 100644 index 00000000..b794553e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/helpers/url_helper.php @@ -0,0 +1,82 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +/** + * CodeIgniter URL Helpers with little modification for testing + * + * @package CodeIgniter + * @subpackage Helpers + * @category Helpers + * @author Kenji Suzuki + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/helpers/url_helper.html + */ + +// ------------------------------------------------------------------------ + +if ( ! function_exists('redirect')) +{ + 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': + if (ENVIRONMENT !== 'testing') + { + header('Refresh:0;url='.$uri); + } + break; + default: + if (ENVIRONMENT !== 'testing') + { + header('Location: '.$uri, TRUE, $code); + } + break; + } + + if (ENVIRONMENT !== 'testing') + { + exit; + } + else + { + while (ob_get_level() > 1) + { + ob_end_clean(); + } + + throw new CIPHPUnitTestRedirectException('Redirect to ' . $uri, $code); + } + } +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/Upload.php new file mode 100644 index 00000000..7e9871e1 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/Upload.php @@ -0,0 +1,1368 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + + return $new_filename; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.10-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.10-Upload.php new file mode 100644 index 00000000..04d5f543 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.10-Upload.php @@ -0,0 +1 @@ +../Upload.php \ No newline at end of file diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.2-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.2-Upload.php new file mode 100644 index 00000000..eaa66053 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.2-Upload.php @@ -0,0 +1,1360 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + else + { + return $new_filename; + } + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + // Fileinfo extension - most reliable method + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.3-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.3-Upload.php new file mode 100644 index 00000000..4640653e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.3-Upload.php @@ -0,0 +1,1370 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + else + { + return $new_filename; + } + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.4-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.4-Upload.php new file mode 100644 index 00000000..4640653e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.4-Upload.php @@ -0,0 +1,1370 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + else + { + return $new_filename; + } + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.5-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.5-Upload.php new file mode 100644 index 00000000..4640653e --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.5-Upload.php @@ -0,0 +1,1370 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + else + { + return $new_filename; + } + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.6-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.6-Upload.php new file mode 100644 index 00000000..9874e6b2 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.6-Upload.php @@ -0,0 +1,1370 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + else + { + return $new_filename; + } + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.7-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.7-Upload.php new file mode 100644 index 00000000..9600a9fe --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.7-Upload.php @@ -0,0 +1,1368 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + + return $new_filename; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.8-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.8-Upload.php new file mode 100644 index 00000000..9600a9fe --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.8-Upload.php @@ -0,0 +1,1368 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + + return $new_filename; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.9-Upload.php b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.9-Upload.php new file mode 100644 index 00000000..9600a9fe --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/libraries/old/3.1.9-Upload.php @@ -0,0 +1,1368 @@ +initialize($config, FALSE); + + $this->_mimes =& get_mimes(); + $this->_CI =& get_instance(); + + log_message('info', 'Upload Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Initialize preferences + * + * @param array $config + * @param bool $reset + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function initialize(array $config = array(), $reset = TRUE) + { + $reflection = new ReflectionClass($this); + + if ($reset === TRUE) + { + $defaults = $reflection->getDefaultProperties(); + foreach (array_keys($defaults) as $key) + { + if ($key[0] === '_') + { + continue; + } + + if (isset($config[$key])) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($config[$key]); + } + else + { + $this->$key = $config[$key]; + } + } + else + { + $this->$key = $defaults[$key]; + } + } + } + else + { + foreach ($config as $key => &$value) + { + if ($key[0] !== '_' && $reflection->hasProperty($key)) + { + if ($reflection->hasMethod('set_'.$key)) + { + $this->{'set_'.$key}($value); + } + else + { + $this->$key = $value; + } + } + } + } + + // if a file_name was provided in the config, use it instead of the user input + // supplied file name for all uploads until initialized again + $this->_file_name_override = $this->file_name; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Perform the file upload + * + * @param string $field + * @return bool + * + * modified by ci-phpunit-test + */ + public function do_upload($field = 'userfile') + { + // Is $_FILES[$field] set? If not, no reason to continue. + if (isset($_FILES[$field])) + { + $_file = $_FILES[$field]; + } + // Does the field name contain array notation? + elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) + { + $_file = $_FILES; + for ($i = 0; $i < $c; $i++) + { + // We can't track numeric iterations, only full field names are accepted + if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field])) + { + $_file = NULL; + break; + } + + $_file = $_file[$field]; + } + } + + if ( ! isset($_file)) + { + $this->set_error('upload_no_file_selected', 'debug'); + return FALSE; + } + + // Is the upload path valid? + if ( ! $this->validate_upload_path()) + { + // errors will already be set by validate_upload_path() so just return FALSE + return FALSE; + } + + // Was the file able to be uploaded? If not, determine the reason why. + if ( ! file_exists($_file['tmp_name'])) // modified by ci-phpunit-test + { + $error = isset($_file['error']) ? $_file['error'] : 4; + + switch ($error) + { + case UPLOAD_ERR_INI_SIZE: + $this->set_error('upload_file_exceeds_limit', 'info'); + break; + case UPLOAD_ERR_FORM_SIZE: + $this->set_error('upload_file_exceeds_form_limit', 'info'); + break; + case UPLOAD_ERR_PARTIAL: + $this->set_error('upload_file_partial', 'debug'); + break; + case UPLOAD_ERR_NO_FILE: + $this->set_error('upload_no_file_selected', 'debug'); + break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->set_error('upload_no_temp_directory', 'error'); + break; + case UPLOAD_ERR_CANT_WRITE: + $this->set_error('upload_unable_to_write_file', 'error'); + break; + case UPLOAD_ERR_EXTENSION: + $this->set_error('upload_stopped_by_extension', 'debug'); + break; + default: + $this->set_error('upload_no_file_selected', 'debug'); + break; + } + + return FALSE; + } + + // Set the uploaded data as class variables + $this->file_temp = $_file['tmp_name']; + $this->file_size = $_file['size']; + + // Skip MIME type detection? + if ($this->detect_mime !== FALSE) + { + $this->_file_mime_type($_file); + } + + $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); + $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); + $this->file_name = $this->_prep_filename($_file['name']); + $this->file_ext = $this->get_extension($this->file_name); + $this->client_name = $this->file_name; + + // Is the file type allowed to be uploaded? + if ( ! $this->is_allowed_filetype()) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + + // if we're overriding, let's now make sure the new name and type is allowed + if ($this->_file_name_override !== '') + { + $this->file_name = $this->_prep_filename($this->_file_name_override); + + // If no extension was provided in the file_name config item, use the uploaded one + if (strpos($this->_file_name_override, '.') === FALSE) + { + $this->file_name .= $this->file_ext; + } + else + { + // An extension was provided, let's have it! + $this->file_ext = $this->get_extension($this->_file_name_override); + } + + if ( ! $this->is_allowed_filetype(TRUE)) + { + $this->set_error('upload_invalid_filetype', 'debug'); + return FALSE; + } + } + + // Convert the file size to kilobytes + if ($this->file_size > 0) + { + $this->file_size = round($this->file_size/1024, 2); + } + + // Is the file size within the allowed maximum? + if ( ! $this->is_allowed_filesize()) + { + $this->set_error('upload_invalid_filesize', 'info'); + return FALSE; + } + + // Are the image dimensions within the allowed size? + // Note: This can fail if the server has an open_basedir restriction. + if ( ! $this->is_allowed_dimensions()) + { + $this->set_error('upload_invalid_dimensions', 'info'); + return FALSE; + } + + // Sanitize the file name for security + $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); + + // Truncate the file name if it's too long + if ($this->max_filename > 0) + { + $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); + } + + // Remove white spaces in the name + if ($this->remove_spaces === TRUE) + { + $this->file_name = preg_replace('/\s+/', '_', $this->file_name); + } + + if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) + { + // file_ext was previously lower-cased by a get_extension() call + $this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext; + } + + /* + * Validate the file name + * This function appends an number onto the end of + * the file if one with the same name already exists. + * If it returns false there was a problem. + */ + $this->orig_name = $this->file_name; + if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) + { + return FALSE; + } + + /* + * Run the file through the XSS hacking filter + * This helps prevent malicious code from being + * embedded within a file. Scripts can easily + * be disguised as images or other file types. + */ + if ($this->xss_clean && $this->do_xss_clean() === FALSE) + { + $this->set_error('upload_unable_to_write_file', 'error'); + return FALSE; + } + + /* + * Move the file to the final destination + * To deal with different server configurations + * we'll attempt to use copy() first. If that fails + * we'll use move_uploaded_file(). One of the two should + * reliably work in most environments + */ + if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) + { + if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) + { + $this->set_error('upload_destination_error', 'error'); + return FALSE; + } + } + + /* + * Set the finalized image dimensions + * This sets the image width/height (assuming the + * file was an image). We use this information + * in the "data" function. + */ + $this->set_image_properties($this->upload_path.$this->file_name); + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Finalized Data Array + * + * Returns an associative array containing all of the information + * related to the upload, allowing the developer easy access in one array. + * + * @param string $index + * @return mixed + * + * @codeCoverageIgnore + */ + public function data($index = NULL) + { + $data = array( + 'file_name' => $this->file_name, + 'file_type' => $this->file_type, + 'file_path' => $this->upload_path, + 'full_path' => $this->upload_path.$this->file_name, + 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), + 'orig_name' => $this->orig_name, + 'client_name' => $this->client_name, + 'file_ext' => $this->file_ext, + 'file_size' => $this->file_size, + 'is_image' => $this->is_image(), + 'image_width' => $this->image_width, + 'image_height' => $this->image_height, + 'image_type' => $this->image_type, + 'image_size_str' => $this->image_size_str, + ); + + if ( ! empty($index)) + { + return isset($data[$index]) ? $data[$index] : NULL; + } + + return $data; + } + + // -------------------------------------------------------------------- + + /** + * Set Upload Path + * + * @param string $path + * @return CI_Upload + */ + public function set_upload_path($path) + { + // Make sure it has a trailing slash + $this->upload_path = rtrim($path, '/').'/'; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set the file name + * + * This function takes a filename/path as input and looks for the + * existence of a file with the same name. If found, it will append a + * number to the end of the filename to avoid overwriting a pre-existing file. + * + * @param string $path + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function set_filename($path, $filename) + { + if ($this->encrypt_name === TRUE) + { + $filename = md5(uniqid(mt_rand())).$this->file_ext; + } + + if ($this->overwrite === TRUE OR ! file_exists($path.$filename)) + { + return $filename; + } + + $filename = str_replace($this->file_ext, '', $filename); + + $new_filename = ''; + for ($i = 1; $i < $this->max_filename_increment; $i++) + { + if ( ! file_exists($path.$filename.$i.$this->file_ext)) + { + $new_filename = $filename.$i.$this->file_ext; + break; + } + } + + if ($new_filename === '') + { + $this->set_error('upload_bad_filename', 'debug'); + return FALSE; + } + + return $new_filename; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * @param int $n + * @return CI_Upload + */ + public function set_max_filesize($n) + { + $this->max_size = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Size + * + * An internal alias to set_max_filesize() to help with configuration + * as initialize() will look for a set_() method ... + * + * @param int $n + * @return CI_Upload + */ + protected function set_max_size($n) + { + return $this->set_max_filesize($n); + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum File Name Length + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_max_filename($n) + { + $this->max_filename = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Width + * + * @param int $n + * @return CI_Upload + */ + public function set_max_width($n) + { + $this->max_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Maximum Image Height + * + * @param int $n + * @return CI_Upload + */ + public function set_max_height($n) + { + $this->max_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image width + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_width($n) + { + $this->min_width = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set minimum image height + * + * @param int $n + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_min_height($n) + { + $this->min_height = ($n < 0) ? 0 : (int) $n; + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Allowed File Types + * + * @param mixed $types + * @return CI_Upload + */ + public function set_allowed_types($types) + { + $this->allowed_types = (is_array($types) OR $types === '*') + ? $types + : explode('|', $types); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set Image Properties + * + * Uses GD to determine the width/height/type of image + * + * @param string $path + * @return CI_Upload + */ + public function set_image_properties($path = '') + { + if ($this->is_image() && function_exists('getimagesize')) + { + if (FALSE !== ($D = @getimagesize($path))) + { + $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); + + $this->image_width = $D[0]; + $this->image_height = $D[1]; + $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; + $this->image_size_str = $D[3]; // string containing height and width + } + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Set XSS Clean + * + * Enables the XSS flag so that the file that was uploaded + * will be run through the XSS filter. + * + * @param bool $flag + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_xss_clean($flag = FALSE) + { + $this->xss_clean = ($flag === TRUE); + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Validate the image + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_image() + { + // IE will sometimes return odd mime-types during upload, so here we just standardize all + // jpegs or pngs to the same file type. + + $png_mimes = array('image/x-png'); + $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); + + if (in_array($this->file_type, $png_mimes)) + { + $this->file_type = 'image/png'; + } + elseif (in_array($this->file_type, $jpeg_mimes)) + { + $this->file_type = 'image/jpeg'; + } + + $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); + + return in_array($this->file_type, $img_mimes, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the filetype is allowed + * + * @param bool $ignore_mime + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filetype($ignore_mime = FALSE) + { + if ($this->allowed_types === '*') + { + return TRUE; + } + + if (empty($this->allowed_types) OR ! is_array($this->allowed_types)) + { + $this->set_error('upload_no_file_types', 'debug'); + return FALSE; + } + + $ext = strtolower(ltrim($this->file_ext, '.')); + + if ( ! in_array($ext, $this->allowed_types, TRUE)) + { + return FALSE; + } + + // Images get some additional checks + if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) + { + return FALSE; + } + + if ($ignore_mime === TRUE) + { + return TRUE; + } + + if (isset($this->_mimes[$ext])) + { + return is_array($this->_mimes[$ext]) + ? in_array($this->file_type, $this->_mimes[$ext], TRUE) + : ($this->_mimes[$ext] === $this->file_type); + } + + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Verify that the file is within the allowed size + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_filesize() + { + return ($this->max_size === 0 OR $this->max_size > $this->file_size); + } + + // -------------------------------------------------------------------- + + /** + * Verify that the image is within the allowed width/height + * + * @return bool + * + * @codeCoverageIgnore + */ + public function is_allowed_dimensions() + { + if ( ! $this->is_image()) + { + return TRUE; + } + + if (function_exists('getimagesize')) + { + $D = @getimagesize($this->file_temp); + + if ($this->max_width > 0 && $D[0] > $this->max_width) + { + return FALSE; + } + + if ($this->max_height > 0 && $D[1] > $this->max_height) + { + return FALSE; + } + + if ($this->min_width > 0 && $D[0] < $this->min_width) + { + return FALSE; + } + + if ($this->min_height > 0 && $D[1] < $this->min_height) + { + return FALSE; + } + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Validate Upload Path + * + * Verifies that it is a valid upload path with proper permissions. + * + * @return bool + * + * @codeCoverageIgnore + */ + public function validate_upload_path() + { + if ($this->upload_path === '') + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if (realpath($this->upload_path) !== FALSE) + { + $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); + } + + if ( ! is_dir($this->upload_path)) + { + $this->set_error('upload_no_filepath', 'error'); + return FALSE; + } + + if ( ! is_really_writable($this->upload_path)) + { + $this->set_error('upload_not_writable', 'error'); + return FALSE; + } + + $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Extract the file extension + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + public function get_extension($filename) + { + $x = explode('.', $filename); + + if (count($x) === 1) + { + return ''; + } + + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; + } + + // -------------------------------------------------------------------- + + /** + * Limit the File Name Length + * + * @param string $filename + * @param int $length + * @return string + * + * @codeCoverageIgnore + */ + public function limit_filename_length($filename, $length) + { + if (strlen($filename) < $length) + { + return $filename; + } + + $ext = ''; + if (strpos($filename, '.') !== FALSE) + { + $parts = explode('.', $filename); + $ext = '.'.array_pop($parts); + $filename = implode('.', $parts); + } + + return substr($filename, 0, ($length - strlen($ext))).$ext; + } + + // -------------------------------------------------------------------- + + /** + * Runs the file through the XSS clean function + * + * This prevents people from embedding malicious code in their files. + * I'm not sure that it won't negatively affect certain files in unexpected ways, + * but so far I haven't found that it causes trouble. + * + * @return string + * + * @codeCoverageIgnore + */ + public function do_xss_clean() + { + $file = $this->file_temp; + + if (filesize($file) == 0) + { + return FALSE; + } + + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) + { + $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); + if ( ! empty($memory_limit[1])) + { + switch ($memory_limit[1][0]) + { + case 'g': + case 'G': + $memory_limit[0] *= 1024 * 1024 * 1024; + break; + case 'm': + case 'M': + $memory_limit[0] *= 1024 * 1024; + break; + default: + break; + } + } + + $memory_limit = (int) ceil(filesize($file) + $memory_limit[0]); + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net + } + + // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but + // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone + // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this + // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of + // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an + // attempted XSS attack. + + if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) + { + if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary + { + return FALSE; // Couldn't open the file, return FALSE + } + + $opening_bytes = fread($file, 256); + fclose($file); + + // These are known to throw IE into mime-type detection chaos + // ]/i', $opening_bytes); + } + + if (($data = @file_get_contents($file)) === FALSE) + { + return FALSE; + } + + return $this->_CI->security->xss_clean($data, TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Set an error message + * + * @param string $msg + * @return CI_Upload + * + * @codeCoverageIgnore + */ + public function set_error($msg, $log_level = 'error') + { + $this->_CI->lang->load('upload'); + + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) + { + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); + $this->error_msg[] = $msg; + log_message($log_level, $msg); + } + + return $this; + } + + // -------------------------------------------------------------------- + + /** + * Display the error message + * + * @param string $open + * @param string $close + * @return string + * + * @codeCoverageIgnore + */ + public function display_errors($open = '

', $close = '

') + { + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; + } + + // -------------------------------------------------------------------- + + /** + * Prep Filename + * + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. + * + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename + * @return string + * + * @codeCoverageIgnore + */ + protected function _prep_filename($filename) + { + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) + { + return $filename; + } + + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; + } + + // -------------------------------------------------------------------- + + /** + * File MIME type + * + * Detects the (actual) MIME type of the uploaded file, if possible. + * The input array is expected to be $_FILES[$field] + * + * @param array $file + * @return void + * + * @codeCoverageIgnore + */ + protected function _file_mime_type($file) + { + // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) + $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; + + /** + * Fileinfo extension - most reliable method + * + * Apparently XAMPP, CentOS, cPanel and who knows what + * other PHP distribution channels EXPLICITLY DISABLE + * ext/fileinfo, which is otherwise enabled by default + * since PHP 5.3 ... + */ + if (function_exists('finfo_file')) + { + $finfo = @finfo_open(FILEINFO_MIME); + if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system + { + $mime = @finfo_file($finfo, $file['tmp_name']); + finfo_close($finfo); + + /* According to the comments section of the PHP manual page, + * it is possible that this function returns an empty string + * for some files (e.g. if they don't exist in the magic MIME database) + */ + if (is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, + * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it + * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better + * than mime_content_type() as well, hence the attempts to try calling the command line with + * three different functions. + * + * Notes: + * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system + * - many system admins would disable the exec(), shell_exec(), popen() and similar functions + * due to security concerns, hence the function_usable() checks + */ + if (DIRECTORY_SEPARATOR !== '\\') + { + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; + + if (function_usable('exec')) + { + /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. + * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites + * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy + * value, which is only put to allow us to get the return status code. + */ + $mime = @exec($cmd, $mime, $return_status); + if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) + { + $mime = @shell_exec($cmd); + if (strlen($mime) > 0) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + + if (function_usable('popen')) + { + $proc = @popen($cmd, 'r'); + if (is_resource($proc)) + { + $mime = @fread($proc, 512); + @pclose($proc); + if ($mime !== FALSE) + { + $mime = explode("\n", trim($mime)); + if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) + { + $this->file_type = $matches[1]; + return; + } + } + } + } + } + + // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type']) + if (function_exists('mime_content_type')) + { + $this->file_type = @mime_content_type($file['tmp_name']); + if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string + { + return; + } + } + + $this->file_type = $file['type']; + } + +} diff --git a/application/tests/_ci_phpunit_test/replacing/make-links.sh b/application/tests/_ci_phpunit_test/replacing/make-links.sh new file mode 100644 index 00000000..de092648 --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/make-links.sh @@ -0,0 +1,23 @@ +#!/bin/sh + +usage() { + echo "Create links to state CodeIgniter version" + echo " usage: $0 " + echo " eg: $0 3.1.3" +} + +if [ $# -eq 0 ]; then + usage + exit +fi + +version="$1" + +. ../../../../bin/filelist.sh + +for i in $list +do + (cd `dirname $i` + ln -sf "../`basename $i`" "old/$version-`basename $i`" + echo "$i -> old/$version-`basename $i`") +done diff --git a/application/tests/_ci_phpunit_test/replacing/mv-current.sh b/application/tests/_ci_phpunit_test/replacing/mv-current.sh new file mode 100644 index 00000000..bff4f30a --- /dev/null +++ b/application/tests/_ci_phpunit_test/replacing/mv-current.sh @@ -0,0 +1,23 @@ +#!/bin/sh + +usage() { + echo "Move current files to \"old/\"" + echo " usage: $0 " + echo " eg: $0 3.1.3" +} + +if [ $# -eq 0 ]; then + usage + exit +fi + +version="$1" + +. ../../../../bin/filelist.sh + +for i in $list +do + (cd `dirname $i` + mv -i "`basename $i`" "old/$version-`basename $i`" + echo "$i -> old/$version-`basename $i`") +done diff --git a/application/tests/controllers/user/Admin_Test.php b/application/tests/controllers/user/Admin_Test.php new file mode 100644 index 00000000..537ad417 --- /dev/null +++ b/application/tests/controllers/user/Admin_Test.php @@ -0,0 +1,1043 @@ + [ + 'name' => 'admin_dummy_user', + 'name_alt' => 'admin_user_dummy', + 'name_unique' => 'admin_user_unique', + 'pass' => 'dummy_password', + 'pass_alt' => 'password_dummy', + 'type' => NULL + ] + ]; + + /** + * Stores the current dummy ids + * + * Only use these through reference + * + * @var array + */ + private static $_dummy_ids = [ + 'user' => NULL + ]; + + /** + * Saves the previous database errors + * + * @var array + */ + private static $_old_db_errors = []; + + /******************* + * START/END METHODS + *******************/ + /** + * Called before testing begins + * + * @return void + */ + public static function setUpBeforeClass() + { + parent::setUpBeforeClass(); + + $CI =& self::_get_ci_instance(); + $CI->load->database(); + $CI->load->model('user/user_type_model'); + + self::$_dummy_values['user']['type'] = $CI->user_type_model->get_all()[0]->id; + + // Save most recent db errors, for the first use + self::_db_errors_save(); + } + /** + * Called before a test + * + * @return void + */ + public function setUp() + { + $this->resetInstance(); + // Required to load the correct url_helper + $this->CI->load->helper('url'); + // Tests cannot work without this + self::_login_as_admin(); + // Make sure everything exists before testing + self::_dummy_user_create(); + + // Load Admin for future use + // It can't be put in a static function + $this->class_map['Admin'] = Admin::class; + } + /** + * Called after a test + * + * @return void + */ + public function tearDown() + { + parent::tearDown(); + + self::_logout(); + // Reset dummy user, in case it was updated + self::_dummy_user_reset(); + } + /** + * Called after testing ends + * + * @return void + */ + public static function tearDownAfterClass() + { + parent::tearDownAfterClass(); + + // Delete all dummies + self::_dummy_users_wipe(); + } + + /******* + * TESTS + *******/ + /** + * Test for `Admin::list_user` without being logged + * + * @return void + */ + public function test_list_user_not_logged() + { + self::_logout(); + + $this->_db_errors_save(); + + $this->request('GET', 'user/admin/list_user'); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + $this->assertRedirect('user/auth/login'); + } + /** + * Test for `Admin::list_user` + * + * @dataProvider provider_list_user + * + * @param string $with_deleted = Value to pass to $with_deleted + * @param integer $expected_count = Amount of users expected + * @return void + */ + public function test_list_user(string $with_deleted, int $expected_count) + { + $this->_db_errors_save(); + + $output = $this->request('GET', 'user/admin/list_user/'.$with_deleted); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + // Each user is in a , and so are the headers + $actual_count = substr_count($output, '')-1; + + $this->assertEquals($expected_count, $actual_count); + } + /** + * Test for `Admin::save_user` without $_POST data + * + * @dataProvider provider_save_user + * + * @param string $user_id = ID of the user to modify + * @param string $expected_title = Expected title of the page + * @return void + */ + public function test_save_user(string $user_id, string $expected_title, callable $setup) + { + $setup($user_id); + $this->CI->lang->load('MY_application'); + $expected_title = ''.$this->CI->lang->line('page_prefix').' - '.$expected_title.''; + + // First request always fails, so make sure it's not first + $this->request('GET', 'user/admin/save_user'); + + $this->_db_errors_save(); + $output = $this->request('GET', 'user/admin/save_user/'.$user_id); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + $this->assertTrue(strpos($output, $expected_title) !== FALSE); + } + /** + * Test for `Admin::save_user` with $_POST data + * + * @dataProvider provider_save_user_post + * + * @param array $post_params = Parameters to pass to $_POST + * @param boolean $error_expected = Whether or not an error is expected in `validation_errors()` + * @param boolean $redirect_expected = Whether or not a redirect is expected + * @return void + */ + public function test_save_user_post(array $post_params, bool $error_expected, bool $redirect_expected) + { + $this->_db_errors_save(); + + $this->request('POST', 'user/admin/save_user', $post_params); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + if ($error_expected) { + $this->assertNotEmpty(validation_errors()); + } else { + $this->assertEmpty(validation_errors()); + } + + if ($redirect_expected) { + $this->assertRedirect('user/admin/list_user'); + } + } + /** + * Test for `Admin::delete_user` + * + * @dataProvider provider_delete_user + * + * @param string $user_id = ID of the user to "delete" + * @param string $action = Value to pass to $action + * @param array $status = Status of the user + * @param boolean $redirect_expected = Whether a redirect is expected + * @return void + */ + public function test_delete_user(string $user_id, string $action, array $status, bool $redirect_expected) + { + $this->CI->load->model('user/user_model'); + + $user = $this->CI->user_model->with_deleted()->get($user_id); + if ($status['deleted']['pre']) { + $this->assertNull($user); + } else { + $this->assertTrue((int)$user->archive == (int)$status['archived']['pre']); + } + + $this->_db_errors_save(); + + $this->request('GET', "user/admin/delete_user/{$user_id}/{$action}"); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + $user = $this->CI->user_model->with_deleted()->get($user_id); + if ($status['deleted']['post']) { + $this->assertNull($user); + } else { + $this->assertTrue((int)$user->archive == (int)$status['archived']['post']); + } + if ($redirect_expected) { + $this->assertRedirect('user/admin/list_user'); + } + } + /** + * Test for `Admin::reactivate_user` + * + * @dataProvider provider_reactivate_user + * + * @param integer $user_id = ID of the user to reactivate + * @param boolean $redirect_to_index = Whether the method redirects to index or to add + * @return void + */ + public function test_reactivate_user(int $user_id, bool $redirect_to_index) + { + $this->_db_errors_save(); + + $this->request('GET', "user/admin/reactivate_user/{$user_id}"); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + $target = 'user/admin/'; + if ($redirect_to_index) { + $target .= 'list_user'; + } else { + $target .= "save_user/{$user_id}"; + } + + $this->assertRedirect($target); + } + /** + * Test for `Admin::password_change_user` without $_POST data + * + * @dataProvider provider_password_change_user + * + * @param integer $user_id = ID of the user + * @param boolean $redirect_expected = Whether a redirect is expected + * @return void + */ + public function test_password_change_user(int $user_id, bool $redirect_expected) + { + $this->CI->lang->load('MY_application'); + + $this->_db_errors_save(); + + $output = $this->request('GET', "user/admin/password_change_user/{$user_id}"); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + if ($redirect_expected) { + $this->assertRedirect('user/admin/list_user'); + } else { + $this->assertContains($this->CI->lang->line('title_user_password_reset'), $output); + } + } + /** + * Test for `Admin::password_change_user` with $_POST data + * + * @dataProvider provider_password_change_user_post + * + * @param array $post_params = Parameters to pass to $_POST + * @param boolean $error_expected = Whether an error is expected + * @param boolean $redirect_expected = Whether a redirect is expected + * @return void + */ + public function test_password_change_user_post(array $post_params, bool $error_expected, bool $redirect_expected) + { + $this->_db_errors_save(); + + $this->request('POST', "user/admin/password_change_user/{$post_params['id']}", $post_params); + + $this->assertFalse( + $this->_db_errors_diff(), + 'One or more error occured in an SQL statement' + ); + + if ($error_expected) { + $this->assertNotEmpty(validation_errors()); + } + if ($redirect_expected) { + $this->assertRedirect('user/admin/list_user'); + } + } + /** + * Test for `Admin::cb_not_null_user` + * + * @dataProvider provider_not_null_user + * + * @param integer $user_id = ID of the user to test + * @param boolean $expected_result = Expected result from the call + * @return void + */ + public function test_not_null_user(int $user_id, bool $expected_result) + { + $this->assertSame($expected_result, $this->Admin->cb_not_null_user($user_id)); + } + /** + * Test for `Admin::cb_not_null_user_type` + * + * @dataProvider provider_not_null_user_type + * + * @param integer $user_type = Type of the user to test + * @param boolean $expected_result = Expected result from the call + * @return void + */ + public function test_not_null_user_type(int $user_type, bool $expected_result) + { + $this->assertSame($expected_result, $this->Admin->cb_not_null_user_type($user_type)); + } + + /*********** + * PROVIDERS + ***********/ + /** + * Provider for `test_list_user` + * + * @return array + */ + public function provider_list_user() : array + { + self::_dummy_user_create(); + $this->resetInstance(); + $this->CI->load->database(); + $this->CI->load->model('user/user_model'); + + $data = []; + + $data['none_hide'] = [ + '', + $this->CI->user_model->count_by(['archive' => 0]) + ]; + + $data['hide'] = [ + '0', + $this->CI->user_model->count_by(['archive' => 0]) + ]; + + $data['show'] = [ + '1', + $this->CI->user_model->with_deleted()->count_all() + ]; + + return $data; + } + /** + * Provider for `test_save_user` + * + * @return array + */ + public function provider_save_user() : array + { + $this->resetInstance(); + $user_id =& self::_dummy_user_create(); + $this->CI->lang->load('../../modules/user/language/french/MY_user'); + + $data = []; + + $data['new_none'] = [ + '', + $this->CI->lang->line('title_user_new'), + function() { } + ]; + + $data['new_0'] = [ + '0', + $this->CI->lang->line('title_user_new'), + function() { } + ]; + + $data['update_active'] = [ + (string)$user_id, + $this->CI->lang->line('title_user_update'), + function($user_id) { + $CI =& self::_get_ci_instance(); + $CI->load->model('user/user_model'); + + $CI->user_model->update($user_id, ['archive' => 1]); + } + ]; + + return $data; + } + /** + * Provider for `test_save_user_post` + * + * @return array + */ + public function provider_save_user_post() : array + { + $this->resetInstance(); + $this->CI->load->model(['user/user_model', 'user/user_type_model']); + $this->CI->load->config('../modules/user/config/MY_user_config'); + + $user_id =& self::_dummy_user_create(); + $user_name = self::$_dummy_values['user']['name_alt']; + $user_name_unique = self::$_dummy_values['user']['name_unique']; + $user_type = self::$_dummy_values['user']['type']; + $user_pass = self::$_dummy_values['user']['pass']; + + $data = []; + + $data['no_error_add'] = [ + [ + 'id' => 0, + 'user_name' => $user_name_unique, + 'user_usertype' => $user_type, + 'user_password' => $user_pass, + 'user_password_again' => $user_pass + ], + FALSE, + TRUE + ]; + + $data['no_error_update'] = [ + [ + 'save' => 1, + 'id' => &$user_id, + 'user_name' => $user_name, + 'user_usertype' => $user_type + ], + FALSE, + TRUE + ]; + + $bad_id = $this->CI->user_model->get_next_id()+100; + $data['error_not_exist'] = [ + [ + 'id' => $bad_id, + 'user_name' => $user_name, + 'user_usertype' => $user_type + ], + TRUE, + FALSE + ]; + + $data['error_no_name'] = [ + [ + 'id' => &$user_id, + 'user_usertype' => $user_type + ], + TRUE, + FALSE + ]; + + $name_short = substr($user_name, 0, $this->CI->config->item('username_min_length')-1); + $data['error_name_short'] = [ + [ + 'id' => &$user_id, + 'user_name' => $name_short, + 'user_usertype' => $user_type + ], + TRUE, + FALSE + ]; + + $repeat_count = ceil($this->CI->config->item('username_max_length') / strlen($user_name)) + 1; + $name_long = str_repeat($user_name, $repeat_count); + $data['error_name_long'] = [ + [ + 'id' => &$user_id, + 'user_name' => $name_long, + 'user_usertype' => $user_type + ], + TRUE, + FALSE + ]; + + $pass_short = substr($user_pass, 0, $this->CI->config->item('password_min_length')-1); + $data['error_pass_short'] = [ + [ + 'id' => 0, + 'user_name' => $user_name, + 'user_usertype' => $user_type, + 'user_password' => $pass_short, + 'user_password_again' => $pass_short + ], + TRUE, + FALSE + ]; + + $repeat_count = ceil($this->CI->config->item('password_max_length') / strlen($user_pass)) + 1; + $pass_long = str_repeat($user_pass, $repeat_count); + $data['error_pass_long'] = [ + [ + 'id' => 0, + 'user_name' => $user_name, + 'user_usertype' => $user_type, + 'user_password' => $pass_long, + 'user_password_again' => $pass_long + ], + TRUE, + FALSE + ]; + + $data['error_no_type'] = [ + [ + 'id' => &$user_id, + 'user_name' => $user_name + ], + TRUE, + FALSE + ]; + + $bad_type = $this->CI->user_type_model->get_next_id()+100; + $data['error_type_not_exist'] = [ + [ + 'id' => &$user_id, + 'user_name' => $user_name, + 'user_usertype' => $bad_type + ], + TRUE, + FALSE + ]; + + $data['error_no_password'] = [ + [ + 'id' => 0, + 'user_name' => $user_name, + 'user_usertype' => $user_type + ], + TRUE, + FALSE + ]; + + $data['error_passwords_not_match'] = [ + [ + 'id' => 0, + 'user_name' => $user_name, + 'user_usertype' => $user_type, + 'user_password' => $user_pass, + 'user_password_again' => $user_pass.'_wrong' + ], + TRUE, + FALSE + ]; + + return $data; + } + /** + * Provider for `test_delete_user` + * + * @return array + */ + public function provider_delete_user() : array + { + $this->resetInstance(); + $this->CI->load->model('user/user_model'); + $user_id =& self::_dummy_user_create(); + + $data = []; + + $bad_id = $this->CI->user_model->get_next_id()+100; + $data['not_exist'] = [ + (string)$bad_id, + '', + [ + 'deleted' => [ + 'pre' => TRUE, + 'post' => TRUE + ] + ], + TRUE + ]; + + $data['display'] = [ + &$user_id, + '', + [ + 'deleted' => [ + 'pre' => FALSE, + 'post' => FALSE + ], + 'archived' => [ + 'pre' => FALSE, + 'post' => FALSE + ] + ], + FALSE + ]; + + $data['deactivate'] = [ + &$user_id, + '1', + [ + 'deleted' => [ + 'pre' => FALSE, + 'post' => FALSE + ], + 'archived' => [ + 'pre' => FALSE, + 'post' => TRUE + ] + ], + TRUE + ]; + + $data['delete'] = [ + &$user_id, + '2', + [ + 'deleted' => [ + 'pre' => FALSE, + 'post' => TRUE + ], + 'archived' => [ + 'pre' => FALSE + ] + ], + TRUE + ]; + + $data['unknown'] = [ + &$user_id, + '-1', + [ + 'deleted' => [ + 'pre' => FALSE, + 'post' => FALSE + ], + 'archived' => [ + 'pre' => FALSE, + 'post' => FALSE + ] + ], + TRUE + ]; + + return $data; + } + /** + * Provider for `test_reactivate_user` + * + * @return array + */ + public function provider_reactivate_user() : array + { + $this->resetInstance(); + $this->CI->load->model('user/user_model'); + $user_id =& self::_dummy_user_create(); + + $data = []; + + $data['no_error'] = [ + &$user_id, + FALSE + ]; + + $bad_id = $this->CI->user_model->get_next_id()+100; + $data['not_exist'] = [ + $bad_id, + TRUE + ]; + + return $data; + } + /** + * Provider for `test_password_change_user` + * + * @return array + */ + public function provider_password_change_user() : array + { + $this->resetInstance(); + $this->CI->load->model('user/user_model'); + $user_id =& self::_dummy_user_create(); + + $data = []; + + $bad_id = $this->CI->user_model->get_next_id()+100; + $data['not_exist'] = [ + $bad_id, + TRUE + ]; + + $data['no_error'] = [ + &$user_id, + FALSE + ]; + + return $data; + } + /** + * Provider for `test_password_change_user_post` + * + * @return array + */ + public function provider_password_change_user_post() : array + { + $this->resetInstance(); + $this->CI->load->model('user/user_model'); + $this->CI->load->config('../modules/user/config/MY_user_config'); + + $user_id =& self::_dummy_user_create(); + $user_pass = self::$_dummy_values['user']['pass_alt']; + + $data = []; + + $data['no_error'] = [ + [ + 'id' => &$user_id, + 'user_password_new' => $user_pass, + 'user_password_again' => $user_pass + ], + FALSE, + TRUE + ]; + + $bad_id = $this->CI->user_model->get_next_id()+100; + $data['not_exist'] = [ + [ + 'id' => $bad_id, + 'user_password_new' => $user_pass, + 'user_password_again' => $user_pass + ], + TRUE, + TRUE + ]; + + $data['passwords_not_match'] = [ + [ + 'id' => &$user_id, + 'user_password_new' => $user_pass, + 'user_password_again' => $user_pass.'_wrong' + ], + TRUE, + FALSE + ]; + + $pass_short = substr($user_pass, 0, $this->CI->config->item('password_min_length')-1); + $data['password_short'] = [ + [ + 'id' => &$user_id, + 'user_password_new' => $pass_short, + 'user_password_again' => $pass_short + ], + TRUE, + FALSE + ]; + + $repeat_count = ceil($this->CI->config->item('password_max_length') / strlen($user_pass)) + 1; + $pass_long = str_repeat($user_pass, $repeat_count); + $data['password_long'] = [ + [ + 'id' => &$user_id, + 'user_password_new' => $pass_long, + 'user_password_again' => $pass_long + ], + TRUE, + FALSE + ]; + + return $data; + } + /** + * Provider for `test_not_null_user` + * + * @return array + */ + public function provider_not_null_user() : array + { + $this->resetInstance(); + $this->CI->load->model('user/user_model'); + $user_id =& self::_dummy_user_create(); + + $data = []; + + $data['exists'] = [ + &$user_id, + TRUE + ]; + + $bad_id = $this->CI->user_model->get_next_id()+100; + $data['not_exist'] = [ + $bad_id, + FALSE + ]; + + $data['zero'] = [ + 0, + TRUE + ]; + + return $data; + } + /** + * Provider for `test_not_null_user_type` + * + * @return array + */ + public function provider_not_null_user_type() : array + { + $this->resetInstance(); + $this->CI->load->model('user/user_type_model'); + $user_type = self::$_dummy_values['user']['type']; + + $data = []; + + $data['exists'] = [ + $user_type, + TRUE + ]; + + $bad_type = $this->CI->user_type_model->get_next_id()+100; + $data['not_exist'] = [ + $bad_type, + FALSE + ]; + + return $data; + } + + /************** + * MISC METHODS + **************/ + /** + * Tricks the server to think there is an admin logged in + * + * @return void + */ + private static function _login_as_admin() + { + $_SESSION['logged_in'] = TRUE; + // We can't know the current configuration for admin access, so we max it + $_SESSION['user_access'] = PHP_INT_MAX; + $_SESSION['user_id'] = 0; + } + /** + * Tricks the server to think there is nobody logged in + * + * @return void + */ + private static function _logout() + { + $_SESSION = []; + session_reset(); + session_unset(); + } + + /** + * Gets the CI instance and creates it if required + * + * @return CI_Controller + */ + private static function &_get_ci_instance() + { + $CI =& get_instance(); + if($CI instanceof CIPHPUnitTestNullCodeIgniter) { + CIPHPUnitTest::createCodeIgniterInstance(); + $CI =& get_instance(); + } + return $CI; + } + + /** + * Creates a dummy user + * + * @return integer = ID of the dummy user + */ + private static function &_dummy_user_create() : int + { + // Make sure CI is initialized + $CI =& self::_get_ci_instance(); + $CI->load->model(['user/user_model', 'user/user_type_model']); + + // Only create user if it does not exist + $user = $CI->user_model->with_deleted()->get(self::$_dummy_ids['user']); + if (is_null($user)) { + // Load auth config, for password encryption + $CI->load->config('../modules/user/config/MY_user_config'); + $dummy_values =& self::$_dummy_values['user']; + + // While we're at it, make sure the user type exists + if (is_null($CI->user_type_model->get($dummy_values['type']))) { + $dummy_values['type'] = $CI->user_type_model->get_all()[0]->id; + } + + // Create the user + $user = array( + 'fk_user_type' => $dummy_values['type'], + 'username' => $dummy_values['name'], + 'password' => password_hash($dummy_values['pass'], $CI->config->item('password_hash_algorithm')) + ); + + self::$_dummy_ids['user'] = $CI->user_model->insert($user); + } + + return self::$_dummy_ids['user']; + } + /** + * Resets the current dummy user + * + * @return void + */ + private static function _dummy_user_reset() + { + $CI =& self::_get_ci_instance(); + $CI->load->model('user/user_model'); + + $user = $CI->user_model->with_deleted()->get(self::$_dummy_ids['user']); + if (is_null($user)) { + // Can't reset what does not exist + self::_dummy_user_create(); + } else { + $CI->load->config('../modules/user/config/MY_user_config'); + $dummy_values =& self::$_dummy_values['user']; + + // Create the user + $user = array( + 'fk_user_type' => $dummy_values['type'], + 'username' => $dummy_values['name'], + 'password' => password_hash($dummy_values['pass'], $CI->config->item('password_hash_algorithm')), + 'archive' => 0 + ); + + $CI->user_model->update(self::$_dummy_ids['user'], $user); + } + } + /** + * Deletes all possible dummy users. + * + * @return void + */ + private static function _dummy_users_wipe() + { + $CI =& self::_get_ci_instance(); + $CI->load->model('user/user_model'); + + $dummy_values = [ + self::$_dummy_values['user']['name'], + self::$_dummy_values['user']['name_alt'], + self::$_dummy_values['user']['name_unique'], + '' + ]; + + foreach ($dummy_values as $value) { + // Fetch users + $users = $CI->user_model->with_deleted()->get_many_by(['username' => $value]); + foreach ($users as $user) { + // Delete user + $CI->user_model->delete($user->id, TRUE); + } + } + } + + /** + * Saves most recent database errors. + * + * Uses user_model and user_type_model + * + * @return void + */ + private static function _db_errors_save() + { + $CI =& self::_get_ci_instance(); + $CI->load->model([ + 'user/user_model', + 'user/user_type_model' + ]); + + self::$_old_db_errors['user_model'] = $CI->user_model->_database->error(); + self::$_old_db_errors['user_type_model'] = $CI->user_type_model->_database->error(); + } + /** + * Compares the saved database errors to the most recent ones. + * + * @return boolean = FALSE if the error is the same as before + */ + private static function _db_errors_diff() : bool + { + $CI =& self::_get_ci_instance(); + $CI->load->model([ + 'user/user_model', + 'user/user_type_model' + ]); + + return self::$_old_db_errors['user_model'] != $CI->user_model->_database->error() || + self::$_old_db_errors['user_type_model'] != $CI->user_type_model->_database->error(); + } +} diff --git a/application/tests/controllers/welcome/Welcome_test.php b/application/tests/controllers/welcome/Welcome_test.php new file mode 100644 index 00000000..8f925de3 --- /dev/null +++ b/application/tests/controllers/welcome/Welcome_test.php @@ -0,0 +1,35 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class Welcome_test extends TestCase +{ + public function test_index() + { + $output = $this->request('GET', 'welcome/index'); + $this->assertContains('

Welcome to CodeIgniter with HMVC !

', $output); + } + + public function test_method_404() + { + $this->request('GET', 'welcome/method_not_exist'); + $this->assertResponseCode(404); + } + + public function test_APPPATH() + { + $actual = realpath(APPPATH); + $expected = realpath(__DIR__ . '/../../..'); + $this->assertEquals( + $expected, + $actual, + 'Your APPPATH seems to be wrong. Check your $application_folder in tests/Bootstrap.php' + ); + } +} diff --git a/application/tests/helpers/.gitkeep b/application/tests/helpers/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/application/tests/hooks/.gitkeep b/application/tests/hooks/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/application/tests/libraries/.gitkeep b/application/tests/libraries/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/application/tests/mocks/autoloader.php b/application/tests/mocks/autoloader.php new file mode 100644 index 00000000..f6b2cfd0 --- /dev/null +++ b/application/tests/mocks/autoloader.php @@ -0,0 +1,121 @@ + + * @license MIT License + * @copyright 2015 Kenji Suzuki + * @link https://github.com/kenjis/ci-phpunit-test + */ + +class Mock_Libraries_Email +{ + private $data = []; + + /** + * @var bool return value of send() + */ + public $return_send = TRUE; + + public function initialize() + { + + } + + public function from($from) + { + $this->data['from'] = $from; + } + + public function to($to) + { + $this->data['to'] = $to; + } + + public function bcc($bcc) + { + $this->data['bcc'] = $bcc; + } + + public function subject($subject) + { + $this->data['subject'] = $subject; + } + + public function message($message) + { + $this->data['message'] = $message; + } + + public function send() + { + return $this->return_send; + } + + public function _get_data() + { + return $this->data; + } +} diff --git a/application/tests/models/.gitkeep b/application/tests/models/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/application/tests/phpunit.xml b/application/tests/phpunit.xml new file mode 100644 index 00000000..5892df8a --- /dev/null +++ b/application/tests/phpunit.xml @@ -0,0 +1,35 @@ + + + + ../modules/**/tests/ + + + ./ + ./_ci_phpunit_test/ + + + + + ../controllers + ../models + ../views + ../libraries + ../helpers + ../hooks + ../modules/**/controllers + ../modules/**/models + ../modules/**/views + ../modules/**/libraries + ../modules/**/helpers + ../modules/**/hooks + + + + + + + + diff --git a/application/third_party/MX/Base.php b/application/third_party/MX/Base.php new file mode 100644 index 00000000..3ba27d4b --- /dev/null +++ b/application/third_party/MX/Base.php @@ -0,0 +1,70 @@ +is_loaded, true)) { + return $this->item($file); + } + + $_module or $_module = CI::$APP->router->fetch_module(); + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $file) = Modules::find($file, $_module, 'config/'); + } else { + [$path, $file] = Modules::find($file, $_module, 'config/'); + } + + if ($path === false) { + parent::load($file, $use_sections, $fail_gracefully); + return $this->item($file); + } + + if ($config = Modules::load_file($file, $path, 'config')) { + // reference to the config array + $current_config =& $this->config; + + if ($use_sections === true) { + if (isset($current_config[$file])) { + $current_config[$file] = array_merge($current_config[$file], $config); + } else { + $current_config[$file] = $config; + } + } else { + $current_config = array_merge($current_config, $config); + } + + $this->is_loaded[] = $file; + unset($config); + return $this->item($file); + } + } +} diff --git a/application/third_party/MX/Controller.php b/application/third_party/MX/Controller.php new file mode 100644 index 00000000..5535aa07 --- /dev/null +++ b/application/third_party/MX/Controller.php @@ -0,0 +1,75 @@ +config->item('controller_suffix'), '', get_class($this)); + log_message('debug', $class.' MX_Controller Initialized'); + Modules::$registry[strtolower($class)] = $this; + + // copy a loader instance and initialize + $this->load = clone load_class('Loader'); + $this->load->initialize($this); + + // autoload module items + $this->load->_autoloader($this->autoload); + } + + /** + * [__get description] + * + * @method __get + * + * @param [type] $class [description] + * + * @return [type] [description] + */ + public function __get($class) + { + return CI::$APP->$class; + } +} diff --git a/application/third_party/MX/Lang.php b/application/third_party/MX/Lang.php new file mode 100644 index 00000000..5ac6cae5 --- /dev/null +++ b/application/third_party/MX/Lang.php @@ -0,0 +1,96 @@ +load($_lang); + } + return $this->language; + } + + $deft_lang = CI::$APP->config->item('language'); + $idiom = ($lang === '') ? $deft_lang : $lang; + + if (in_array($langfile.'_lang'.EXT, $this->is_loaded, true)) { + return $this->language; + } + + $_module or $_module = CI::$APP->router->fetch_module(); + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $_langfile) = Modules::find($langfile.'_lang', $_module, 'language/'.$idiom.'/'); + } else { + [$path, $_langfile] = Modules::find($langfile.'_lang', $_module, 'language/'.$idiom.'/'); + } + + if ($path === false) { + if ($lang = parent::load($langfile, $lang, $return, $add_suffix, $alt_path)) { + return $lang; + } + } else { + if ($lang = Modules::load_file($_langfile, $path, 'lang')) { + if ($return) { + return $lang; + } + $this->language = array_merge($this->language, $lang); + $this->is_loaded[] = $langfile.'_lang'.EXT; + unset($lang); + } + } + + return $this->language; + } +} diff --git a/application/third_party/MX/Loader.php b/application/third_party/MX/Loader.php new file mode 100644 index 00000000..fd1f904a --- /dev/null +++ b/application/third_party/MX/Loader.php @@ -0,0 +1,713 @@ +_module = CI::$APP->router->fetch_module(); + + if ($controller instanceof MX_Controller) { + // reference to the module controller + $this->controller = $controller; + + // references to ci loader variables + foreach (get_class_vars('CI_Loader') as $var => $val) { + if ($var !== '_ci_ob_level') { + $this->$var =& CI::$APP->load->$var; + } + } + } else { + parent::initialize(); + + // autoload module items + $this->_autoloader([]); + } + + // add this module path to the loader variables + $this->_add_module_paths($this->_module); + } + + /** + * [Add a module path loader variables] + * + * @method _add_module_paths + * + * @param string $module [description] + */ + public function _add_module_paths($module = '') + { + if (empty($module)) { + return; + } + + foreach (Modules::$locations as $location => $offset) { + // only add a module path if it exists + if (is_dir($module_path = $location.$module.'/') && ! in_array($module_path, $this->_ci_model_paths)) { + array_unshift($this->_ci_model_paths, $module_path); + } + } + } + + /** + * [Load a module config file] + * + * @method config + * + * @param [type] $file [description] + * @param boolean $use_sections [description] + * @param boolean $fail_gracefully [description] + * + * @return [type] [description] + */ + public function config($file, $use_sections = false, $fail_gracefully = false) + { + return CI::$APP->config->load($file, $use_sections, $fail_gracefully, $this->_module); + } + + /** + * [Load the database drivers] + * + * @method database + * + * @param string $params [description] + * @param boolean $return [description] + * @param [type] $query_builder [description] + * + * @return [type] [description] + */ + public function database($params = '', $return = false, $query_builder = null) + { + if ($return === false && $query_builder === null && + isset(CI::$APP->db) && is_object(CI::$APP->db) && ! empty(CI::$APP->db->conn_id)) { + return false; + } + + require_once BASEPATH.'database/DB'.EXT; + + if ($return === true) { + return DB($params, $query_builder); + } + + CI::$APP->db = DB($params, $query_builder); + + return $this; + } + + /** + * [Load a module helper] + * + * @method helper + * + * @param array $helper [description] + * + * @return [type] [description] + */ + public function helper($helper = []) + { + if (is_array($helper)) { + return $this->helpers($helper); + } + + if (isset($this->_ci_helpers[$helper])) { + return; + } + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $_helper) = Modules::find($helper.'_helper', $this->_module, 'helpers/'); + } else { + [$path, $_helper] = Modules::find($helper.'_helper', $this->_module, 'helpers/'); + } + + if ($path === false) { + return parent::helper($helper); + } + + Modules::load_file($_helper, $path); + $this->_ci_helpers[$_helper] = true; + return $this; + } + + /** + * [Load an array of helpers] + * + * @method helpers + * + * @param array $helpers [description] + * + * @return [type] [description] + */ + public function helpers($helpers = []) + { + foreach ($helpers as $_helper) { + $this->helper($_helper); + } + return $this; + } + + /** + * [Load a module language file] + * + * @method language + * + * @param [type] $langfile [description] + * @param string $idiom [description] + * @param boolean $return [description] + * @param boolean $add_suffix [description] + * @param string $alt_path [description] + * + * @return [type] [description] + */ + public function language($langfile, $idiom = '', $return = false, $add_suffix = true, $alt_path = '') + { + CI::$APP->lang->load($langfile, $idiom, $return, $add_suffix, $alt_path, $this->_module); + return $this; + } + + /** + * [languages description] + * + * @method languages + * + * @param [type] $languages [description] + * + * @return [type] [description] + */ + public function languages($languages) + { + foreach ($languages as $_language) { + $this->language($_language); + } + return $this; + } + + /** + * [Load a module library] + * + * @method library + * + * @param [type] $library [description] + * @param [type] $params [description] + * @param [type] $object_name [description] + * + * @return [type] [description] + */ + public function library($library, $params = null, $object_name = null) + { + if (is_array($library)) { + return $this->libraries($library); + } + + $class = strtolower(basename($library)); + + if (isset($this->_ci_classes[$class]) && $_alias = $this->_ci_classes[$class]) { + return $this; + } + + ($_alias = strtolower($object_name)) or $_alias = $class; + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $_library) = Modules::find($library, $this->_module, 'libraries/'); + } else { + [$path, $_library] = Modules::find($library, $this->_module, 'libraries/'); + } + + // load library config file as params + if ($params === null) { + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path2, $file) = Modules::find($_alias, $this->_module, 'config/'); + } else { + [$path2, $file] = Modules::find($_alias, $this->_module, 'config/'); + } + $path2 && $params = Modules::load_file($file, $path2, 'config'); + } + + if ($path === false) { + $this->_ci_load_library($library, $params, $object_name); + } else { + Modules::load_file($_library, $path); + + $library = ucfirst($_library); + CI::$APP->$_alias = new $library($params); + + $this->_ci_classes[$class] = $_alias; + } + return $this; + } + + /** + * [Load an array of libraries] + * + * @method libraries + * + * @param [type] $libraries [description] + * + * @return [type] [description] + */ + public function libraries($libraries) + { + foreach ($libraries as $library => $alias) { + is_int($library) ? $this->library($alias) : $this->library($library, null, $alias); + } + return $this; + } + + /** + * [Load a module model] + * + * @method model + * + * @param [type] $model [description] + * @param [type] $object_name [description] + * @param boolean $connect [description] + * + * @return [type] [description] + */ + public function model($model, $object_name = null, $connect = false) + { + if (is_array($model)) { + return $this->models($model); + } + + ($_alias = $object_name) or $_alias = basename($model); + + if (in_array($_alias, $this->_ci_models, true)) { + return $this; + } + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + // check module + list($path, $_model) = Modules::find(strtolower($model), $this->_module, 'models/'); + } else { + [$path, $_model] = Modules::find(strtolower($model), $this->_module, 'models/'); + } + + if ($path === false) { + // check application & packages + parent::model($model, $object_name, $connect); + } else { + class_exists('CI_Model', false) or load_class('Model', 'core'); + + if ($connect !== false && ! class_exists('CI_DB', false)) { + if ($connect === true) { + $connect = ''; + } + $this->database($connect, false, true); + } + + Modules::load_file($_model, $path); + + $model = ucfirst($_model); + CI::$APP->$_alias = new $model(); + + $this->_ci_models[] = $_alias; + } + return $this; + } + + /** + * [Load an array of models] + * + * @method models + * + * @param [type] $models [description] + * + * @return [type] [description] + */ + public function models($models) + { + foreach ($models as $model => $alias) { + is_int($model) ? $this->model($alias) : $this->model($model, $alias); + } + return $this; + } + + /** + * [Load a module controller] + * + * @method module + * + * @param [type] $module [description] + * @param [type] $params [description] + * + * @return [type] [description] + */ + public function module($module, $params = null) + { + if (is_array($module)) { + return $this->modules($module); + } + + $_alias = strtolower(basename($module)); + CI::$APP->$_alias = Modules::load([$module => $params]); + return $this; + } + + /** + * [Load an array of controllers] + * + * @method modules + * + * @param [type] $modules [description] + * + * @return [type] [description] + */ + public function modules($modules) + { + foreach ($modules as $_module) { + $this->module($_module); + } + return $this; + } + + /** + * [Load a module plugin] + * + * @method plugin + * + * @param [type] $plugin [description] + * + * @return [type] [description] + */ + public function plugin($plugin) + { + if (is_array($plugin)) { + return $this->plugins($plugin); + } + + if (isset($this->_ci_plugins[$plugin])) { + return $this; + } + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $_plugin) = Modules::find($plugin.'_pi', $this->_module, 'plugins/'); + } else { + [$path, $_plugin] = Modules::find($plugin.'_pi', $this->_module, 'plugins/'); + } + + if ($path === false && ! is_file($_plugin = APPPATH.'plugins/'.$_plugin.EXT)) { + show_error("Unable to locate the plugin file: {$_plugin}"); + } + + Modules::load_file($_plugin, $path); + $this->_ci_plugins[$plugin] = true; + return $this; + } + + /** + * [Load an array of plugins] + * + * @method plugins + * + * @param [type] $plugins [description] + * + * @return [type] [description] + */ + public function plugins($plugins) + { + foreach ($plugins as $_plugin) { + $this->plugin($_plugin); + } + return $this; + } + + /** + * [Load a module view] + * + * @method view + * + * @param [type] $view [description] + * @param array $vars [description] + * @param boolean $return [description] + * + * @return [type] [description] + */ + public function view($view, $vars = [], $return = false) + { + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $_view) = Modules::find($view, $this->_module, 'views/'); + } else { + [$path, $_view] = Modules::find($view, $this->_module, 'views/'); + } + + if ($path != false) { + $this->_ci_view_paths = [$path => true] + $this->_ci_view_paths; + $view = $_view; + } + + if (method_exists($this, '_ci_object_to_array')) { + return $this->_ci_load(['_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return]); + } else { + return $this->_ci_load(['_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return]); + } + } + + /** + * [_ci_get_component description] + * + * @method _ci_get_component + * + * @param [type] $component [description] + * + * @return [type] [description] + */ + protected function &_ci_get_component($component) + { + return CI::$APP->$component; + } + + /** + * [__get description] + * + * @method __get + * + * @param [type] $class [description] + * + * @return [type] [description] + */ + public function __get($class) + { + return isset($this->controller) ? $this->controller->$class : CI::$APP->$class; + } + + /** + * [_ci_load description] + * + * @method _ci_load + * + * @param [type] $_ci_data [description] + * + * @return [type] [description] + */ + public function _ci_load($_ci_data) + { + extract($_ci_data); + + if (isset($_ci_view)) { + $_ci_path = ''; + + // add file extension if not provided + $_ci_file = pathinfo($_ci_view, PATHINFO_EXTENSION) ? $_ci_view : $_ci_view.EXT; + + foreach ($this->_ci_view_paths as $path => $cascade) { + if (file_exists($view = $path.$_ci_file)) { + $_ci_path = $view; + break; + } + if (! $cascade) { + break; + } + } + } elseif (isset($_ci_path)) { + $_ci_file = basename($_ci_path); + if (! file_exists($_ci_path)) { + $_ci_path = ''; + } + } + + if (empty($_ci_path)) { + show_error('Unable to load the requested file: '.$_ci_file); + } + + if (isset($_ci_vars)) { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, (array) $_ci_vars); + } + + extract($this->_ci_cached_vars); + + ob_start(); + + if ((bool) @ini_get('short_open_tag') === false && CI::$APP->config->item('rewrite_short_tags') == true) { + echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace(' $this->_ci_ob_level + 1) { + ob_end_flush(); + } else { + CI::$APP->output->append_output(ob_get_clean()); + } + } + + /** + * [Autoload module items] + * + * @method _autoloader + * + * @param [type] $autoload [description] + * + * @return [type] [description] + */ + public function _autoloader($autoload) + { + $path = false; + + if ($this->_module) { + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $file) = Modules::find('constants', $this->_module, 'config/'); + } else { + [$path, $file] = Modules::find('constants', $this->_module, 'config/'); + } + // module constants file + if ($path !== false) { + include_once $path.$file.EXT; + } + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + list($path, $file) = Modules::find('autoload', $this->_module, 'config/'); + } else { + [$path, $file] = Modules::find('autoload', $this->_module, 'config/'); + } + + // module autoload file + if ($path !== false) { + $autoload = array_merge(Modules::load_file($file, $path, 'autoload'), $autoload); + } + } + + // nothing to do + if (count($autoload) === 0) { + return; + } + + // autoload package paths + if (isset($autoload['packages'])) { + foreach ($autoload['packages'] as $package_path) { + $this->add_package_path($package_path); + } + } + + /* autoload config */ + if (isset($autoload['config'])) { + foreach ($autoload['config'] as $config) { + $this->config($config); + } + } + + // autoload helpers, plugins, languages + foreach (['helper', 'plugin', 'language'] as $type) { + if (isset($autoload[$type])) { + foreach ($autoload[$type] as $item) { + $this->$type($item); + } + } + } + + // Autoload drivers + if (isset($autoload['drivers'])) { + foreach ($autoload['drivers'] as $item => $alias) { + is_int($item) ? $this->driver($alias) : $this->driver($item, $alias); + } + } + + // autoload database & libraries + if (isset($autoload['libraries'])) { + if (!$db = CI::$APP->config->item('database') && in_array('database', $autoload['libraries'])) { + $this->database(); + + $autoload['libraries'] = array_diff($autoload['libraries'], ['database']); + } + + // autoload libraries + foreach ($autoload['libraries'] as $library => $alias) { + is_int($library) ? $this->library($alias) : $this->library($library, null, $alias); + } + } + + // autoload models + if (isset($autoload['model'])) { + foreach ($autoload['model'] as $model => $alias) { + is_int($model) ? $this->model($alias) : $this->model($model, $alias); + } + } + + // autoload module controllers + if (isset($autoload['modules'])) { + foreach ($autoload['modules'] as $controller) { + ($controller != $this->_module) && $this->module($controller); + } + } + } +} + +// load the CI class for Modular Separation +(class_exists('CI', false)) or require_once __DIR__ .'/Ci.php'; diff --git a/application/third_party/MX/Modules.php b/application/third_party/MX/Modules.php new file mode 100644 index 00000000..ca8571ac --- /dev/null +++ b/application/third_party/MX/Modules.php @@ -0,0 +1,328 @@ +item('modules_locations')) or Modules::$locations = [ + APPPATH.'modules/' => '../modules/', +]; + +// PHP5 spl_autoload +spl_autoload_register('Modules::autoload'); + +/** + * Modular Extensions - HMVC + * + * Adapted from the CodeIgniter Core Classes + * @link http://codeigniter.com + * + * Description: + * This library provides functions to load and instantiate controllers + * and module controllers allowing use of modules and the HMVC design pattern. + * + * Install this file as application/third_party/MX/Modules.php + * + * @copyright Copyright (c) 2015 Wiredesignz + * @version 5.5 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + **/ +class Modules +{ + public static $routes; + public static $registry; + public static $locations; + + /** + * [Run a module controller method, output from module is buffered and returned.] + * + * @method run + * + * @param [type] $module [description] + * + * @return [type] [description] + */ + public static function run($module) + { + $method = 'index'; + + if (($pos = strrpos($module, '/')) !== false) { + $method = substr($module, $pos + 1); + $module = substr($module, 0, $pos); + } + + if ($class = self::load($module)) { + if (method_exists($class, $method)) { + ob_start(); + $args = func_get_args(); + $output = call_user_func_array([$class, $method], array_slice($args, 1)); + $buffer = ob_get_clean(); + return $output ?? $buffer; + } + } + + log_message('error', "Module controller failed to run: {$module}/{$method}"); + } + + /** + * [Load a module controller] + * + * @method load + * + * @param [type] $module [description] + * + * @return [type] [description] + */ + public static function load($module) + { + // Backward function + // The function each() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + is_array($module) ? list($module, $params) = each($module) : $params = null; + } else { + if (!is_array($module)) { + $params = null; + } else { + $keys = array_keys($module); + + $params = $module[$keys[0]]; + + $module = $keys[0]; + } + } + + // get the requested controller class name + $alias = strtolower(basename($module)); + + // create or return an existing controller from the registry + if (!isset(self::$registry[$alias])) { + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + // find the controller + list($class) = CI::$APP->router->locate(explode('/', $module)); + } else { + [$class] = CI::$APP->router->locate(explode('/', $module)); + } + + // controller cannot be located + if (empty($class)) { + return; + } + + // set the module directory + $path = APPPATH.'controllers/'.CI::$APP->router->directory; + + // load the controller class + $class .= CI::$APP->config->item('controller_suffix'); + self::load_file(ucfirst($class), $path); + + // create and register the new controller + $controller = ucfirst($class); + self::$registry[$alias] = new $controller($params); + } + + return self::$registry[$alias]; + } + + /** + * [Library base class autoload] + * + * @method autoload + * + * @param [type] $class [description] + * + * @return [type] [description] + */ + public static function autoload($class) + { + // don't autoload CI_ prefixed classes or those using the config subclass_prefix + if (strstr($class, 'CI_') || strstr($class, config_item('subclass_prefix'))) { + return; + } + + // autoload Modular Extensions MX core classes + if (strstr($class, 'MX_')) { + if (is_file($location = dirname(__FILE__).'/'.substr($class, 3).EXT)) { + include_once $location; + return; + } + show_error('Failed to load MX core class: '.$class); + } + + // autoload core classes + if (is_file($location = APPPATH.'core/'.ucfirst($class).EXT)) { + include_once $location; + return; + } + + // autoload library classes + if (is_file($location = APPPATH.'libraries/'.ucfirst($class).EXT)) { + include_once $location; + return; + } + } + + /** + * [Load a module file] + * + * @method load_file + * + * @param [type] $file [description] + * @param [type] $path [description] + * @param string $type [description] + * @param boolean $result [description] + * + * @return [type] [description] + */ + public static function load_file($file, $path, $type = 'other', $result = true) + { + $file = str_replace(EXT, '', $file); + $location = $path.$file.EXT; + + if ($type === 'other') { + if (class_exists($file, false)) { + log_message('debug', "File already loaded: {$location}"); + return $result; + } + include_once $location; + } else { + // load config or language array + include $location; + + if (! isset($$type) || ! is_array($$type)) { + show_error("{$location} does not contain a valid {$type} array"); + } + + $result = $$type; + } + log_message('debug', "File loaded: {$location}"); + return $result; + } + + /** + * [Find a file, + * scans for files located within modules directories, + * also scans application directories for models, + * plugins and views, Generates fatal error if file not found] + * + * @method find + * + * @param [type] $file [description] + * @param [type] $module [description] + * @param [type] $base [description] + * + * @return [type] [description] + */ + public static function find($file, $module, $base) + { + $segments = explode('/', $file); + + $file = array_pop($segments); + $file_ext = pathinfo($file, PATHINFO_EXTENSION) ? $file : $file.EXT; + + $path = ltrim(implode('/', $segments).'/', '/'); + $module ? $modules[$module] = $path : $modules = []; + + if (! empty($segments)) { + $modules[array_shift($segments)] = ltrim(implode('/', $segments).'/', '/'); + } + + foreach (self::$locations as $location => $offset) { + foreach ($modules as $module => $subpath) { + $fullpath = $location.$module.'/'.$base.$subpath; + + if ($base === 'libraries/' || $base === 'models/') { + if (is_file($fullpath.ucfirst($file_ext))) { + return [$fullpath, ucfirst($file)]; + } + } elseif // load non-class files + (is_file($fullpath.$file_ext)) { + return [$fullpath, $file]; + } + } + } + + return [false, $file]; + } + + /** + * [Parse module routes] + * + * @method parse_routes + * + * @param [type] $module [description] + * @param [type] $uri [description] + * + * @return [type] [description] + */ + public static function parse_routes($module, $uri) + { + // load the route file + if (! isset(self::$routes[$module])) { + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + if (list($path) = self::find('routes', $module, 'config/')) { + $path && self::$routes[$module] = self::load_file('routes', $path, 'route'); + } + } else { + if ([$path] = self::find('routes', $module, 'config/')) { + $path && self::$routes[$module] = self::load_file('routes', $path, 'route'); + } + } + } + + if (! isset(self::$routes[$module])) { + return; + } + + // Add http verb support for each module routing + $http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli'; + + // parse module routes + foreach (self::$routes[$module] as $key => $val) { + // Add http verb support for each module routing + if (is_array($val)) { + $val = array_change_key_case($val, CASE_LOWER); + + if (isset($val[$http_verb])) { + $val = $val[$http_verb]; + } else { + continue; + } + } + + $key = str_replace([':any', ':num'], ['.+', '[0-9]+'], $key); + + if (preg_match('#^'.$key.'$#', $uri)) { + if (strpos($val, '$') !== false && strpos($key, '(') !== false) { + $val = preg_replace('#^'.$key.'$#', $val, $uri); + } + return explode('/', $module.'/'.$val); + } + } + } +} diff --git a/application/third_party/MX/Router.php b/application/third_party/MX/Router.php new file mode 100644 index 00000000..8888c0b9 --- /dev/null +++ b/application/third_party/MX/Router.php @@ -0,0 +1,273 @@ +module; + } + + /** + * [_set_request description] + * + * @method _set_request + * + * @param array $segments [description] + */ + protected function _set_request($segments = []) + { + if ($this->translate_uri_dashes === true) { + foreach (range(0, 2) as $v) { + isset($segments[$v]) && $segments[$v] = str_replace('-', '_', $segments[$v]); + } + } + + $segments = $this->locate($segments); + + if ($this->located == -1) { + $this->_set_404override_controller(); + return; + } + + if (empty($segments)) { + $this->_set_default_controller(); + return; + } + + $this->set_class($segments[0]); + + if (isset($segments[1])) { + $this->set_method($segments[1]); + } else { + $segments[1] = 'index'; + } + + array_unshift($segments, null); + unset($segments[0]); + $this->uri->rsegments = $segments; + } + + /** + * [_set_404override_controller description] + * + * @method _set_404override_controller + */ + protected function _set_404override_controller() + { + $this->_set_module_path($this->routes['404_override']); + } + + /** + * [_set_default_controller description] + * + * @method _set_default_controller + */ + protected function _set_default_controller() + { + if (empty($this->directory)) { + // set the default controller module path + $this->_set_module_path($this->default_controller); + } + + parent::_set_default_controller(); + + if (empty($this->class)) { + $this->_set_404override_controller(); + } + } + + /** + * [Locate the controller] + * + * @method locate + * + * @param [type] $segments [description] + * + * @return [type] [description] + */ + public function locate($segments) + { + // Clear var $this->directory before search controller in function locate() of the Router class. + // Solve the problem of trying to load a "root" controller using Modules::run('controller/method') after loading a module controller + // with Modules::run('module/controller/method') + $this->directory = null; + $this->located = 0; + $ext = $this->config->item('controller_suffix').EXT; + + /* use module route if available */ + if (isset($segments[0]) && $routes = Modules::parse_routes($segments[0], implode('/', $segments))) { + $segments = $routes; + } + + // Backward function + // Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. + if (version_compare(phpversion(), '7.1', '<')) { + // php version isn't high enough + // get the segments array elements + list($module, $directory, $controller) = array_pad($segments, 3, null); + } else { + [$module, $directory, $controller] = array_pad($segments, 3, null); + } + + // check modules + foreach (Modules::$locations as $location => $offset) { + // module exists? + if (is_dir($source = $location.$module.'/controllers/')) { + $this->module = $module; + $this->directory = $offset.$module.'/controllers/'; + + // module sub-controller exists? + if ($directory) { + // module sub-directory exists? + if (is_dir($source.$directory.'/')) { + $source .= $directory.'/'; + $this->directory .= $directory.'/'; + + // module sub-directory controller exists? + if ($controller) { + if (is_file($source.ucfirst($controller).$ext)) { + $this->located = 3; + return array_slice($segments, 2); + } + $this->located = -1; + } + } elseif (is_file($source.ucfirst($directory).$ext)) { + $this->located = 2; + return array_slice($segments, 1); + } else { + $this->located = -1; + } + } + + // module controller exists? + if (is_file($source.ucfirst($module).$ext)) { + $this->located = 1; + return $segments; + } + } + } + + if (! empty($this->directory)) { + return; + } + + // application sub-directory controller exists? + if ($directory) { + if (is_file(APPPATH.'controllers/'.$module.'/'.ucfirst($directory).$ext)) { + $this->directory = $module.'/'; + return array_slice($segments, 1); + } + + // application sub-sub-directory controller exists? + if ($controller && is_file(APPPATH . 'controllers/' . $module . '/' . $directory . '/' . ucfirst($controller) . $ext)) { + $this->directory = $module.'/'.$directory.'/'; + return array_slice($segments, 2); + } + } + + // application controllers sub-directory exists? + if (is_dir(APPPATH.'controllers/'.$module.'/')) { + $this->directory = $module.'/'; + return array_slice($segments, 1); + } + + // application controller exists? + if (is_file(APPPATH.'controllers/'.ucfirst($module).$ext)) { + return $segments; + } + $this->located = -1; + } + + /** + * [set module path] + * + * @method _set_module_path + * + * @param [type] &$_route [description] + */ + protected function _set_module_path(&$_route) + { + if (! empty($_route)) { + // Are module/directory/controller/method segments being specified? + $sgs = sscanf($_route, '%[^/]/%[^/]/%[^/]/%s', $module, $directory, $class, $method); + + // set the module/controller directory location if found + if ($this->locate([$module, $directory, $class])) { + //reset to class/method + switch ($sgs) { + case 1: $_route = $module.'/index'; + break; + case 2: $_route = ($this->located < 2) ? $module.'/'.$directory : $directory.'/index'; + break; + case 3: $_route = ($this->located == 2) ? $directory.'/'.$class : $class.'/index'; + break; + case 4: $_route = ($this->located == 3) ? $class.'/'.$method : $method.'/index'; + break; + } + } + } + } + + /** + * [set_class description] + * + * @method set_class + * + * @param [type] $class [description] + */ + public function set_class($class) + { + $suffix = $this->config->item('controller_suffix'); + // Fixing Error Message: strpos(): Non-string needles will be interpreted as strings in the future. + // Use an explicit chr() call to preserve the current behavior. + if ($suffix && strpos($class, $suffix) === false) { + $class .= $suffix; + } + parent::set_class($class); + } +} diff --git a/application/third_party/MX/index.html b/application/third_party/MX/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/third_party/MX/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/third_party/index.html b/application/third_party/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/third_party/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/errors/cli/error_404.php b/application/views/errors/cli/error_404.php new file mode 100644 index 00000000..6984b61e --- /dev/null +++ b/application/views/errors/cli/error_404.php @@ -0,0 +1,8 @@ + + +An uncaught Exception was encountered + +Type: +Message: +Filename: getFile(), "\n"; ?> +Line Number: getLine(); ?> + + + +Backtrace: +getTrace() as $error): ?> + + File: + Line: + Function: + + + + diff --git a/application/views/errors/cli/error_general.php b/application/views/errors/cli/error_general.php new file mode 100644 index 00000000..6984b61e --- /dev/null +++ b/application/views/errors/cli/error_general.php @@ -0,0 +1,8 @@ + + +A PHP Error was encountered + +Severity: +Message: +Filename: +Line Number: + + + +Backtrace: + + + File: + Line: + Function: + + + + diff --git a/application/views/errors/cli/index.html b/application/views/errors/cli/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/errors/cli/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/errors/html/error_404.php b/application/views/errors/html/error_404.php new file mode 100644 index 00000000..86e29244 --- /dev/null +++ b/application/views/errors/html/error_404.php @@ -0,0 +1,27 @@ + + +
+

+ +
\ No newline at end of file diff --git a/application/views/errors/html/error_db.php b/application/views/errors/html/error_db.php new file mode 100644 index 00000000..86e29244 --- /dev/null +++ b/application/views/errors/html/error_db.php @@ -0,0 +1,27 @@ + + +
+

+ +
\ No newline at end of file diff --git a/application/views/errors/html/error_exception.php b/application/views/errors/html/error_exception.php new file mode 100644 index 00000000..87848866 --- /dev/null +++ b/application/views/errors/html/error_exception.php @@ -0,0 +1,32 @@ + + +
+ +

An uncaught Exception was encountered

+ +

Type:

+

Message:

+

Filename: getFile(); ?>

+

Line Number: getLine(); ?>

+ + + +

Backtrace:

+ getTrace() as $error): ?> + + + +

+ File:
+ Line:
+ Function: +

+ + + + + + +
\ No newline at end of file diff --git a/application/views/errors/html/error_general.php b/application/views/errors/html/error_general.php new file mode 100644 index 00000000..86e29244 --- /dev/null +++ b/application/views/errors/html/error_general.php @@ -0,0 +1,27 @@ + + +
+

+ +
\ No newline at end of file diff --git a/application/views/errors/html/error_php.php b/application/views/errors/html/error_php.php new file mode 100644 index 00000000..b146f9c5 --- /dev/null +++ b/application/views/errors/html/error_php.php @@ -0,0 +1,33 @@ + + +
+ +

A PHP Error was encountered

+ +

Severity:

+

Message:

+

Filename:

+

Line Number:

+ + + +

Backtrace:

+ + + + +

+ File:
+ Line:
+ Function: +

+ + + + + + + +
\ No newline at end of file diff --git a/application/views/errors/html/index.html b/application/views/errors/html/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/errors/html/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/errors/index.html b/application/views/errors/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/errors/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/index.html b/application/views/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/assets/css/MY_styles.css b/assets/css/MY_styles.css new file mode 100644 index 00000000..48fcedcc --- /dev/null +++ b/assets/css/MY_styles.css @@ -0,0 +1 @@ +/* ADD CUSTOM STYLES HERE */ diff --git a/assets/css/bootstrap.min.css b/assets/css/bootstrap.min.css new file mode 100644 index 00000000..225c2e02 --- /dev/null +++ b/assets/css/bootstrap.min.css @@ -0,0 +1 @@ +:root{--blue:#005BA9;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#AE9B70;--secondary:#DBCEB1;--success:#007100;--info:#005BA9;--warning:#FF7C00;--danger:#AE0000;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;text-decoration:underline dotted;cursor:help;border-bottom:0;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#ae9b70;text-decoration:none;background-color:transparent}a:hover{color:#86744c;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#6c757d}.blockquote-footer::before{content:"\2014\00A0"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#6c757d}code{font-size:87.5%;color:#e83e8c;word-break:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;font-size:87.5%;color:#212529}pre code{font-size:inherit;color:inherit;word-break:normal}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container{max-width:540px}}@media (min-width:768px){.container{max-width:720px}}@media (min-width:992px){.container{max-width:960px}}@media (min-width:1200px){.container{max-width:1140px}}.container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{display:flex;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*=col-]{padding-right:0;padding-left:0}.col,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{position:relative;width:100%;padding-right:15px;padding-left:15px}.col{flex-basis:0;flex-grow:1;max-width:100%}.col-auto{flex:0 0 auto;width:auto;max-width:100%}.col-1{flex:0 0 8.33333%;max-width:8.33333%}.col-2{flex:0 0 16.66667%;max-width:16.66667%}.col-3{flex:0 0 25%;max-width:25%}.col-4{flex:0 0 33.33333%;max-width:33.33333%}.col-5{flex:0 0 41.66667%;max-width:41.66667%}.col-6{flex:0 0 50%;max-width:50%}.col-7{flex:0 0 58.33333%;max-width:58.33333%}.col-8{flex:0 0 66.66667%;max-width:66.66667%}.col-9{flex:0 0 75%;max-width:75%}.col-10{flex:0 0 83.33333%;max-width:83.33333%}.col-11{flex:0 0 91.66667%;max-width:91.66667%}.col-12{flex:0 0 100%;max-width:100%}.order-first{order:-1}.order-last{order:13}.order-0{order:0}.order-1{order:1}.order-2{order:2}.order-3{order:3}.order-4{order:4}.order-5{order:5}.order-6{order:6}.order-7{order:7}.order-8{order:8}.order-9{order:9}.order-10{order:10}.order-11{order:11}.order-12{order:12}.offset-1{margin-left:8.33333%}.offset-2{margin-left:16.66667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.33333%}.offset-5{margin-left:41.66667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.33333%}.offset-8{margin-left:66.66667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.33333%}.offset-11{margin-left:91.66667%}@media (min-width:576px){.col-sm{flex-basis:0;flex-grow:1;max-width:100%}.col-sm-auto{flex:0 0 auto;width:auto;max-width:100%}.col-sm-1{flex:0 0 8.33333%;max-width:8.33333%}.col-sm-2{flex:0 0 16.66667%;max-width:16.66667%}.col-sm-3{flex:0 0 25%;max-width:25%}.col-sm-4{flex:0 0 33.33333%;max-width:33.33333%}.col-sm-5{flex:0 0 41.66667%;max-width:41.66667%}.col-sm-6{flex:0 0 50%;max-width:50%}.col-sm-7{flex:0 0 58.33333%;max-width:58.33333%}.col-sm-8{flex:0 0 66.66667%;max-width:66.66667%}.col-sm-9{flex:0 0 75%;max-width:75%}.col-sm-10{flex:0 0 83.33333%;max-width:83.33333%}.col-sm-11{flex:0 0 91.66667%;max-width:91.66667%}.col-sm-12{flex:0 0 100%;max-width:100%}.order-sm-first{order:-1}.order-sm-last{order:13}.order-sm-0{order:0}.order-sm-1{order:1}.order-sm-2{order:2}.order-sm-3{order:3}.order-sm-4{order:4}.order-sm-5{order:5}.order-sm-6{order:6}.order-sm-7{order:7}.order-sm-8{order:8}.order-sm-9{order:9}.order-sm-10{order:10}.order-sm-11{order:11}.order-sm-12{order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.33333%}.offset-sm-2{margin-left:16.66667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.33333%}.offset-sm-5{margin-left:41.66667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.33333%}.offset-sm-8{margin-left:66.66667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.33333%}.offset-sm-11{margin-left:91.66667%}}@media (min-width:768px){.col-md{flex-basis:0;flex-grow:1;max-width:100%}.col-md-auto{flex:0 0 auto;width:auto;max-width:100%}.col-md-1{flex:0 0 8.33333%;max-width:8.33333%}.col-md-2{flex:0 0 16.66667%;max-width:16.66667%}.col-md-3{flex:0 0 25%;max-width:25%}.col-md-4{flex:0 0 33.33333%;max-width:33.33333%}.col-md-5{flex:0 0 41.66667%;max-width:41.66667%}.col-md-6{flex:0 0 50%;max-width:50%}.col-md-7{flex:0 0 58.33333%;max-width:58.33333%}.col-md-8{flex:0 0 66.66667%;max-width:66.66667%}.col-md-9{flex:0 0 75%;max-width:75%}.col-md-10{flex:0 0 83.33333%;max-width:83.33333%}.col-md-11{flex:0 0 91.66667%;max-width:91.66667%}.col-md-12{flex:0 0 100%;max-width:100%}.order-md-first{order:-1}.order-md-last{order:13}.order-md-0{order:0}.order-md-1{order:1}.order-md-2{order:2}.order-md-3{order:3}.order-md-4{order:4}.order-md-5{order:5}.order-md-6{order:6}.order-md-7{order:7}.order-md-8{order:8}.order-md-9{order:9}.order-md-10{order:10}.order-md-11{order:11}.order-md-12{order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.33333%}.offset-md-2{margin-left:16.66667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.33333%}.offset-md-5{margin-left:41.66667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.33333%}.offset-md-8{margin-left:66.66667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.33333%}.offset-md-11{margin-left:91.66667%}}@media (min-width:992px){.col-lg{flex-basis:0;flex-grow:1;max-width:100%}.col-lg-auto{flex:0 0 auto;width:auto;max-width:100%}.col-lg-1{flex:0 0 8.33333%;max-width:8.33333%}.col-lg-2{flex:0 0 16.66667%;max-width:16.66667%}.col-lg-3{flex:0 0 25%;max-width:25%}.col-lg-4{flex:0 0 33.33333%;max-width:33.33333%}.col-lg-5{flex:0 0 41.66667%;max-width:41.66667%}.col-lg-6{flex:0 0 50%;max-width:50%}.col-lg-7{flex:0 0 58.33333%;max-width:58.33333%}.col-lg-8{flex:0 0 66.66667%;max-width:66.66667%}.col-lg-9{flex:0 0 75%;max-width:75%}.col-lg-10{flex:0 0 83.33333%;max-width:83.33333%}.col-lg-11{flex:0 0 91.66667%;max-width:91.66667%}.col-lg-12{flex:0 0 100%;max-width:100%}.order-lg-first{order:-1}.order-lg-last{order:13}.order-lg-0{order:0}.order-lg-1{order:1}.order-lg-2{order:2}.order-lg-3{order:3}.order-lg-4{order:4}.order-lg-5{order:5}.order-lg-6{order:6}.order-lg-7{order:7}.order-lg-8{order:8}.order-lg-9{order:9}.order-lg-10{order:10}.order-lg-11{order:11}.order-lg-12{order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.33333%}.offset-lg-2{margin-left:16.66667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.33333%}.offset-lg-5{margin-left:41.66667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.33333%}.offset-lg-8{margin-left:66.66667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.33333%}.offset-lg-11{margin-left:91.66667%}}@media (min-width:1200px){.col-xl{flex-basis:0;flex-grow:1;max-width:100%}.col-xl-auto{flex:0 0 auto;width:auto;max-width:100%}.col-xl-1{flex:0 0 8.33333%;max-width:8.33333%}.col-xl-2{flex:0 0 16.66667%;max-width:16.66667%}.col-xl-3{flex:0 0 25%;max-width:25%}.col-xl-4{flex:0 0 33.33333%;max-width:33.33333%}.col-xl-5{flex:0 0 41.66667%;max-width:41.66667%}.col-xl-6{flex:0 0 50%;max-width:50%}.col-xl-7{flex:0 0 58.33333%;max-width:58.33333%}.col-xl-8{flex:0 0 66.66667%;max-width:66.66667%}.col-xl-9{flex:0 0 75%;max-width:75%}.col-xl-10{flex:0 0 83.33333%;max-width:83.33333%}.col-xl-11{flex:0 0 91.66667%;max-width:91.66667%}.col-xl-12{flex:0 0 100%;max-width:100%}.order-xl-first{order:-1}.order-xl-last{order:13}.order-xl-0{order:0}.order-xl-1{order:1}.order-xl-2{order:2}.order-xl-3{order:3}.order-xl-4{order:4}.order-xl-5{order:5}.order-xl-6{order:6}.order-xl-7{order:7}.order-xl-8{order:8}.order-xl-9{order:9}.order-xl-10{order:10}.order-xl-11{order:11}.order-xl-12{order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.33333%}.offset-xl-2{margin-left:16.66667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.33333%}.offset-xl-5{margin-left:41.66667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.33333%}.offset-xl-8{margin-left:66.66667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.33333%}.offset-xl-11{margin-left:91.66667%}}.table{width:100%;margin-bottom:1rem;color:#212529}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-borderless tbody+tbody,.table-borderless td,.table-borderless th,.table-borderless thead th{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{color:#212529;background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#e8e3d7}.table-primary tbody+tbody,.table-primary td,.table-primary th,.table-primary thead th{border-color:#d5cbb5}.table-hover .table-primary:hover{background-color:#dfd8c7}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#dfd8c7}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#f5f1e9}.table-secondary tbody+tbody,.table-secondary td,.table-secondary th,.table-secondary thead th{border-color:#ece6d6}.table-hover .table-secondary:hover{background-color:#ede6d7}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#ede6d7}.table-success,.table-success>td,.table-success>th{background-color:#b8d7b8}.table-success tbody+tbody,.table-success td,.table-success th,.table-success thead th{border-color:#7ab57a}.table-hover .table-success:hover{background-color:#a8cea8}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#a8cea8}.table-info,.table-info>td,.table-info>th{background-color:#b8d1e7}.table-info tbody+tbody,.table-info td,.table-info th,.table-info thead th{border-color:#7aaad2}.table-hover .table-info:hover{background-color:#a5c5e1}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#a5c5e1}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffdab8}.table-warning tbody+tbody,.table-warning td,.table-warning th,.table-warning thead th{border-color:#ffbb7a}.table-hover .table-warning:hover{background-color:#ffcd9f}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffcd9f}.table-danger,.table-danger>td,.table-danger>th{background-color:#e8b8b8}.table-danger tbody+tbody,.table-danger td,.table-danger th,.table-danger thead th{border-color:#d57a7a}.table-hover .table-danger:hover{background-color:#e2a5a5}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#e2a5a5}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-light tbody+tbody,.table-light td,.table-light th,.table-light thead th{border-color:#fbfcfc}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#95999c}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#343a40;border-color:#454d55}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#343a40}.table-dark td,.table-dark th,.table-dark thead th{border-color:#454d55}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{color:#fff;background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive>.table-bordered{border:0}.form-control{display:block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.form-control{transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:focus{color:#495057;background-color:#fff;border-color:#dcd4c1;outline:0;box-shadow:0 0 0 .2rem rgba(174,155,112,.25)}.form-control::placeholder{color:#6c757d;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block;width:100%}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding-top:.375rem;padding-bottom:.375rem;margin-bottom:0;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.5em + .5rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.form-control-lg{height:calc(1.5em + 1rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}select.form-control[multiple],select.form-control[size]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{display:flex;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*=col-]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;padding-left:1.25rem}.form-check-input{position:absolute;margin-top:.3rem;margin-left:-1.25rem}.form-check-input:disabled~.form-check-label{color:#6c757d}.form-check-label{margin-bottom:0}.form-check-inline{display:inline-flex;align-items:center;padding-left:0;margin-right:.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#007100}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(0,113,0,.9);border-radius:.25rem}.form-control.is-valid,.was-validated .form-control:valid{border-color:#007100;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23007100' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:center right calc(.375em + .1875rem);background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-valid:focus,.was-validated .form-control:valid:focus{border-color:#007100;box-shadow:0 0 0 .2rem rgba(0,113,0,.25)}.form-control.is-valid~.valid-feedback,.form-control.is-valid~.valid-tooltip,.was-validated .form-control:valid~.valid-feedback,.was-validated .form-control:valid~.valid-tooltip{display:block}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-valid,.was-validated .custom-select:valid{border-color:#007100;padding-right:calc((1em + .75rem) * 3 / 4 + 1.75rem);background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px,url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23007100' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-valid:focus,.was-validated .custom-select:valid:focus{border-color:#007100;box-shadow:0 0 0 .2rem rgba(0,113,0,.25)}.custom-select.is-valid~.valid-feedback,.custom-select.is-valid~.valid-tooltip,.was-validated .custom-select:valid~.valid-feedback,.was-validated .custom-select:valid~.valid-tooltip{display:block}.form-control-file.is-valid~.valid-feedback,.form-control-file.is-valid~.valid-tooltip,.was-validated .form-control-file:valid~.valid-feedback,.was-validated .form-control-file:valid~.valid-tooltip{display:block}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#007100}.form-check-input.is-valid~.valid-feedback,.form-check-input.is-valid~.valid-tooltip,.was-validated .form-check-input:valid~.valid-feedback,.was-validated .form-check-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid~.custom-control-label,.was-validated .custom-control-input:valid~.custom-control-label{color:#007100}.custom-control-input.is-valid~.custom-control-label::before,.was-validated .custom-control-input:valid~.custom-control-label::before{border-color:#007100}.custom-control-input.is-valid~.valid-feedback,.custom-control-input.is-valid~.valid-tooltip,.was-validated .custom-control-input:valid~.valid-feedback,.was-validated .custom-control-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid:checked~.custom-control-label::before,.was-validated .custom-control-input:valid:checked~.custom-control-label::before{border-color:#00a400;background-color:#00a400}.custom-control-input.is-valid:focus~.custom-control-label::before,.was-validated .custom-control-input:valid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(0,113,0,.25)}.custom-control-input.is-valid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:valid:focus:not(:checked)~.custom-control-label::before{border-color:#007100}.custom-file-input.is-valid~.custom-file-label,.was-validated .custom-file-input:valid~.custom-file-label{border-color:#007100}.custom-file-input.is-valid~.valid-feedback,.custom-file-input.is-valid~.valid-tooltip,.was-validated .custom-file-input:valid~.valid-feedback,.was-validated .custom-file-input:valid~.valid-tooltip{display:block}.custom-file-input.is-valid:focus~.custom-file-label,.was-validated .custom-file-input:valid:focus~.custom-file-label{border-color:#007100;box-shadow:0 0 0 .2rem rgba(0,113,0,.25)}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#ae0000}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(174,0,0,.9);border-radius:.25rem}.form-control.is-invalid,.was-validated .form-control:invalid{border-color:#ae0000;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23AE0000' viewBox='-2 -2 7 7'%3e%3cpath stroke='%23AE0000' d='M0 0l3 3m0-3L0 3'/%3e%3ccircle r='.5'/%3e%3ccircle cx='3' r='.5'/%3e%3ccircle cy='3' r='.5'/%3e%3ccircle cx='3' cy='3' r='.5'/%3e%3c/svg%3E");background-repeat:no-repeat;background-position:center right calc(.375em + .1875rem);background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-invalid:focus,.was-validated .form-control:invalid:focus{border-color:#ae0000;box-shadow:0 0 0 .2rem rgba(174,0,0,.25)}.form-control.is-invalid~.invalid-feedback,.form-control.is-invalid~.invalid-tooltip,.was-validated .form-control:invalid~.invalid-feedback,.was-validated .form-control:invalid~.invalid-tooltip{display:block}.was-validated textarea.form-control:invalid,textarea.form-control.is-invalid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-invalid,.was-validated .custom-select:invalid{border-color:#ae0000;padding-right:calc((1em + .75rem) * 3 / 4 + 1.75rem);background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px,url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23AE0000' viewBox='-2 -2 7 7'%3e%3cpath stroke='%23AE0000' d='M0 0l3 3m0-3L0 3'/%3e%3ccircle r='.5'/%3e%3ccircle cx='3' r='.5'/%3e%3ccircle cy='3' r='.5'/%3e%3ccircle cx='3' cy='3' r='.5'/%3e%3c/svg%3E") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-invalid:focus,.was-validated .custom-select:invalid:focus{border-color:#ae0000;box-shadow:0 0 0 .2rem rgba(174,0,0,.25)}.custom-select.is-invalid~.invalid-feedback,.custom-select.is-invalid~.invalid-tooltip,.was-validated .custom-select:invalid~.invalid-feedback,.was-validated .custom-select:invalid~.invalid-tooltip{display:block}.form-control-file.is-invalid~.invalid-feedback,.form-control-file.is-invalid~.invalid-tooltip,.was-validated .form-control-file:invalid~.invalid-feedback,.was-validated .form-control-file:invalid~.invalid-tooltip{display:block}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#ae0000}.form-check-input.is-invalid~.invalid-feedback,.form-check-input.is-invalid~.invalid-tooltip,.was-validated .form-check-input:invalid~.invalid-feedback,.was-validated .form-check-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid~.custom-control-label,.was-validated .custom-control-input:invalid~.custom-control-label{color:#ae0000}.custom-control-input.is-invalid~.custom-control-label::before,.was-validated .custom-control-input:invalid~.custom-control-label::before{border-color:#ae0000}.custom-control-input.is-invalid~.invalid-feedback,.custom-control-input.is-invalid~.invalid-tooltip,.was-validated .custom-control-input:invalid~.invalid-feedback,.was-validated .custom-control-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid:checked~.custom-control-label::before,.was-validated .custom-control-input:invalid:checked~.custom-control-label::before{border-color:#e10000;background-color:#e10000}.custom-control-input.is-invalid:focus~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(174,0,0,.25)}.custom-control-input.is-invalid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus:not(:checked)~.custom-control-label::before{border-color:#ae0000}.custom-file-input.is-invalid~.custom-file-label,.was-validated .custom-file-input:invalid~.custom-file-label{border-color:#ae0000}.custom-file-input.is-invalid~.invalid-feedback,.custom-file-input.is-invalid~.invalid-tooltip,.was-validated .custom-file-input:invalid~.invalid-feedback,.was-validated .custom-file-input:invalid~.invalid-tooltip{display:block}.custom-file-input.is-invalid:focus~.custom-file-label,.was-validated .custom-file-input:invalid:focus~.custom-file-label{border-color:#ae0000;box-shadow:0 0 0 .2rem rgba(174,0,0,.25)}.form-inline{display:flex;flex-flow:row wrap;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:flex;align-items:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:flex;flex:0 0 auto;flex-flow:row wrap;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .custom-select,.form-inline .input-group{width:auto}.form-inline .form-check{display:flex;align-items:center;justify-content:center;width:auto;padding-left:0}.form-inline .form-check-input{position:relative;flex-shrink:0;margin-top:0;margin-right:.25rem;margin-left:0}.form-inline .custom-control{align-items:center;justify-content:center}.form-inline .custom-control-label{margin-bottom:0}}.btn{display:inline-block;font-weight:400;color:#212529;text-align:center;vertical-align:middle;user-select:none;background-color:transparent;border:1px solid transparent;padding:.375rem .75rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.btn{transition:none}}.btn:hover{color:#212529;text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(174,155,112,.25)}.btn.disabled,.btn:disabled{opacity:.65}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#212529;background-color:#ae9b70;border-color:#ae9b70}.btn-primary:hover{color:#fff;background-color:#9e895a;border-color:#968255}.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(153,137,101,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#212529;background-color:#ae9b70;border-color:#ae9b70}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#968255;border-color:#8e7b50}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(153,137,101,.5)}.btn-secondary{color:#212529;background-color:#dbceb1;border-color:#dbceb1}.btn-secondary:hover{color:#212529;background-color:#cfbe97;border-color:#cbb88e}.btn-secondary.focus,.btn-secondary:focus{box-shadow:0 0 0 .2rem rgba(191,181,157,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#212529;background-color:#dbceb1;border-color:#dbceb1}.btn-secondary:not(:disabled):not(.disabled).active,.btn-secondary:not(:disabled):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#212529;background-color:#cbb88e;border-color:#c7b385}.btn-secondary:not(:disabled):not(.disabled).active:focus,.btn-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(191,181,157,.5)}.btn-success{color:#fff;background-color:#007100;border-color:#007100}.btn-success:hover{color:#fff;background-color:#004b00;border-color:#003e00}.btn-success.focus,.btn-success:focus{box-shadow:0 0 0 .2rem rgba(38,134,38,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#007100;border-color:#007100}.btn-success:not(:disabled):not(.disabled).active,.btn-success:not(:disabled):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#003e00;border-color:#003100}.btn-success:not(:disabled):not(.disabled).active:focus,.btn-success:not(:disabled):not(.disabled):active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(38,134,38,.5)}.btn-info{color:#fff;background-color:#005ba9;border-color:#005ba9}.btn-info:hover{color:#fff;background-color:#004683;border-color:#004076}.btn-info.focus,.btn-info:focus{box-shadow:0 0 0 .2rem rgba(38,116,182,.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#005ba9;border-color:#005ba9}.btn-info:not(:disabled):not(.disabled).active,.btn-info:not(:disabled):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#004076;border-color:#003969}.btn-info:not(:disabled):not(.disabled).active:focus,.btn-info:not(:disabled):not(.disabled):active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(38,116,182,.5)}.btn-warning{color:#fff;background-color:#ff7c00;border-color:#ff7c00}.btn-warning:hover{color:#fff;background-color:#d96900;border-color:#cc6300}.btn-warning.focus,.btn-warning:focus{box-shadow:0 0 0 .2rem rgba(255,144,38,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#fff;background-color:#ff7c00;border-color:#ff7c00}.btn-warning:not(:disabled):not(.disabled).active,.btn-warning:not(:disabled):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#fff;background-color:#cc6300;border-color:#bf5d00}.btn-warning:not(:disabled):not(.disabled).active:focus,.btn-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,144,38,.5)}.btn-danger{color:#fff;background-color:#ae0000;border-color:#ae0000}.btn-danger:hover{color:#fff;background-color:#800;border-color:#7b0000}.btn-danger.focus,.btn-danger:focus{box-shadow:0 0 0 .2rem rgba(186,38,38,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#ae0000;border-color:#ae0000}.btn-danger:not(:disabled):not(.disabled).active,.btn-danger:not(:disabled):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#7b0000;border-color:#6e0000}.btn-danger:not(:disabled):not(.disabled).active:focus,.btn-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(186,38,38,.5)}.btn-light{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#212529;background-color:#e2e6ea;border-color:#dae0e5}.btn-light.focus,.btn-light:focus{box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-light.disabled,.btn-light:disabled{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not(:disabled):not(.disabled).active,.btn-light:not(:disabled):not(.disabled):active,.show>.btn-light.dropdown-toggle{color:#212529;background-color:#dae0e5;border-color:#d3d9df}.btn-light:not(:disabled):not(.disabled).active:focus,.btn-light:not(:disabled):not(.disabled):active:focus,.show>.btn-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark.focus,.btn-dark:focus{box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:not(:disabled):not(.disabled).active,.btn-dark:not(:disabled):not(.disabled):active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d}.btn-dark:not(:disabled):not(.disabled).active:focus,.btn-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-outline-primary{color:#ae9b70;border-color:#ae9b70}.btn-outline-primary:hover{color:#212529;background-color:#ae9b70;border-color:#ae9b70}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(174,155,112,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#ae9b70;background-color:transparent}.btn-outline-primary:not(:disabled):not(.disabled).active,.btn-outline-primary:not(:disabled):not(.disabled):active,.show>.btn-outline-primary.dropdown-toggle{color:#212529;background-color:#ae9b70;border-color:#ae9b70}.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(174,155,112,.5)}.btn-outline-secondary{color:#dbceb1;border-color:#dbceb1}.btn-outline-secondary:hover{color:#212529;background-color:#dbceb1;border-color:#dbceb1}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(219,206,177,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#dbceb1;background-color:transparent}.btn-outline-secondary:not(:disabled):not(.disabled).active,.btn-outline-secondary:not(:disabled):not(.disabled):active,.show>.btn-outline-secondary.dropdown-toggle{color:#212529;background-color:#dbceb1;border-color:#dbceb1}.btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(219,206,177,.5)}.btn-outline-success{color:#007100;border-color:#007100}.btn-outline-success:hover{color:#fff;background-color:#007100;border-color:#007100}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(0,113,0,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#007100;background-color:transparent}.btn-outline-success:not(:disabled):not(.disabled).active,.btn-outline-success:not(:disabled):not(.disabled):active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#007100;border-color:#007100}.btn-outline-success:not(:disabled):not(.disabled).active:focus,.btn-outline-success:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,113,0,.5)}.btn-outline-info{color:#005ba9;border-color:#005ba9}.btn-outline-info:hover{color:#fff;background-color:#005ba9;border-color:#005ba9}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(0,91,169,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#005ba9;background-color:transparent}.btn-outline-info:not(:disabled):not(.disabled).active,.btn-outline-info:not(:disabled):not(.disabled):active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#005ba9;border-color:#005ba9}.btn-outline-info:not(:disabled):not(.disabled).active:focus,.btn-outline-info:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,91,169,.5)}.btn-outline-warning{color:#ff7c00;border-color:#ff7c00}.btn-outline-warning:hover{color:#fff;background-color:#ff7c00;border-color:#ff7c00}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,124,0,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ff7c00;background-color:transparent}.btn-outline-warning:not(:disabled):not(.disabled).active,.btn-outline-warning:not(:disabled):not(.disabled):active,.show>.btn-outline-warning.dropdown-toggle{color:#fff;background-color:#ff7c00;border-color:#ff7c00}.btn-outline-warning:not(:disabled):not(.disabled).active:focus,.btn-outline-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,124,0,.5)}.btn-outline-danger{color:#ae0000;border-color:#ae0000}.btn-outline-danger:hover{color:#fff;background-color:#ae0000;border-color:#ae0000}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(174,0,0,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#ae0000;background-color:transparent}.btn-outline-danger:not(:disabled):not(.disabled).active,.btn-outline-danger:not(:disabled):not(.disabled):active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#ae0000;border-color:#ae0000}.btn-outline-danger:not(:disabled):not(.disabled).active:focus,.btn-outline-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(174,0,0,.5)}.btn-outline-light{color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light.focus,.btn-outline-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not(:disabled):not(.disabled).active,.btn-outline-light:not(:disabled):not(.disabled):active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:not(:disabled):not(.disabled).active:focus,.btn-outline-light:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-dark{color:#343a40;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark.focus,.btn-outline-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not(:disabled):not(.disabled).active,.btn-outline-dark:not(:disabled):not(.disabled):active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:not(:disabled):not(.disabled).active:focus,.btn-outline-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#ae9b70;text-decoration:none}.btn-link:hover{color:#86744c;text-decoration:underline}.btn-link.focus,.btn-link:focus{text-decoration:underline;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#6c757d;pointer-events:none}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{transition:opacity .15s linear}@media (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}@media (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropleft,.dropright,.dropup{position:relative}.dropdown-toggle{white-space:nowrap}.dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu-left{right:auto;left:0}.dropdown-menu-right{right:0;left:auto}@media (min-width:576px){.dropdown-menu-sm-left{right:auto;left:0}.dropdown-menu-sm-right{right:0;left:auto}}@media (min-width:768px){.dropdown-menu-md-left{right:auto;left:0}.dropdown-menu-md-right{right:0;left:auto}}@media (min-width:992px){.dropdown-menu-lg-left{right:auto;left:0}.dropdown-menu-lg-right{right:0;left:auto}}@media (min-width:1200px){.dropdown-menu-xl-left{right:auto;left:0}.dropdown-menu-xl-right{right:0;left:auto}}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-menu{top:0;right:auto;left:100%;margin-top:0;margin-left:.125rem}.dropright .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.3em solid}.dropright .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-toggle::after{vertical-align:0}.dropleft .dropdown-menu{top:0;right:100%;left:auto;margin-top:0;margin-right:.125rem}.dropleft .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:""}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;margin-right:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^=bottom],.dropdown-menu[x-placement^=left],.dropdown-menu[x-placement^=right],.dropdown-menu[x-placement^=top]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#ae9b70}.dropdown-item.disabled,.dropdown-item:disabled{color:#6c757d;pointer-events:none;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1.5rem;color:#212529}.btn-group,.btn-group-vertical{position:relative;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;flex:1 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:1}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{z-index:1}.btn-toolbar{display:flex;flex-wrap:wrap;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn-group:not(:first-child),.btn-group>.btn:not(:first-child){margin-left:-1px}.btn-group>.btn-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{flex-direction:column;align-items:flex-start;justify-content:center}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{width:100%}.btn-group-vertical>.btn-group:not(:first-child),.btn-group-vertical>.btn:not(:first-child){margin-top:-1px}.btn-group-vertical>.btn-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.btn-group-toggle>.btn,.btn-group-toggle>.btn-group>.btn{margin-bottom:0}.btn-group-toggle>.btn input[type=checkbox],.btn-group-toggle>.btn input[type=radio],.btn-group-toggle>.btn-group>.btn input[type=checkbox],.btn-group-toggle>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:flex;flex-wrap:wrap;align-items:stretch;width:100%}.input-group>.custom-file,.input-group>.custom-select,.input-group>.form-control,.input-group>.form-control-plaintext{position:relative;flex:1 1 auto;width:1%;margin-bottom:0}.input-group>.custom-file+.custom-file,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.form-control,.input-group>.custom-select+.custom-file,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.form-control,.input-group>.form-control+.custom-file,.input-group>.form-control+.custom-select,.input-group>.form-control+.form-control,.input-group>.form-control-plaintext+.custom-file,.input-group>.form-control-plaintext+.custom-select,.input-group>.form-control-plaintext+.form-control{margin-left:-1px}.input-group>.custom-file .custom-file-input:focus~.custom-file-label,.input-group>.custom-select:focus,.input-group>.form-control:focus{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.custom-select:not(:last-child),.input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-select:not(:first-child),.input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:flex;align-items:center}.input-group>.custom-file:not(:last-child) .custom-file-label,.input-group>.custom-file:not(:last-child) .custom-file-label::after{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-file:not(:first-child) .custom-file-label{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-append,.input-group-prepend{display:flex}.input-group-append .btn,.input-group-prepend .btn{position:relative;z-index:2}.input-group-append .btn:focus,.input-group-prepend .btn:focus{z-index:3}.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.btn,.input-group-append .input-group-text+.input-group-text,.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-prepend .input-group-text+.input-group-text{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:flex;align-items:center;padding:.375rem .75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-text input[type=checkbox],.input-group-text input[type=radio]{margin-top:0}.input-group-lg>.custom-select,.input-group-lg>.form-control:not(textarea){height:calc(1.5em + 1rem + 2px)}.input-group-lg>.custom-select,.input-group-lg>.form-control,.input-group-lg>.input-group-append>.btn,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-prepend>.input-group-text{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-sm>.custom-select,.input-group-sm>.form-control:not(textarea){height:calc(1.5em + .5rem + 2px)}.input-group-sm>.custom-select,.input-group-sm>.form-control,.input-group-sm>.input-group-append>.btn,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-prepend>.input-group-text{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.input-group-lg>.custom-select,.input-group-sm>.custom-select{padding-right:1.75rem}.input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group>.input-group-append:last-child>.input-group-text:not(:last-child),.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.input-group-append>.btn,.input-group>.input-group-append>.input-group-text,.input-group>.input-group-prepend:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child),.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text{border-top-left-radius:0;border-bottom-left-radius:0}.custom-control{position:relative;display:block;min-height:1.5rem;padding-left:1.5rem}.custom-control-inline{display:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;z-index:-1;opacity:0}.custom-control-input:checked~.custom-control-label::before{color:#fff;border-color:#ae9b70;background-color:#ae9b70}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(174,155,112,.25)}.custom-control-input:focus:not(:checked)~.custom-control-label::before{border-color:#dcd4c1}.custom-control-input:not(:disabled):active~.custom-control-label::before{color:#fff;background-color:#efebe2;border-color:#efebe2}.custom-control-input:disabled~.custom-control-label{color:#6c757d}.custom-control-input:disabled~.custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0;vertical-align:top}.custom-control-label::before{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:"";background-color:#fff;border:#adb5bd solid 1px}.custom-control-label::after{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:"";background:no-repeat 50%/50% 50%}.custom-checkbox .custom-control-label::before{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before{border-color:#ae9b70;background-color:#ae9b70}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3e%3cpath stroke='%23fff' d='M0 2h4'/%3e%3c/svg%3e")}.custom-checkbox .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(174,155,112,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(174,155,112,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e")}.custom-radio .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(174,155,112,.5)}.custom-switch{padding-left:2.25rem}.custom-switch .custom-control-label::before{left:-2.25rem;width:1.75rem;pointer-events:all;border-radius:.5rem}.custom-switch .custom-control-label::after{top:calc(.25rem + 2px);left:calc(-2.25rem + 2px);width:calc(1rem - 4px);height:calc(1rem - 4px);background-color:#adb5bd;border-radius:.5rem;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-switch .custom-control-label::after{transition:none}}.custom-switch .custom-control-input:checked~.custom-control-label::after{background-color:#fff;transform:translateX(.75rem)}.custom-switch .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(174,155,112,.5)}.custom-select{display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem 1.75rem .375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;vertical-align:middle;background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem;appearance:none}.custom-select:focus{border-color:#dcd4c1;outline:0;box-shadow:0 0 0 .2rem rgba(174,155,112,.25)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size="1"]){height:auto;padding-right:.75rem;background-image:none}.custom-select:disabled{color:#6c757d;background-color:#e9ecef}.custom-select::-ms-expand{display:none}.custom-select-sm{height:calc(1.5em + .5rem + 2px);padding-top:.25rem;padding-bottom:.25rem;padding-left:.5rem;font-size:.875rem}.custom-select-lg{height:calc(1.5em + 1rem + 2px);padding-top:.5rem;padding-bottom:.5rem;padding-left:1rem;font-size:1.25rem}.custom-file{position:relative;display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);margin-bottom:0}.custom-file-input{position:relative;z-index:2;width:100%;height:calc(1.5em + .75rem + 2px);margin:0;opacity:0}.custom-file-input:focus~.custom-file-label{border-color:#dcd4c1;box-shadow:0 0 0 .2rem rgba(174,155,112,.25)}.custom-file-input:disabled~.custom-file-label{background-color:#e9ecef}.custom-file-input:lang(en)~.custom-file-label::after{content:"Browse"}.custom-file-input~.custom-file-label[data-browse]::after{content:attr(data-browse)}.custom-file-label{position:absolute;top:0;right:0;left:0;z-index:1;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:calc(1.5em + .75rem);padding:.375rem .75rem;line-height:1.5;color:#495057;content:"Browse";background-color:#e9ecef;border-left:inherit;border-radius:0 .25rem .25rem 0}.custom-range{width:100%;height:calc(1rem + .4rem);padding:0;background-color:transparent;appearance:none}.custom-range:focus{outline:0}.custom-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(174,155,112,.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(174,155,112,.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(174,155,112,.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#ae9b70;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-webkit-slider-thumb{transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#efebe2}.custom-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#ae9b70;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-moz-range-thumb{transition:none}}.custom-range::-moz-range-thumb:active{background-color:#efebe2}.custom-range::-moz-range-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-ms-thumb{width:1rem;height:1rem;margin-top:0;margin-right:.2rem;margin-left:.2rem;background-color:#ae9b70;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-ms-thumb{transition:none}}.custom-range::-ms-thumb:active{background-color:#efebe2}.custom-range::-ms-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:.5rem}.custom-range::-ms-fill-lower{background-color:#dee2e6;border-radius:1rem}.custom-range::-ms-fill-upper{margin-right:15px;background-color:#dee2e6;border-radius:1rem}.custom-range:disabled::-webkit-slider-thumb{background-color:#adb5bd}.custom-range:disabled::-webkit-slider-runnable-track{cursor:default}.custom-range:disabled::-moz-range-thumb{background-color:#adb5bd}.custom-range:disabled::-moz-range-track{cursor:default}.custom-range:disabled::-ms-thumb{background-color:#adb5bd}.custom-control-label::before,.custom-file-label,.custom-select{transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-control-label::before,.custom-file-label,.custom-select{transition:none}}.nav{display:flex;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#6c757d;pointer-events:none;cursor:default}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#ae9b70}.nav-fill .nav-item{flex:1 1 auto;text-align:center}.nav-justified .nav-item{flex-basis:0;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;padding:.5rem 1rem}.navbar>.container,.navbar>.container-fluid{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:flex;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{flex-basis:100%;flex-grow:1;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{text-decoration:none}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:"";background:no-repeat center center;background-size:100% 100%}@media (max-width:575.98px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:576px){.navbar-expand-sm{flex-flow:row nowrap;justify-content:flex-start}.navbar-expand-sm .navbar-nav{flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (max-width:767.98px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:768px){.navbar-expand-md{flex-flow:row nowrap;justify-content:flex-start}.navbar-expand-md .navbar-nav{flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (max-width:991.98px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:992px){.navbar-expand-lg{flex-flow:row nowrap;justify-content:flex-start}.navbar-expand-lg .navbar-nav{flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (max-width:1199.98px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:1200px){.navbar-expand-xl{flex-flow:row nowrap;justify-content:flex-start}.navbar-expand-xl .navbar-nav{flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{flex-flow:row nowrap;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid{flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:flex!important;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url("data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.navbar-light .navbar-text{color:rgba(0,0,0,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url("data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e")}.navbar-dark .navbar-text{color:rgba(255,255,255,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:flex;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{flex:1 1 auto;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img{width:100%;border-radius:calc(.25rem - 1px)}.card-img-top{width:100%;border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img-bottom{width:100%;border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck{display:flex;flex-direction:column}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{display:flex;flex:1 0 0%;flex-direction:column;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group{display:flex;flex-direction:column}.card-group>.card{margin-bottom:15px}@media (min-width:576px){.card-group{flex-flow:row wrap}.card-group>.card{flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:not(:last-child) .card-header,.card-group>.card:not(:last-child) .card-img-top{border-top-right-radius:0}.card-group>.card:not(:last-child) .card-footer,.card-group>.card:not(:last-child) .card-img-bottom{border-bottom-right-radius:0}.card-group>.card:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:not(:first-child) .card-header,.card-group>.card:not(:first-child) .card-img-top{border-top-left-radius:0}.card-group>.card:not(:first-child) .card-footer,.card-group>.card:not(:first-child) .card-img-bottom{border-bottom-left-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{column-count:3;column-gap:1.25rem;orphans:1;widows:1}.card-columns .card{display:inline-block;width:100%}}.accordion>.card{overflow:hidden}.accordion>.card:not(:first-of-type) .card-header:first-child{border-radius:0}.accordion>.card:not(:first-of-type):not(:last-of-type){border-bottom:0;border-radius:0}.accordion>.card:first-of-type{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}.accordion>.card:last-of-type{border-top-left-radius:0;border-top-right-radius:0}.accordion>.card .card-header{margin-bottom:-1px}.breadcrumb{display:flex;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;color:#6c757d;content:"/"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#6c757d}.pagination{display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#ae9b70;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#86744c;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:2;outline:0;box-shadow:0 0 0 .2rem rgba(174,155,112,.25)}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:1;color:#fff;background-color:#ae9b70;border-color:#ae9b70}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.badge{transition:none}}a.badge:focus,a.badge:hover{text-decoration:none}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#212529;background-color:#ae9b70}a.badge-primary:focus,a.badge-primary:hover{color:#212529;background-color:#968255}a.badge-primary.focus,a.badge-primary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(174,155,112,.5)}.badge-secondary{color:#212529;background-color:#dbceb1}a.badge-secondary:focus,a.badge-secondary:hover{color:#212529;background-color:#cbb88e}a.badge-secondary.focus,a.badge-secondary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(219,206,177,.5)}.badge-success{color:#fff;background-color:#007100}a.badge-success:focus,a.badge-success:hover{color:#fff;background-color:#003e00}a.badge-success.focus,a.badge-success:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,113,0,.5)}.badge-info{color:#fff;background-color:#005ba9}a.badge-info:focus,a.badge-info:hover{color:#fff;background-color:#004076}a.badge-info.focus,a.badge-info:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,91,169,.5)}.badge-warning{color:#fff;background-color:#ff7c00}a.badge-warning:focus,a.badge-warning:hover{color:#fff;background-color:#cc6300}a.badge-warning.focus,a.badge-warning:focus{outline:0;box-shadow:0 0 0 .2rem rgba(255,124,0,.5)}.badge-danger{color:#fff;background-color:#ae0000}a.badge-danger:focus,a.badge-danger:hover{color:#fff;background-color:#7b0000}a.badge-danger.focus,a.badge-danger:focus{outline:0;box-shadow:0 0 0 .2rem rgba(174,0,0,.5)}.badge-light{color:#212529;background-color:#f8f9fa}a.badge-light:focus,a.badge-light:hover{color:#212529;background-color:#dae0e5}a.badge-light.focus,a.badge-light:focus{outline:0;box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.badge-dark{color:#fff;background-color:#343a40}a.badge-dark:focus,a.badge-dark:hover{color:#fff;background-color:#1d2124}a.badge-dark.focus,a.badge-dark:focus{outline:0;box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:4rem}.alert-dismissible .close{position:absolute;top:0;right:0;padding:.75rem 1.25rem;color:inherit}.alert-primary{color:#5a513a;background-color:#efebe2;border-color:#e8e3d7}.alert-primary hr{border-top-color:#dfd8c7}.alert-primary .alert-link{color:#3b3526}.alert-secondary{color:#726b5c;background-color:#f8f5ef;border-color:#f5f1e9}.alert-secondary hr{border-top-color:#ede6d7}.alert-secondary .alert-link{color:#565145}.alert-success{color:#003b00;background-color:#cce3cc;border-color:#b8d7b8}.alert-success hr{border-top-color:#a8cea8}.alert-success .alert-link{color:#000800}.alert-info{color:#002f58;background-color:#ccdeee;border-color:#b8d1e7}.alert-info hr{border-top-color:#a5c5e1}.alert-info .alert-link{color:#001425}.alert-warning{color:#854000;background-color:#ffe5cc;border-color:#ffdab8}.alert-warning hr{border-top-color:#ffcd9f}.alert-warning .alert-link{color:#522700}.alert-danger{color:#5a0000;background-color:#efcccc;border-color:#e8b8b8}.alert-danger hr{border-top-color:#e2a5a5}.alert-danger .alert-link{color:#270000}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:flex;flex-direction:column;justify-content:center;color:#fff;text-align:center;white-space:nowrap;background-color:#ae9b70;transition:width .6s ease}@media (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{animation:progress-bar-stripes 1s linear infinite}@media (prefers-reduced-motion:reduce){.progress-bar-animated{animation:none}}.media{display:flex;align-items:flex-start}.media-body{flex:1}.list-group{display:flex;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{z-index:1;color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;margin-bottom:-1px;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;pointer-events:none;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#ae9b70;border-color:#ae9b70}.list-group-horizontal{flex-direction:row}.list-group-horizontal .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}@media (min-width:576px){.list-group-horizontal-sm{flex-direction:row}.list-group-horizontal-sm .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-sm .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-sm .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}@media (min-width:768px){.list-group-horizontal-md{flex-direction:row}.list-group-horizontal-md .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-md .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-md .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}@media (min-width:992px){.list-group-horizontal-lg{flex-direction:row}.list-group-horizontal-lg .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-lg .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-lg .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}@media (min-width:1200px){.list-group-horizontal-xl{flex-direction:row}.list-group-horizontal-xl .list-group-item{margin-right:-1px;margin-bottom:0}.list-group-horizontal-xl .list-group-item:first-child{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-xl .list-group-item:last-child{margin-right:0;border-top-right-radius:.25rem;border-bottom-right-radius:.25rem;border-bottom-left-radius:0}}.list-group-flush .list-group-item{border-right:0;border-left:0;border-radius:0}.list-group-flush .list-group-item:last-child{margin-bottom:-1px}.list-group-flush:first-child .list-group-item:first-child{border-top:0}.list-group-flush:last-child .list-group-item:last-child{margin-bottom:0;border-bottom:0}.list-group-item-primary{color:#5a513a;background-color:#e8e3d7}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#5a513a;background-color:#dfd8c7}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#5a513a;border-color:#5a513a}.list-group-item-secondary{color:#726b5c;background-color:#f5f1e9}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#726b5c;background-color:#ede6d7}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#726b5c;border-color:#726b5c}.list-group-item-success{color:#003b00;background-color:#b8d7b8}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#003b00;background-color:#a8cea8}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#003b00;border-color:#003b00}.list-group-item-info{color:#002f58;background-color:#b8d1e7}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#002f58;background-color:#a5c5e1}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#002f58;border-color:#002f58}.list-group-item-warning{color:#854000;background-color:#ffdab8}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#854000;background-color:#ffcd9f}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#854000;border-color:#854000}.list-group-item-danger{color:#5a0000;background-color:#e8b8b8}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#5a0000;background-color:#e2a5a5}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#5a0000;border-color:#5a0000}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{color:#818182;background-color:#ececf6}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}.list-group-item-dark.list-group-item-action:focus,.list-group-item-dark.list-group-item-action:hover{color:#1b1e21;background-color:#b9bbbe}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:hover{color:#000;text-decoration:none}.close:not(:disabled):not(.disabled):focus,.close:not(:disabled):not(.disabled):hover{opacity:.75}button.close{padding:0;background-color:transparent;border:0;appearance:none}a.close.disabled{pointer-events:none}.toast{max-width:350px;overflow:hidden;font-size:.875rem;background-color:rgba(255,255,255,.85);background-clip:padding-box;border:1px solid rgba(0,0,0,.1);box-shadow:0 .25rem .75rem rgba(0,0,0,.1);backdrop-filter:blur(10px);opacity:0;border-radius:.25rem}.toast:not(:last-child){margin-bottom:.75rem}.toast.showing{opacity:1}.toast.show{display:block;opacity:1}.toast.hide{display:none}.toast-header{display:flex;align-items:center;padding:.25rem .75rem;color:#6c757d;background-color:rgba(255,255,255,.85);background-clip:padding-box;border-bottom:1px solid rgba(0,0,0,.05)}.toast-body{padding:.75rem}.modal-open{overflow:hidden}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal{position:fixed;top:0;left:0;z-index:1050;display:none;width:100%;height:100%;overflow:hidden;outline:0}.modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:transform .3s ease-out;transform:translate(0,-50px)}@media (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{transform:none}.modal-dialog-scrollable{display:flex;max-height:calc(100% - 1rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 1rem);overflow:hidden}.modal-dialog-scrollable .modal-footer,.modal-dialog-scrollable .modal-header{flex-shrink:0}.modal-dialog-scrollable .modal-body{overflow-y:auto}.modal-dialog-centered{display:flex;align-items:center;min-height:calc(100% - 1rem)}.modal-dialog-centered::before{display:block;height:calc(100vh - 1rem);content:""}.modal-dialog-centered.modal-dialog-scrollable{flex-direction:column;justify-content:center;height:100%}.modal-dialog-centered.modal-dialog-scrollable .modal-content{max-height:none}.modal-dialog-centered.modal-dialog-scrollable::before{content:none}.modal-content{position:relative;display:flex;flex-direction:column;width:100%;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem;outline:0}.modal-backdrop{position:fixed;top:0;left:0;z-index:1040;width:100vw;height:100vh;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:1rem 1rem;border-bottom:1px solid #dee2e6;border-top-left-radius:.3rem;border-top-right-radius:.3rem}.modal-header .close{padding:1rem 1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;flex:1 1 auto;padding:1rem}.modal-footer{display:flex;align-items:center;justify-content:flex-end;padding:1rem;border-top:1px solid #dee2e6;border-bottom-right-radius:.3rem;border-bottom-left-radius:.3rem}.modal-footer>:not(:first-child){margin-left:.25rem}.modal-footer>:not(:last-child){margin-right:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-scrollable{max-height:calc(100% - 3.5rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 3.5rem)}.modal-dialog-centered{min-height:calc(100% - 3.5rem)}.modal-dialog-centered::before{height:calc(100vh - 3.5rem)}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg,.modal-xl{max-width:800px}}@media (min-width:1200px){.modal-xl{max-width:1140px}}.tooltip{position:absolute;z-index:1070;display:block;margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .arrow::before{position:absolute;content:"";border-color:transparent;border-style:solid}.bs-tooltip-auto[x-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[x-placement^=top] .arrow,.bs-tooltip-top .arrow{bottom:0}.bs-tooltip-auto[x-placement^=top] .arrow::before,.bs-tooltip-top .arrow::before{top:0;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[x-placement^=right],.bs-tooltip-right{padding:0 .4rem}.bs-tooltip-auto[x-placement^=right] .arrow,.bs-tooltip-right .arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=right] .arrow::before,.bs-tooltip-right .arrow::before{right:0;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[x-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[x-placement^=bottom] .arrow,.bs-tooltip-bottom .arrow{top:0}.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.bs-tooltip-bottom .arrow::before{bottom:0;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[x-placement^=left],.bs-tooltip-left{padding:0 .4rem}.bs-tooltip-auto[x-placement^=left] .arrow,.bs-tooltip-left .arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=left] .arrow::before,.bs-tooltip-left .arrow::before{left:0;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:.5rem;margin:0 .3rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;content:"";border-color:transparent;border-style:solid}.bs-popover-auto[x-placement^=top],.bs-popover-top{margin-bottom:.5rem}.bs-popover-auto[x-placement^=top]>.arrow,.bs-popover-top>.arrow{bottom:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=top]>.arrow::before,.bs-popover-top>.arrow::before{bottom:0;border-width:.5rem .5rem 0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=top]>.arrow::after,.bs-popover-top>.arrow::after{bottom:1px;border-width:.5rem .5rem 0;border-top-color:#fff}.bs-popover-auto[x-placement^=right],.bs-popover-right{margin-left:.5rem}.bs-popover-auto[x-placement^=right]>.arrow,.bs-popover-right>.arrow{left:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=right]>.arrow::before,.bs-popover-right>.arrow::before{left:0;border-width:.5rem .5rem .5rem 0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{left:1px;border-width:.5rem .5rem .5rem 0;border-right-color:#fff}.bs-popover-auto[x-placement^=bottom],.bs-popover-bottom{margin-top:.5rem}.bs-popover-auto[x-placement^=bottom]>.arrow,.bs-popover-bottom>.arrow{top:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=bottom]>.arrow::before,.bs-popover-bottom>.arrow::before{top:0;border-width:0 .5rem .5rem .5rem;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=bottom]>.arrow::after,.bs-popover-bottom>.arrow::after{top:1px;border-width:0 .5rem .5rem .5rem;border-bottom-color:#fff}.bs-popover-auto[x-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:"";border-bottom:1px solid #f7f7f7}.bs-popover-auto[x-placement^=left],.bs-popover-left{margin-right:.5rem}.bs-popover-auto[x-placement^=left]>.arrow,.bs-popover-left>.arrow{right:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=left]>.arrow::before,.bs-popover-left>.arrow::before{right:0;border-width:.5rem 0 .5rem .5rem;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=left]>.arrow::after,.bs-popover-left>.arrow::after{right:1px;border-width:.5rem 0 .5rem .5rem;border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel.pointer-event{touch-action:pan-y}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner::after{display:block;clear:both;content:""}.carousel-item{position:relative;display:none;float:left;width:100%;margin-right:-100%;backface-visibility:hidden;transition:transform .6s ease-in-out}@media (prefers-reduced-motion:reduce){.carousel-item{transition:none}}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block}.active.carousel-item-right,.carousel-item-next:not(.carousel-item-left){transform:translateX(100%)}.active.carousel-item-left,.carousel-item-prev:not(.carousel-item-right){transform:translateX(-100%)}.carousel-fade .carousel-item{opacity:0;transition-property:opacity;transform:none}.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right,.carousel-fade .carousel-item.active{z-index:1;opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{z-index:0;opacity:0;transition:0s .6s opacity}@media (prefers-reduced-motion:reduce){.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{transition:none}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;z-index:1;display:flex;align-items:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5;transition:opacity .15s ease}@media (prefers-reduced-motion:reduce){.carousel-control-next,.carousel-control-prev{transition:none}}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:20px;height:20px;background:no-repeat 50%/100% 100%}.carousel-control-prev-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3e%3c/svg%3e")}.carousel-control-next-icon{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3e%3c/svg%3e")}.carousel-indicators{position:absolute;right:0;bottom:0;left:0;z-index:15;display:flex;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{box-sizing:content-box;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:#fff;background-clip:padding-box;border-top:10px solid transparent;border-bottom:10px solid transparent;opacity:.5;transition:opacity .6s ease}@media (prefers-reduced-motion:reduce){.carousel-indicators li{transition:none}}.carousel-indicators .active{opacity:1}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}@keyframes spinner-border{to{transform:rotate(360deg)}}.spinner-border{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;border:.25em solid currentColor;border-right-color:transparent;border-radius:50%;animation:spinner-border .75s linear infinite}.spinner-border-sm{width:1rem;height:1rem;border-width:.2em}@keyframes spinner-grow{0%{transform:scale(0)}50%{opacity:1}}.spinner-grow{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;background-color:currentColor;border-radius:50%;opacity:0;animation:spinner-grow .75s linear infinite}.spinner-grow-sm{width:1rem;height:1rem}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.bg-primary{background-color:#ae9b70!important}a.bg-primary:focus,a.bg-primary:hover,button.bg-primary:focus,button.bg-primary:hover{background-color:#968255!important}.bg-secondary{background-color:#dbceb1!important}a.bg-secondary:focus,a.bg-secondary:hover,button.bg-secondary:focus,button.bg-secondary:hover{background-color:#cbb88e!important}.bg-success{background-color:#007100!important}a.bg-success:focus,a.bg-success:hover,button.bg-success:focus,button.bg-success:hover{background-color:#003e00!important}.bg-info{background-color:#005ba9!important}a.bg-info:focus,a.bg-info:hover,button.bg-info:focus,button.bg-info:hover{background-color:#004076!important}.bg-warning{background-color:#ff7c00!important}a.bg-warning:focus,a.bg-warning:hover,button.bg-warning:focus,button.bg-warning:hover{background-color:#cc6300!important}.bg-danger{background-color:#ae0000!important}a.bg-danger:focus,a.bg-danger:hover,button.bg-danger:focus,button.bg-danger:hover{background-color:#7b0000!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover,button.bg-light:focus,button.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover,button.bg-dark:focus,button.bg-dark:hover{background-color:#1d2124!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.border{border:1px solid #dee2e6!important}.border-top{border-top:1px solid #dee2e6!important}.border-right{border-right:1px solid #dee2e6!important}.border-bottom{border-bottom:1px solid #dee2e6!important}.border-left{border-left:1px solid #dee2e6!important}.border-0{border:0!important}.border-top-0{border-top:0!important}.border-right-0{border-right:0!important}.border-bottom-0{border-bottom:0!important}.border-left-0{border-left:0!important}.border-primary{border-color:#ae9b70!important}.border-secondary{border-color:#dbceb1!important}.border-success{border-color:#007100!important}.border-info{border-color:#005ba9!important}.border-warning{border-color:#ff7c00!important}.border-danger{border-color:#ae0000!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded-sm{border-radius:.2rem!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-lg{border-radius:.3rem!important}.rounded-circle{border-radius:50%!important}.rounded-pill{border-radius:50rem!important}.rounded-0{border-radius:0!important}.clearfix::after{display:block;clear:both;content:""}.d-none{display:none!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:flex!important}.d-inline-flex{display:inline-flex!important}@media (min-width:576px){.d-sm-none{display:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:flex!important}.d-sm-inline-flex{display:inline-flex!important}}@media (min-width:768px){.d-md-none{display:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:flex!important}.d-md-inline-flex{display:inline-flex!important}}@media (min-width:992px){.d-lg-none{display:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:flex!important}.d-lg-inline-flex{display:inline-flex!important}}@media (min-width:1200px){.d-xl-none{display:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:flex!important}.d-xl-inline-flex{display:inline-flex!important}}@media print{.d-print-none{display:none!important}.d-print-inline{display:inline!important}.d-print-inline-block{display:inline-block!important}.d-print-block{display:block!important}.d-print-table{display:table!important}.d-print-table-row{display:table-row!important}.d-print-table-cell{display:table-cell!important}.d-print-flex{display:flex!important}.d-print-inline-flex{display:inline-flex!important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:""}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.85714%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{flex-direction:row!important}.flex-column{flex-direction:column!important}.flex-row-reverse{flex-direction:row-reverse!important}.flex-column-reverse{flex-direction:column-reverse!important}.flex-wrap{flex-wrap:wrap!important}.flex-nowrap{flex-wrap:nowrap!important}.flex-wrap-reverse{flex-wrap:wrap-reverse!important}.flex-fill{flex:1 1 auto!important}.flex-grow-0{flex-grow:0!important}.flex-grow-1{flex-grow:1!important}.flex-shrink-0{flex-shrink:0!important}.flex-shrink-1{flex-shrink:1!important}.justify-content-start{justify-content:flex-start!important}.justify-content-end{justify-content:flex-end!important}.justify-content-center{justify-content:center!important}.justify-content-between{justify-content:space-between!important}.justify-content-around{justify-content:space-around!important}.align-items-start{align-items:flex-start!important}.align-items-end{align-items:flex-end!important}.align-items-center{align-items:center!important}.align-items-baseline{align-items:baseline!important}.align-items-stretch{align-items:stretch!important}.align-content-start{align-content:flex-start!important}.align-content-end{align-content:flex-end!important}.align-content-center{align-content:center!important}.align-content-between{align-content:space-between!important}.align-content-around{align-content:space-around!important}.align-content-stretch{align-content:stretch!important}.align-self-auto{align-self:auto!important}.align-self-start{align-self:flex-start!important}.align-self-end{align-self:flex-end!important}.align-self-center{align-self:center!important}.align-self-baseline{align-self:baseline!important}.align-self-stretch{align-self:stretch!important}@media (min-width:576px){.flex-sm-row{flex-direction:row!important}.flex-sm-column{flex-direction:column!important}.flex-sm-row-reverse{flex-direction:row-reverse!important}.flex-sm-column-reverse{flex-direction:column-reverse!important}.flex-sm-wrap{flex-wrap:wrap!important}.flex-sm-nowrap{flex-wrap:nowrap!important}.flex-sm-wrap-reverse{flex-wrap:wrap-reverse!important}.flex-sm-fill{flex:1 1 auto!important}.flex-sm-grow-0{flex-grow:0!important}.flex-sm-grow-1{flex-grow:1!important}.flex-sm-shrink-0{flex-shrink:0!important}.flex-sm-shrink-1{flex-shrink:1!important}.justify-content-sm-start{justify-content:flex-start!important}.justify-content-sm-end{justify-content:flex-end!important}.justify-content-sm-center{justify-content:center!important}.justify-content-sm-between{justify-content:space-between!important}.justify-content-sm-around{justify-content:space-around!important}.align-items-sm-start{align-items:flex-start!important}.align-items-sm-end{align-items:flex-end!important}.align-items-sm-center{align-items:center!important}.align-items-sm-baseline{align-items:baseline!important}.align-items-sm-stretch{align-items:stretch!important}.align-content-sm-start{align-content:flex-start!important}.align-content-sm-end{align-content:flex-end!important}.align-content-sm-center{align-content:center!important}.align-content-sm-between{align-content:space-between!important}.align-content-sm-around{align-content:space-around!important}.align-content-sm-stretch{align-content:stretch!important}.align-self-sm-auto{align-self:auto!important}.align-self-sm-start{align-self:flex-start!important}.align-self-sm-end{align-self:flex-end!important}.align-self-sm-center{align-self:center!important}.align-self-sm-baseline{align-self:baseline!important}.align-self-sm-stretch{align-self:stretch!important}}@media (min-width:768px){.flex-md-row{flex-direction:row!important}.flex-md-column{flex-direction:column!important}.flex-md-row-reverse{flex-direction:row-reverse!important}.flex-md-column-reverse{flex-direction:column-reverse!important}.flex-md-wrap{flex-wrap:wrap!important}.flex-md-nowrap{flex-wrap:nowrap!important}.flex-md-wrap-reverse{flex-wrap:wrap-reverse!important}.flex-md-fill{flex:1 1 auto!important}.flex-md-grow-0{flex-grow:0!important}.flex-md-grow-1{flex-grow:1!important}.flex-md-shrink-0{flex-shrink:0!important}.flex-md-shrink-1{flex-shrink:1!important}.justify-content-md-start{justify-content:flex-start!important}.justify-content-md-end{justify-content:flex-end!important}.justify-content-md-center{justify-content:center!important}.justify-content-md-between{justify-content:space-between!important}.justify-content-md-around{justify-content:space-around!important}.align-items-md-start{align-items:flex-start!important}.align-items-md-end{align-items:flex-end!important}.align-items-md-center{align-items:center!important}.align-items-md-baseline{align-items:baseline!important}.align-items-md-stretch{align-items:stretch!important}.align-content-md-start{align-content:flex-start!important}.align-content-md-end{align-content:flex-end!important}.align-content-md-center{align-content:center!important}.align-content-md-between{align-content:space-between!important}.align-content-md-around{align-content:space-around!important}.align-content-md-stretch{align-content:stretch!important}.align-self-md-auto{align-self:auto!important}.align-self-md-start{align-self:flex-start!important}.align-self-md-end{align-self:flex-end!important}.align-self-md-center{align-self:center!important}.align-self-md-baseline{align-self:baseline!important}.align-self-md-stretch{align-self:stretch!important}}@media (min-width:992px){.flex-lg-row{flex-direction:row!important}.flex-lg-column{flex-direction:column!important}.flex-lg-row-reverse{flex-direction:row-reverse!important}.flex-lg-column-reverse{flex-direction:column-reverse!important}.flex-lg-wrap{flex-wrap:wrap!important}.flex-lg-nowrap{flex-wrap:nowrap!important}.flex-lg-wrap-reverse{flex-wrap:wrap-reverse!important}.flex-lg-fill{flex:1 1 auto!important}.flex-lg-grow-0{flex-grow:0!important}.flex-lg-grow-1{flex-grow:1!important}.flex-lg-shrink-0{flex-shrink:0!important}.flex-lg-shrink-1{flex-shrink:1!important}.justify-content-lg-start{justify-content:flex-start!important}.justify-content-lg-end{justify-content:flex-end!important}.justify-content-lg-center{justify-content:center!important}.justify-content-lg-between{justify-content:space-between!important}.justify-content-lg-around{justify-content:space-around!important}.align-items-lg-start{align-items:flex-start!important}.align-items-lg-end{align-items:flex-end!important}.align-items-lg-center{align-items:center!important}.align-items-lg-baseline{align-items:baseline!important}.align-items-lg-stretch{align-items:stretch!important}.align-content-lg-start{align-content:flex-start!important}.align-content-lg-end{align-content:flex-end!important}.align-content-lg-center{align-content:center!important}.align-content-lg-between{align-content:space-between!important}.align-content-lg-around{align-content:space-around!important}.align-content-lg-stretch{align-content:stretch!important}.align-self-lg-auto{align-self:auto!important}.align-self-lg-start{align-self:flex-start!important}.align-self-lg-end{align-self:flex-end!important}.align-self-lg-center{align-self:center!important}.align-self-lg-baseline{align-self:baseline!important}.align-self-lg-stretch{align-self:stretch!important}}@media (min-width:1200px){.flex-xl-row{flex-direction:row!important}.flex-xl-column{flex-direction:column!important}.flex-xl-row-reverse{flex-direction:row-reverse!important}.flex-xl-column-reverse{flex-direction:column-reverse!important}.flex-xl-wrap{flex-wrap:wrap!important}.flex-xl-nowrap{flex-wrap:nowrap!important}.flex-xl-wrap-reverse{flex-wrap:wrap-reverse!important}.flex-xl-fill{flex:1 1 auto!important}.flex-xl-grow-0{flex-grow:0!important}.flex-xl-grow-1{flex-grow:1!important}.flex-xl-shrink-0{flex-shrink:0!important}.flex-xl-shrink-1{flex-shrink:1!important}.justify-content-xl-start{justify-content:flex-start!important}.justify-content-xl-end{justify-content:flex-end!important}.justify-content-xl-center{justify-content:center!important}.justify-content-xl-between{justify-content:space-between!important}.justify-content-xl-around{justify-content:space-around!important}.align-items-xl-start{align-items:flex-start!important}.align-items-xl-end{align-items:flex-end!important}.align-items-xl-center{align-items:center!important}.align-items-xl-baseline{align-items:baseline!important}.align-items-xl-stretch{align-items:stretch!important}.align-content-xl-start{align-content:flex-start!important}.align-content-xl-end{align-content:flex-end!important}.align-content-xl-center{align-content:center!important}.align-content-xl-between{align-content:space-between!important}.align-content-xl-around{align-content:space-around!important}.align-content-xl-stretch{align-content:stretch!important}.align-self-xl-auto{align-self:auto!important}.align-self-xl-start{align-self:flex-start!important}.align-self-xl-end{align-self:flex-end!important}.align-self-xl-center{align-self:center!important}.align-self-xl-baseline{align-self:baseline!important}.align-self-xl-stretch{align-self:stretch!important}}.float-left{float:left!important}.float-right{float:right!important}.float-none{float:none!important}@media (min-width:576px){.float-sm-left{float:left!important}.float-sm-right{float:right!important}.float-sm-none{float:none!important}}@media (min-width:768px){.float-md-left{float:left!important}.float-md-right{float:right!important}.float-md-none{float:none!important}}@media (min-width:992px){.float-lg-left{float:left!important}.float-lg-right{float:right!important}.float-lg-none{float:none!important}}@media (min-width:1200px){.float-xl-left{float:left!important}.float-xl-right{float:right!important}.float-xl-none{float:none!important}}.overflow-auto{overflow:auto!important}.overflow-hidden{overflow:hidden!important}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:sticky!important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports (position:sticky){.sticky-top{position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal}.shadow-sm{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{box-shadow:none!important}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.w-auto{width:auto!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.h-auto{height:auto!important}.mw-100{max-width:100%!important}.mh-100{max-height:100%!important}.min-vw-100{min-width:100vw!important}.min-vh-100{min-height:100vh!important}.vw-100{width:100vw!important}.vh-100{height:100vh!important}.stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;pointer-events:auto;content:"";background-color:rgba(0,0,0,0)}.m-0{margin:0!important}.mt-0,.my-0{margin-top:0!important}.mr-0,.mx-0{margin-right:0!important}.mb-0,.my-0{margin-bottom:0!important}.ml-0,.mx-0{margin-left:0!important}.m-1{margin:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.5rem!important}.m-3{margin:1rem!important}.mt-3,.my-3{margin-top:1rem!important}.mr-3,.mx-3{margin-right:1rem!important}.mb-3,.my-3{margin-bottom:1rem!important}.ml-3,.mx-3{margin-left:1rem!important}.m-4{margin:1.5rem!important}.mt-4,.my-4{margin-top:1.5rem!important}.mr-4,.mx-4{margin-right:1.5rem!important}.mb-4,.my-4{margin-bottom:1.5rem!important}.ml-4,.mx-4{margin-left:1.5rem!important}.m-5{margin:3rem!important}.mt-5,.my-5{margin-top:3rem!important}.mr-5,.mx-5{margin-right:3rem!important}.mb-5,.my-5{margin-bottom:3rem!important}.ml-5,.mx-5{margin-left:3rem!important}.p-0{padding:0!important}.pt-0,.py-0{padding-top:0!important}.pr-0,.px-0{padding-right:0!important}.pb-0,.py-0{padding-bottom:0!important}.pl-0,.px-0{padding-left:0!important}.p-1{padding:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.5rem!important}.p-3{padding:1rem!important}.pt-3,.py-3{padding-top:1rem!important}.pr-3,.px-3{padding-right:1rem!important}.pb-3,.py-3{padding-bottom:1rem!important}.pl-3,.px-3{padding-left:1rem!important}.p-4{padding:1.5rem!important}.pt-4,.py-4{padding-top:1.5rem!important}.pr-4,.px-4{padding-right:1.5rem!important}.pb-4,.py-4{padding-bottom:1.5rem!important}.pl-4,.px-4{padding-left:1.5rem!important}.p-5{padding:3rem!important}.pt-5,.py-5{padding-top:3rem!important}.pr-5,.px-5{padding-right:3rem!important}.pb-5,.py-5{padding-bottom:3rem!important}.pl-5,.px-5{padding-left:3rem!important}.m-n1{margin:-.25rem!important}.mt-n1,.my-n1{margin-top:-.25rem!important}.mr-n1,.mx-n1{margin-right:-.25rem!important}.mb-n1,.my-n1{margin-bottom:-.25rem!important}.ml-n1,.mx-n1{margin-left:-.25rem!important}.m-n2{margin:-.5rem!important}.mt-n2,.my-n2{margin-top:-.5rem!important}.mr-n2,.mx-n2{margin-right:-.5rem!important}.mb-n2,.my-n2{margin-bottom:-.5rem!important}.ml-n2,.mx-n2{margin-left:-.5rem!important}.m-n3{margin:-1rem!important}.mt-n3,.my-n3{margin-top:-1rem!important}.mr-n3,.mx-n3{margin-right:-1rem!important}.mb-n3,.my-n3{margin-bottom:-1rem!important}.ml-n3,.mx-n3{margin-left:-1rem!important}.m-n4{margin:-1.5rem!important}.mt-n4,.my-n4{margin-top:-1.5rem!important}.mr-n4,.mx-n4{margin-right:-1.5rem!important}.mb-n4,.my-n4{margin-bottom:-1.5rem!important}.ml-n4,.mx-n4{margin-left:-1.5rem!important}.m-n5{margin:-3rem!important}.mt-n5,.my-n5{margin-top:-3rem!important}.mr-n5,.mx-n5{margin-right:-3rem!important}.mb-n5,.my-n5{margin-bottom:-3rem!important}.ml-n5,.mx-n5{margin-left:-3rem!important}.m-auto{margin:auto!important}.mt-auto,.my-auto{margin-top:auto!important}.mr-auto,.mx-auto{margin-right:auto!important}.mb-auto,.my-auto{margin-bottom:auto!important}.ml-auto,.mx-auto{margin-left:auto!important}@media (min-width:576px){.m-sm-0{margin:0!important}.mt-sm-0,.my-sm-0{margin-top:0!important}.mr-sm-0,.mx-sm-0{margin-right:0!important}.mb-sm-0,.my-sm-0{margin-bottom:0!important}.ml-sm-0,.mx-sm-0{margin-left:0!important}.m-sm-1{margin:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.5rem!important}.m-sm-3{margin:1rem!important}.mt-sm-3,.my-sm-3{margin-top:1rem!important}.mr-sm-3,.mx-sm-3{margin-right:1rem!important}.mb-sm-3,.my-sm-3{margin-bottom:1rem!important}.ml-sm-3,.mx-sm-3{margin-left:1rem!important}.m-sm-4{margin:1.5rem!important}.mt-sm-4,.my-sm-4{margin-top:1.5rem!important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem!important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem!important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem!important}.m-sm-5{margin:3rem!important}.mt-sm-5,.my-sm-5{margin-top:3rem!important}.mr-sm-5,.mx-sm-5{margin-right:3rem!important}.mb-sm-5,.my-sm-5{margin-bottom:3rem!important}.ml-sm-5,.mx-sm-5{margin-left:3rem!important}.p-sm-0{padding:0!important}.pt-sm-0,.py-sm-0{padding-top:0!important}.pr-sm-0,.px-sm-0{padding-right:0!important}.pb-sm-0,.py-sm-0{padding-bottom:0!important}.pl-sm-0,.px-sm-0{padding-left:0!important}.p-sm-1{padding:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.5rem!important}.p-sm-3{padding:1rem!important}.pt-sm-3,.py-sm-3{padding-top:1rem!important}.pr-sm-3,.px-sm-3{padding-right:1rem!important}.pb-sm-3,.py-sm-3{padding-bottom:1rem!important}.pl-sm-3,.px-sm-3{padding-left:1rem!important}.p-sm-4{padding:1.5rem!important}.pt-sm-4,.py-sm-4{padding-top:1.5rem!important}.pr-sm-4,.px-sm-4{padding-right:1.5rem!important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem!important}.pl-sm-4,.px-sm-4{padding-left:1.5rem!important}.p-sm-5{padding:3rem!important}.pt-sm-5,.py-sm-5{padding-top:3rem!important}.pr-sm-5,.px-sm-5{padding-right:3rem!important}.pb-sm-5,.py-sm-5{padding-bottom:3rem!important}.pl-sm-5,.px-sm-5{padding-left:3rem!important}.m-sm-n1{margin:-.25rem!important}.mt-sm-n1,.my-sm-n1{margin-top:-.25rem!important}.mr-sm-n1,.mx-sm-n1{margin-right:-.25rem!important}.mb-sm-n1,.my-sm-n1{margin-bottom:-.25rem!important}.ml-sm-n1,.mx-sm-n1{margin-left:-.25rem!important}.m-sm-n2{margin:-.5rem!important}.mt-sm-n2,.my-sm-n2{margin-top:-.5rem!important}.mr-sm-n2,.mx-sm-n2{margin-right:-.5rem!important}.mb-sm-n2,.my-sm-n2{margin-bottom:-.5rem!important}.ml-sm-n2,.mx-sm-n2{margin-left:-.5rem!important}.m-sm-n3{margin:-1rem!important}.mt-sm-n3,.my-sm-n3{margin-top:-1rem!important}.mr-sm-n3,.mx-sm-n3{margin-right:-1rem!important}.mb-sm-n3,.my-sm-n3{margin-bottom:-1rem!important}.ml-sm-n3,.mx-sm-n3{margin-left:-1rem!important}.m-sm-n4{margin:-1.5rem!important}.mt-sm-n4,.my-sm-n4{margin-top:-1.5rem!important}.mr-sm-n4,.mx-sm-n4{margin-right:-1.5rem!important}.mb-sm-n4,.my-sm-n4{margin-bottom:-1.5rem!important}.ml-sm-n4,.mx-sm-n4{margin-left:-1.5rem!important}.m-sm-n5{margin:-3rem!important}.mt-sm-n5,.my-sm-n5{margin-top:-3rem!important}.mr-sm-n5,.mx-sm-n5{margin-right:-3rem!important}.mb-sm-n5,.my-sm-n5{margin-bottom:-3rem!important}.ml-sm-n5,.mx-sm-n5{margin-left:-3rem!important}.m-sm-auto{margin:auto!important}.mt-sm-auto,.my-sm-auto{margin-top:auto!important}.mr-sm-auto,.mx-sm-auto{margin-right:auto!important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto!important}.ml-sm-auto,.mx-sm-auto{margin-left:auto!important}}@media (min-width:768px){.m-md-0{margin:0!important}.mt-md-0,.my-md-0{margin-top:0!important}.mr-md-0,.mx-md-0{margin-right:0!important}.mb-md-0,.my-md-0{margin-bottom:0!important}.ml-md-0,.mx-md-0{margin-left:0!important}.m-md-1{margin:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.5rem!important}.m-md-3{margin:1rem!important}.mt-md-3,.my-md-3{margin-top:1rem!important}.mr-md-3,.mx-md-3{margin-right:1rem!important}.mb-md-3,.my-md-3{margin-bottom:1rem!important}.ml-md-3,.mx-md-3{margin-left:1rem!important}.m-md-4{margin:1.5rem!important}.mt-md-4,.my-md-4{margin-top:1.5rem!important}.mr-md-4,.mx-md-4{margin-right:1.5rem!important}.mb-md-4,.my-md-4{margin-bottom:1.5rem!important}.ml-md-4,.mx-md-4{margin-left:1.5rem!important}.m-md-5{margin:3rem!important}.mt-md-5,.my-md-5{margin-top:3rem!important}.mr-md-5,.mx-md-5{margin-right:3rem!important}.mb-md-5,.my-md-5{margin-bottom:3rem!important}.ml-md-5,.mx-md-5{margin-left:3rem!important}.p-md-0{padding:0!important}.pt-md-0,.py-md-0{padding-top:0!important}.pr-md-0,.px-md-0{padding-right:0!important}.pb-md-0,.py-md-0{padding-bottom:0!important}.pl-md-0,.px-md-0{padding-left:0!important}.p-md-1{padding:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.5rem!important}.p-md-3{padding:1rem!important}.pt-md-3,.py-md-3{padding-top:1rem!important}.pr-md-3,.px-md-3{padding-right:1rem!important}.pb-md-3,.py-md-3{padding-bottom:1rem!important}.pl-md-3,.px-md-3{padding-left:1rem!important}.p-md-4{padding:1.5rem!important}.pt-md-4,.py-md-4{padding-top:1.5rem!important}.pr-md-4,.px-md-4{padding-right:1.5rem!important}.pb-md-4,.py-md-4{padding-bottom:1.5rem!important}.pl-md-4,.px-md-4{padding-left:1.5rem!important}.p-md-5{padding:3rem!important}.pt-md-5,.py-md-5{padding-top:3rem!important}.pr-md-5,.px-md-5{padding-right:3rem!important}.pb-md-5,.py-md-5{padding-bottom:3rem!important}.pl-md-5,.px-md-5{padding-left:3rem!important}.m-md-n1{margin:-.25rem!important}.mt-md-n1,.my-md-n1{margin-top:-.25rem!important}.mr-md-n1,.mx-md-n1{margin-right:-.25rem!important}.mb-md-n1,.my-md-n1{margin-bottom:-.25rem!important}.ml-md-n1,.mx-md-n1{margin-left:-.25rem!important}.m-md-n2{margin:-.5rem!important}.mt-md-n2,.my-md-n2{margin-top:-.5rem!important}.mr-md-n2,.mx-md-n2{margin-right:-.5rem!important}.mb-md-n2,.my-md-n2{margin-bottom:-.5rem!important}.ml-md-n2,.mx-md-n2{margin-left:-.5rem!important}.m-md-n3{margin:-1rem!important}.mt-md-n3,.my-md-n3{margin-top:-1rem!important}.mr-md-n3,.mx-md-n3{margin-right:-1rem!important}.mb-md-n3,.my-md-n3{margin-bottom:-1rem!important}.ml-md-n3,.mx-md-n3{margin-left:-1rem!important}.m-md-n4{margin:-1.5rem!important}.mt-md-n4,.my-md-n4{margin-top:-1.5rem!important}.mr-md-n4,.mx-md-n4{margin-right:-1.5rem!important}.mb-md-n4,.my-md-n4{margin-bottom:-1.5rem!important}.ml-md-n4,.mx-md-n4{margin-left:-1.5rem!important}.m-md-n5{margin:-3rem!important}.mt-md-n5,.my-md-n5{margin-top:-3rem!important}.mr-md-n5,.mx-md-n5{margin-right:-3rem!important}.mb-md-n5,.my-md-n5{margin-bottom:-3rem!important}.ml-md-n5,.mx-md-n5{margin-left:-3rem!important}.m-md-auto{margin:auto!important}.mt-md-auto,.my-md-auto{margin-top:auto!important}.mr-md-auto,.mx-md-auto{margin-right:auto!important}.mb-md-auto,.my-md-auto{margin-bottom:auto!important}.ml-md-auto,.mx-md-auto{margin-left:auto!important}}@media (min-width:992px){.m-lg-0{margin:0!important}.mt-lg-0,.my-lg-0{margin-top:0!important}.mr-lg-0,.mx-lg-0{margin-right:0!important}.mb-lg-0,.my-lg-0{margin-bottom:0!important}.ml-lg-0,.mx-lg-0{margin-left:0!important}.m-lg-1{margin:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.5rem!important}.m-lg-3{margin:1rem!important}.mt-lg-3,.my-lg-3{margin-top:1rem!important}.mr-lg-3,.mx-lg-3{margin-right:1rem!important}.mb-lg-3,.my-lg-3{margin-bottom:1rem!important}.ml-lg-3,.mx-lg-3{margin-left:1rem!important}.m-lg-4{margin:1.5rem!important}.mt-lg-4,.my-lg-4{margin-top:1.5rem!important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem!important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem!important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem!important}.m-lg-5{margin:3rem!important}.mt-lg-5,.my-lg-5{margin-top:3rem!important}.mr-lg-5,.mx-lg-5{margin-right:3rem!important}.mb-lg-5,.my-lg-5{margin-bottom:3rem!important}.ml-lg-5,.mx-lg-5{margin-left:3rem!important}.p-lg-0{padding:0!important}.pt-lg-0,.py-lg-0{padding-top:0!important}.pr-lg-0,.px-lg-0{padding-right:0!important}.pb-lg-0,.py-lg-0{padding-bottom:0!important}.pl-lg-0,.px-lg-0{padding-left:0!important}.p-lg-1{padding:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.5rem!important}.p-lg-3{padding:1rem!important}.pt-lg-3,.py-lg-3{padding-top:1rem!important}.pr-lg-3,.px-lg-3{padding-right:1rem!important}.pb-lg-3,.py-lg-3{padding-bottom:1rem!important}.pl-lg-3,.px-lg-3{padding-left:1rem!important}.p-lg-4{padding:1.5rem!important}.pt-lg-4,.py-lg-4{padding-top:1.5rem!important}.pr-lg-4,.px-lg-4{padding-right:1.5rem!important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem!important}.pl-lg-4,.px-lg-4{padding-left:1.5rem!important}.p-lg-5{padding:3rem!important}.pt-lg-5,.py-lg-5{padding-top:3rem!important}.pr-lg-5,.px-lg-5{padding-right:3rem!important}.pb-lg-5,.py-lg-5{padding-bottom:3rem!important}.pl-lg-5,.px-lg-5{padding-left:3rem!important}.m-lg-n1{margin:-.25rem!important}.mt-lg-n1,.my-lg-n1{margin-top:-.25rem!important}.mr-lg-n1,.mx-lg-n1{margin-right:-.25rem!important}.mb-lg-n1,.my-lg-n1{margin-bottom:-.25rem!important}.ml-lg-n1,.mx-lg-n1{margin-left:-.25rem!important}.m-lg-n2{margin:-.5rem!important}.mt-lg-n2,.my-lg-n2{margin-top:-.5rem!important}.mr-lg-n2,.mx-lg-n2{margin-right:-.5rem!important}.mb-lg-n2,.my-lg-n2{margin-bottom:-.5rem!important}.ml-lg-n2,.mx-lg-n2{margin-left:-.5rem!important}.m-lg-n3{margin:-1rem!important}.mt-lg-n3,.my-lg-n3{margin-top:-1rem!important}.mr-lg-n3,.mx-lg-n3{margin-right:-1rem!important}.mb-lg-n3,.my-lg-n3{margin-bottom:-1rem!important}.ml-lg-n3,.mx-lg-n3{margin-left:-1rem!important}.m-lg-n4{margin:-1.5rem!important}.mt-lg-n4,.my-lg-n4{margin-top:-1.5rem!important}.mr-lg-n4,.mx-lg-n4{margin-right:-1.5rem!important}.mb-lg-n4,.my-lg-n4{margin-bottom:-1.5rem!important}.ml-lg-n4,.mx-lg-n4{margin-left:-1.5rem!important}.m-lg-n5{margin:-3rem!important}.mt-lg-n5,.my-lg-n5{margin-top:-3rem!important}.mr-lg-n5,.mx-lg-n5{margin-right:-3rem!important}.mb-lg-n5,.my-lg-n5{margin-bottom:-3rem!important}.ml-lg-n5,.mx-lg-n5{margin-left:-3rem!important}.m-lg-auto{margin:auto!important}.mt-lg-auto,.my-lg-auto{margin-top:auto!important}.mr-lg-auto,.mx-lg-auto{margin-right:auto!important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto!important}.ml-lg-auto,.mx-lg-auto{margin-left:auto!important}}@media (min-width:1200px){.m-xl-0{margin:0!important}.mt-xl-0,.my-xl-0{margin-top:0!important}.mr-xl-0,.mx-xl-0{margin-right:0!important}.mb-xl-0,.my-xl-0{margin-bottom:0!important}.ml-xl-0,.mx-xl-0{margin-left:0!important}.m-xl-1{margin:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.5rem!important}.m-xl-3{margin:1rem!important}.mt-xl-3,.my-xl-3{margin-top:1rem!important}.mr-xl-3,.mx-xl-3{margin-right:1rem!important}.mb-xl-3,.my-xl-3{margin-bottom:1rem!important}.ml-xl-3,.mx-xl-3{margin-left:1rem!important}.m-xl-4{margin:1.5rem!important}.mt-xl-4,.my-xl-4{margin-top:1.5rem!important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem!important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem!important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem!important}.m-xl-5{margin:3rem!important}.mt-xl-5,.my-xl-5{margin-top:3rem!important}.mr-xl-5,.mx-xl-5{margin-right:3rem!important}.mb-xl-5,.my-xl-5{margin-bottom:3rem!important}.ml-xl-5,.mx-xl-5{margin-left:3rem!important}.p-xl-0{padding:0!important}.pt-xl-0,.py-xl-0{padding-top:0!important}.pr-xl-0,.px-xl-0{padding-right:0!important}.pb-xl-0,.py-xl-0{padding-bottom:0!important}.pl-xl-0,.px-xl-0{padding-left:0!important}.p-xl-1{padding:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.5rem!important}.p-xl-3{padding:1rem!important}.pt-xl-3,.py-xl-3{padding-top:1rem!important}.pr-xl-3,.px-xl-3{padding-right:1rem!important}.pb-xl-3,.py-xl-3{padding-bottom:1rem!important}.pl-xl-3,.px-xl-3{padding-left:1rem!important}.p-xl-4{padding:1.5rem!important}.pt-xl-4,.py-xl-4{padding-top:1.5rem!important}.pr-xl-4,.px-xl-4{padding-right:1.5rem!important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem!important}.pl-xl-4,.px-xl-4{padding-left:1.5rem!important}.p-xl-5{padding:3rem!important}.pt-xl-5,.py-xl-5{padding-top:3rem!important}.pr-xl-5,.px-xl-5{padding-right:3rem!important}.pb-xl-5,.py-xl-5{padding-bottom:3rem!important}.pl-xl-5,.px-xl-5{padding-left:3rem!important}.m-xl-n1{margin:-.25rem!important}.mt-xl-n1,.my-xl-n1{margin-top:-.25rem!important}.mr-xl-n1,.mx-xl-n1{margin-right:-.25rem!important}.mb-xl-n1,.my-xl-n1{margin-bottom:-.25rem!important}.ml-xl-n1,.mx-xl-n1{margin-left:-.25rem!important}.m-xl-n2{margin:-.5rem!important}.mt-xl-n2,.my-xl-n2{margin-top:-.5rem!important}.mr-xl-n2,.mx-xl-n2{margin-right:-.5rem!important}.mb-xl-n2,.my-xl-n2{margin-bottom:-.5rem!important}.ml-xl-n2,.mx-xl-n2{margin-left:-.5rem!important}.m-xl-n3{margin:-1rem!important}.mt-xl-n3,.my-xl-n3{margin-top:-1rem!important}.mr-xl-n3,.mx-xl-n3{margin-right:-1rem!important}.mb-xl-n3,.my-xl-n3{margin-bottom:-1rem!important}.ml-xl-n3,.mx-xl-n3{margin-left:-1rem!important}.m-xl-n4{margin:-1.5rem!important}.mt-xl-n4,.my-xl-n4{margin-top:-1.5rem!important}.mr-xl-n4,.mx-xl-n4{margin-right:-1.5rem!important}.mb-xl-n4,.my-xl-n4{margin-bottom:-1.5rem!important}.ml-xl-n4,.mx-xl-n4{margin-left:-1.5rem!important}.m-xl-n5{margin:-3rem!important}.mt-xl-n5,.my-xl-n5{margin-top:-3rem!important}.mr-xl-n5,.mx-xl-n5{margin-right:-3rem!important}.mb-xl-n5,.my-xl-n5{margin-bottom:-3rem!important}.ml-xl-n5,.mx-xl-n5{margin-left:-3rem!important}.m-xl-auto{margin:auto!important}.mt-xl-auto,.my-xl-auto{margin-top:auto!important}.mr-xl-auto,.mx-xl-auto{margin-right:auto!important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto!important}.ml-xl-auto,.mx-xl-auto{margin-left:auto!important}}.text-monospace{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace!important}.text-justify{text-align:justify!important}.text-wrap{white-space:normal!important}.text-nowrap{white-space:nowrap!important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left!important}.text-right{text-align:right!important}.text-center{text-align:center!important}@media (min-width:576px){.text-sm-left{text-align:left!important}.text-sm-right{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.text-md-left{text-align:left!important}.text-md-right{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.text-lg-left{text-align:left!important}.text-lg-right{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.text-xl-left{text-align:left!important}.text-xl-right{text-align:right!important}.text-xl-center{text-align:center!important}}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.font-weight-light{font-weight:300!important}.font-weight-lighter{font-weight:lighter!important}.font-weight-normal{font-weight:400!important}.font-weight-bold{font-weight:700!important}.font-weight-bolder{font-weight:bolder!important}.font-italic{font-style:italic!important}.text-white{color:#fff!important}.text-primary{color:#ae9b70!important}a.text-primary:focus,a.text-primary:hover{color:#86744c!important}.text-secondary{color:#dbceb1!important}a.text-secondary:focus,a.text-secondary:hover{color:#c3ad7d!important}.text-success{color:#007100!important}a.text-success:focus,a.text-success:hover{color:#002500!important}.text-info{color:#005ba9!important}a.text-info:focus,a.text-info:hover{color:#00325d!important}.text-warning{color:#ff7c00!important}a.text-warning:focus,a.text-warning:hover{color:#b35700!important}.text-danger{color:#ae0000!important}a.text-danger:focus,a.text-danger:hover{color:#620000!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#cbd3da!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#121416!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.5)!important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.text-decoration-none{text-decoration:none!important}.text-break{word-break:break-word!important;overflow-wrap:break-word!important}.text-reset{color:inherit!important}.visible{visibility:visible!important}.invisible{visibility:hidden!important}@media print{*,::after,::before{text-shadow:none!important;box-shadow:none!important}a:not(.btn){text-decoration:underline}abbr[title]::after{content:" (" attr(title) ")"}pre{white-space:pre-wrap!important}blockquote,pre{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}@page{size:a3}body{min-width:992px!important}.container{min-width:992px!important}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}} \ No newline at end of file diff --git a/assets/images/favicon.png b/assets/images/favicon.png new file mode 100644 index 00000000..ad7ef8c7 Binary files /dev/null and b/assets/images/favicon.png differ diff --git a/assets/images/logo.png b/assets/images/logo.png new file mode 100644 index 00000000..28c52723 Binary files /dev/null and b/assets/images/logo.png differ diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..30630e22 --- /dev/null +++ b/composer.json @@ -0,0 +1,23 @@ +{ + "description": "The CodeIgniter framework", + "name": "codeigniter/framework", + "type": "project", + "homepage": "https://codeigniter.com", + "license": "MIT", + "support": { + "forum": "http://forum.codeigniter.com/", + "wiki": "https://github.com/bcit-ci/CodeIgniter/wiki", + "slack": "https://codeigniterchat.slack.com", + "source": "https://github.com/bcit-ci/CodeIgniter" + }, + "require": { + "php": ">=5.3.7" + }, + "suggest": { + "paragonie/random_compat": "Provides better randomness in PHP 5.x" + }, + "require-dev": { + "mikey179/vfsStream": "1.1.*", + "phpunit/phpunit": "4.* || 5.*" + } +} diff --git a/contributing.md b/contributing.md new file mode 100644 index 00000000..8edb510c --- /dev/null +++ b/contributing.md @@ -0,0 +1,95 @@ +# Contributing to CodeIgniter + + +CodeIgniter is a community driven project and accepts contributions of code and documentation from the community. These contributions are made in the form of Issues or [Pull Requests](http://help.github.com/send-pull-requests/) on the [CodeIgniter repository](https://github.com/bcit-ci/CodeIgniter) on GitHub. + +Issues are a quick way to point out a bug. If you find a bug or documentation error in CodeIgniter then please check a few things first: + +1. There is not already an open Issue +2. The issue has already been fixed (check the develop branch, or look for closed Issues) +3. Is it something really obvious that you can fix yourself? + +Reporting issues is helpful but an even better approach is to send a Pull Request, which is done by "Forking" the main repository and committing to your own copy. This will require you to use the version control system called Git. + +## Guidelines + +Before we look into how, here are the guidelines. If your Pull Requests fail +to pass these guidelines it will be declined and you will need to re-submit +when you’ve made the changes. This might sound a bit tough, but it is required +for us to maintain quality of the code-base. + +### PHP Style + +All code must meet the [Style Guide](https://codeigniter.com/user_guide/general/styleguide.html), which is +essentially the [Allman indent style](https://en.wikipedia.org/wiki/Indent_style#Allman_style), underscores and readable operators. This makes certain that all code is the same format as the existing code and means it will be as readable as possible. + +### Documentation + +If you change anything that requires a change to documentation then you will need to add it. New classes, methods, parameters, changing default values, etc are all things that will require a change to documentation. The change-log must also be updated for every change. Also PHPDoc blocks must be maintained. + +### Compatibility + +CodeIgniter recommends PHP 5.4 or newer to be used, but it should be +compatible with PHP 5.2.4 so all code supplied must stick to this +requirement. If PHP 5.3 (and above) functions or features are used then +there must be a fallback for PHP 5.2.4. + +### Branching + +CodeIgniter uses the [Git-Flow](http://nvie.com/posts/a-successful-git-branching-model/) branching model which requires all pull requests to be sent to the "develop" branch. This is +where the next planned version will be developed. The "master" branch will always contain the latest stable version and is kept clean so a "hotfix" (e.g: an emergency security patch) can be applied to master to create a new version, without worrying about other features holding it up. For this reason all commits need to be made to "develop" and any sent to "master" will be closed automatically. If you have multiple changes to submit, please place all changes into their own branch on your fork. + +One thing at a time: A pull request should only contain one change. That does not mean only one commit, but one change - however many commits it took. The reason for this is that if you change X and Y but send a pull request for both at the same time, we might really want X but disagree with Y, meaning we cannot merge the request. Using the Git-Flow branching model you can create new branches for both of these features and send two requests. + +### Signing + +You must sign your work, certifying that you either wrote the work or otherwise have the right to pass it on to an open source project. git makes this trivial as you merely have to use `--signoff` on your commits to your CodeIgniter fork. + +`git commit --signoff` + +or simply + +`git commit -s` + +This will sign your commits with the information setup in your git config, e.g. + +`Signed-off-by: John Q Public ` + +If you are using [Tower](http://www.git-tower.com/) there is a "Sign-Off" checkbox in the commit window. You could even alias git commit to use the `-s` flag so you don’t have to think about it. + +By signing your work in this manner, you certify to a "Developer's Certificate of Origin". The current version of this certificate is in the `DCO.txt` file in the root of this repository. + + +## How-to Guide + +There are two ways to make changes, the easy way and the hard way. Either way you will need to [create a GitHub account](https://github.com/signup/free). + +Easy way GitHub allows in-line editing of files for making simple typo changes and quick-fixes. This is not the best way as you are unable to test the code works. If you do this you could be introducing syntax errors, etc, but for a Git-phobic user this is good for a quick-fix. + +Hard way The best way to contribute is to "clone" your fork of CodeIgniter to your development area. That sounds like some jargon, but "forking" on GitHub means "making a copy of that repo to your account" and "cloning" means "copying that code to your environment so you can work on it". + +1. Set up Git (Windows, Mac & Linux) +2. Go to the CodeIgniter repo +3. Fork it +4. Clone your CodeIgniter repo: git@github.com:/CodeIgniter.git +5. Checkout the "develop" branch At this point you are ready to start making changes. +6. Fix existing bugs on the Issue tracker after taking a look to see nobody else is working on them. +7. Commit the files +8. Push your develop branch to your fork +9. Send a pull request [http://help.github.com/send-pull-requests/](http://help.github.com/send-pull-requests/) + +The Reactor Engineers will now be alerted about the change and at least one of the team will respond. If your change fails to meet the guidelines it will be bounced, or feedback will be provided to help you improve it. + +Once the Reactor Engineer handling your pull request is happy with it they will merge it into develop and your patch will be part of the next release. + +### Keeping your fork up-to-date + +Unlike systems like Subversion, Git can have multiple remotes. A remote is the name for a URL of a Git repository. By default your fork will have a remote named "origin" which points to your fork, but you can add another remote named "codeigniter" which points to `git://github.com/bcit-ci/CodeIgniter.git`. This is a read-only remote but you can pull from this develop branch to update your own. + +If you are using command-line you can do the following: + +1. `git remote add codeigniter git://github.com/bcit-ci/CodeIgniter.git` +2. `git pull codeigniter develop` +3. `git push origin develop` + +Now your fork is up to date. This should be done regularly, or before you send a pull request at least. diff --git a/conventions.md b/conventions.md new file mode 100644 index 00000000..108eb27d --- /dev/null +++ b/conventions.md @@ -0,0 +1,131 @@ +# Conventions in this project # + +In addition to [CodeIgniter's conventions](https://codeigniter.com/user_guide/general/styleguide.html), we use our own additional conventions. +Functions and classes should be documented with DocBlock. + +## Ignored CodeIgniter conventions ## + +There is no need to use `OR` instead of `||`. +Usage of `` is recommended, as CodeIgniter recommends at least 5.6, meaning it should work anyway. +The use of spaces instead of tabs for indentation is encouraged. You might see them mixed in some files. +There is no convention for end of lines. + +## HTML/PHP and CSS ## + +Element ids and classes are in kebab-case, as Bootstrap classes. + +## CSS ## + +Files are stored in */assets/css*. +Filenames start with *MY_* and end with *.css*. + +## Javascript ## + +Variables and functions are named in camelCase. +Variables should be declared using `let` or `const` instead of `var`. +Classes are named in PascalCase. +Files are stored in */assets/js*. +Filenames start with *MY_* and end with *.js*. +If a function is used only in one view, it can be added at the end of that view. + +## Images ## + +Images used in the application's template are stored in */assets/images*. +If the application lets the user upload his own pictures, these will be stored in a separate folder (for example "uploads" folder). + +## SQL and database ## + +SQL scripts should allways be present in root/database folder for application specific tables and in application/module/{module name}/database folder for module tables. +One script to generate a new empty database and upgrade scripts to update from a version to the next without affecting content datas. +Tables and attributes must be all lowercase and snake_case. +No prefix is used for tables names. +fk_ prefix is used for foreign keys. + +## PHP (in general) ## + +Variables are in camelCase. +Functions are in snake_case. +Classes are in Upper_snake_case. + +## CodeIgniter ## + +### Controllers ### + +Must extend MY_Controller. +Are stored in either */application/controllers* or */application/modules/{module name}/controllers*. +Names are in Upper_snake_case, and should only be a single word. +Read methods (e.g. a list) should start with `list_` for the list, or `detail_` for a specific item, both followed by the type in singular (e.g. `list_user`). +Create and update methods should start with `save_` for displaying the form and validating the input, both followed by the type in singular. +Delete methods should start with `delete_`, also followed by the type. +If there is only one type, simply use `list`, `detail`, `save`, and `delete`. +`index` should call the first list. +CI callbacks for form_validation must start with `cb_`. + +### Models ### + +Must extend MY_Model. +Names are in snake_case, and end with *_model*. +Custom create methods should start with `insert_`, read methods with `get_`, update methods with `update_`, and delete methods with `delete_`. +Other methods should start with a verb. + +### Views ### + +Names are in snake_case, must have the name of the method calling them with *.php* at the end (e.g. *list_user.php*). +Views should be placed in folders named after the calling controller. +Subfolders are allowed for further differenciation. +Whenever possible, use `` instead of ``. + +### Lang ### + +Use prefixes and suffixes accordingly. +If you need to use more than one, put the highest first. +Feel free to expand this list. + +#### Prefixes #### + +| Represents | Prefix | +| ------------- | --------- | +| Page title | title_ | +| Nav link | nav_ | +| Field label | field_ | +| Placeholder | phd_ | +| Button | btn_ | +| Message | msg_ | +| Error | err_ | + +#### Suffixes #### + +| Represents | Suffix | +| ------------- | --------- | +| Confirmation | _confirm | + +## User Interface ## + +All pages must be displayed alongside the views in the common module. +The order is *header.php*, *login_bar.php*, the view(s), *footer.php*. +It is done automatically by calling `MY_Controller::display_view`. + +### Lists ### + +Must be a table with the `table` class. +The table headers are in a thead. +The create button must be at the top left of the list. +The link for modifying an entry should be on the most descriptive part of it (e.g.: username for an user). +Deletes should be `a`s containing an x using the `close` class. + +### Forms ### + +Inputs use the `form-control` class. +Inputs should be in `div`s using the `form-group col` classes. +Additionally, the label must be right above the input. +Each `div` must be in another `div` using the `row` class. It may contain more than one input. +The cancel/save buttons should be at the bottom-right of the form. +If the form is big enough, they should also be at the top-right. + +### Buttons ### + +Cancel buttons use the `btn-default` class, confirm/create buttons use the `btn-primary`. +Hard delete buttons use the `btn-danger` class. +All buttons use the `btn` class. +Buttons do not use Bootstrap `col`s classes. +Cancel buttons must be the leftmost buttons. diff --git a/database/core.sql b/database/core.sql new file mode 100644 index 00000000..ed0fa279 --- /dev/null +++ b/database/core.sql @@ -0,0 +1,52 @@ +-- phpMyAdmin SQL Dump +-- version 4.9.0.1 +-- https://www.phpmyadmin.net/ +-- +-- Version du serveur : 10.4.6-MariaDB +-- Version de PHP : 7.3.9 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET AUTOCOMMIT = 0; +START TRANSACTION; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Base de données : `ci_packbase` +-- +CREATE DATABASE IF NOT EXISTS `ci_packbase_hmvc` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; +USE `ci_packbase_hmvc`; + +-- -------------------------------------------------------- + +-- +-- Structure de la table `ci_sessions` +-- + +CREATE TABLE `ci_sessions` ( + `id` varchar(128) NOT NULL, + `ip_address` varchar(45) NOT NULL, + `timestamp` int(10) UNSIGNED NOT NULL DEFAULT 0, + `data` blob NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- +-- Index pour les tables déchargées +-- + +-- +-- Index pour la table `ci_sessions` +-- +ALTER TABLE `ci_sessions` + ADD KEY `ci_sessions_timestamp` (`timestamp`); + +COMMIT; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/database/plafor_beginning_database.sql b/database/plafor_beginning_database.sql new file mode 100644 index 00000000..cfae3700 --- /dev/null +++ b/database/plafor_beginning_database.sql @@ -0,0 +1,133 @@ +-- phpMyAdmin SQL Dump +-- version 5.0.1 +-- https://www.phpmyadmin.net/ +-- +-- Hôte : 127.0.0.1 +-- Généré le : lun. 30 mars 2020 à 10:47 +-- Version du serveur : 10.4.11-MariaDB +-- Version de PHP : 7.4.3 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET AUTOCOMMIT = 0; +START TRANSACTION; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Base de données : `plafor` +-- + +-- -------------------------------------------------------- + +-- +-- Structure de la table `ci_sessions` +-- + +CREATE TABLE `ci_sessions` ( + `id` varchar(128) NOT NULL, + `ip_address` varchar(45) NOT NULL, + `timestamp` int(10) UNSIGNED NOT NULL DEFAULT 0, + `data` blob NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- -------------------------------------------------------- + +-- +-- Structure de la table `user` +-- + +CREATE TABLE `user` ( + `id` int(11) NOT NULL, + `fk_user_type` int(11) NOT NULL, + `username` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `archive` tinyint(4) NOT NULL DEFAULT 0, + `date_creation` timestamp NOT NULL DEFAULT current_timestamp() +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- +-- Déchargement des données de la table `user` +-- + +INSERT INTO `user` (`id`, `fk_user_type`, `username`, `password`, `archive`, `date_creation`) VALUES +(1, 1, 'admin', '$2y$12$vzMjlepZ8iODjC1Y1scl/OLkRuZe7za6Cx6srHr7iQ49z7e3BmtgG', 0, '2020-03-30 08:33:55'); + +-- -------------------------------------------------------- + +-- +-- Structure de la table `user_type` +-- + +CREATE TABLE `user_type` ( + `id` int(11) NOT NULL, + `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `access_level` int(11) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + +-- +-- Déchargement des données de la table `user_type` +-- + +INSERT INTO `user_type` (`id`, `name`, `access_level`) VALUES +(1, 'Administrateur', 4), +(2, 'Enregistré', 2), +(3, 'Invité', 1); + +-- +-- Index pour les tables déchargées +-- + +-- +-- Index pour la table `ci_sessions` +-- +ALTER TABLE `ci_sessions` + ADD KEY `ci_sessions_timestamp` (`timestamp`); + +-- +-- Index pour la table `user` +-- +ALTER TABLE `user` + ADD PRIMARY KEY (`id`), + ADD KEY `fk_user_user_type1_idx` (`fk_user_type`); + +-- +-- Index pour la table `user_type` +-- +ALTER TABLE `user_type` + ADD PRIMARY KEY (`id`); + +-- +-- AUTO_INCREMENT pour les tables déchargées +-- + +-- +-- AUTO_INCREMENT pour la table `user` +-- +ALTER TABLE `user` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; + +-- +-- AUTO_INCREMENT pour la table `user_type` +-- +ALTER TABLE `user_type` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; + +-- +-- Contraintes pour les tables déchargées +-- + +-- +-- Contraintes pour la table `user` +-- +ALTER TABLE `user` + ADD CONSTRAINT `fk_user_user_type1` FOREIGN KEY (`fk_user_type`) REFERENCES `user_type` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; +COMMIT; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/index.php b/index.php new file mode 100644 index 00000000..ca1304a8 --- /dev/null +++ b/index.php @@ -0,0 +1,315 @@ +=')) + { + error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); + } + else + { + error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE); + } + break; + + default: + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'The application environment is not set correctly.'; + exit(1); // EXIT_ERROR +} + +/* + *--------------------------------------------------------------- + * SYSTEM DIRECTORY NAME + *--------------------------------------------------------------- + * + * This variable must contain the name of your "system" directory. + * Set the path if it is not in the same directory as this file. + */ + $system_path = 'system'; + +/* + *--------------------------------------------------------------- + * APPLICATION DIRECTORY NAME + *--------------------------------------------------------------- + * + * If you want this front controller to use a different "application" + * directory than the default one you can set its name here. The directory + * can also be renamed or relocated anywhere on your server. If you do, + * use an absolute (full) server path. + * For more info please see the user guide: + * + * https://codeigniter.com/user_guide/general/managing_apps.html + * + * NO TRAILING SLASH! + */ + $application_folder = 'application'; + +/* + *--------------------------------------------------------------- + * VIEW DIRECTORY NAME + *--------------------------------------------------------------- + * + * If you want to move the view directory out of the application + * directory, set the path to it here. The directory can be renamed + * and relocated anywhere on your server. If blank, it will default + * to the standard location inside your application directory. + * If you do move this, use an absolute (full) server path. + * + * NO TRAILING SLASH! + */ + $view_folder = ''; + + +/* + * -------------------------------------------------------------------- + * DEFAULT CONTROLLER + * -------------------------------------------------------------------- + * + * Normally you will set your default controller in the routes.php file. + * You can, however, force a custom routing by hard-coding a + * specific controller class/function here. For most applications, you + * WILL NOT set your routing here, but it's an option for those + * special instances where you might want to override the standard + * routing in a specific front controller that shares a common CI installation. + * + * IMPORTANT: If you set the routing here, NO OTHER controller will be + * callable. In essence, this preference limits your application to ONE + * specific controller. Leave the function name blank if you need + * to call functions dynamically via the URI. + * + * Un-comment the $routing array below to use this feature + */ + // The directory name, relative to the "controllers" directory. Leave blank + // if your controller is not in a sub-directory within the "controllers" one + // $routing['directory'] = ''; + + // The controller class file name. Example: mycontroller + // $routing['controller'] = ''; + + // The controller function you wish to be called. + // $routing['function'] = ''; + + +/* + * ------------------------------------------------------------------- + * CUSTOM CONFIG VALUES + * ------------------------------------------------------------------- + * + * The $assign_to_config array below will be passed dynamically to the + * config class when initialized. This allows you to set custom config + * items or override any default config values found in the config.php file. + * This can be handy as it permits you to share one application between + * multiple front controller files, with each file containing different + * config values. + * + * Un-comment the $assign_to_config array below to use this feature + */ + // $assign_to_config['name_of_config_item'] = 'value of config item'; + + + +// -------------------------------------------------------------------- +// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE +// -------------------------------------------------------------------- + +/* + * --------------------------------------------------------------- + * Resolve the system path for increased reliability + * --------------------------------------------------------------- + */ + + // Set the current directory correctly for CLI requests + if (defined('STDIN')) + { + chdir(dirname(__FILE__)); + } + + if (($_temp = realpath($system_path)) !== FALSE) + { + $system_path = $_temp.DIRECTORY_SEPARATOR; + } + else + { + // Ensure there's a trailing slash + $system_path = strtr( + rtrim($system_path, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ).DIRECTORY_SEPARATOR; + } + + // Is the system path correct? + if ( ! is_dir($system_path)) + { + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME); + exit(3); // EXIT_CONFIG + } + +/* + * ------------------------------------------------------------------- + * Now that we know the path, set the main path constants + * ------------------------------------------------------------------- + */ + // The name of THIS file + define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); + + // Path to the system directory + define('BASEPATH', $system_path); + + // Path to the front controller (this file) directory + define('FCPATH', dirname(__FILE__).DIRECTORY_SEPARATOR); + + // Name of the "system" directory + define('SYSDIR', basename(BASEPATH)); + + // The path to the "application" directory + if (is_dir($application_folder)) + { + if (($_temp = realpath($application_folder)) !== FALSE) + { + $application_folder = $_temp; + } + else + { + $application_folder = strtr( + rtrim($application_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + } + elseif (is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR)) + { + $application_folder = BASEPATH.strtr( + trim($application_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + else + { + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; + exit(3); // EXIT_CONFIG + } + + define('APPPATH', $application_folder.DIRECTORY_SEPARATOR); + + // The path to the "views" directory + if ( ! isset($view_folder[0]) && is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR)) + { + $view_folder = APPPATH.'views'; + } + elseif (is_dir($view_folder)) + { + if (($_temp = realpath($view_folder)) !== FALSE) + { + $view_folder = $_temp; + } + else + { + $view_folder = strtr( + rtrim($view_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + } + elseif (is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR)) + { + $view_folder = APPPATH.strtr( + trim($view_folder, '/\\'), + '/\\', + DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR + ); + } + else + { + header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); + echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF; + exit(3); // EXIT_CONFIG + } + + define('VIEWPATH', $view_folder.DIRECTORY_SEPARATOR); + +/* + * -------------------------------------------------------------------- + * LOAD THE BOOTSTRAP FILE + * -------------------------------------------------------------------- + * + * And away we go... + */ +require_once BASEPATH.'core/CodeIgniter.php'; diff --git a/license.txt b/license.txt new file mode 100644 index 00000000..dcac5858 --- /dev/null +++ b/license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 - 2018, British Columbia Institute of Technology + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100644 index 00000000..32bc8286 --- /dev/null +++ b/readme.md @@ -0,0 +1,89 @@ +# Project Title + +One Paragraph of project description goes here + +## Getting Started + +These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system. + +### Prerequisites + +What things you need to install the software and how to install them + +``` +Give examples +``` + +### Installing + +A step by step series of examples that tell you how to get a development env running + +Say what the step will be + +``` +Give the example +``` + +And repeat + +``` +until finished +``` + +End with an example of getting some data out of the system or using it for a little demo + +## Running the tests + +Explain how to run the automated tests for this system + +### Break down into end to end tests + +Explain what these tests test and why + +``` +Give an example +``` + +### And coding style tests + +Explain what these tests test and why + +``` +Give an example +``` + +## Deployment + +Add additional notes about how to deploy this on a live system + +## Built With + +* [CodeIgniter](https://www.codeigniter.com/) - PHP framework +* [CodeIgniter modular extensions HMVC](https://github.com/OrifInformatique/HMVC) - HMVC for CodeIgniter +* [CodeIgniter base model](https://github.com/OrifInformatique/codeigniter-base-model) - Generic model +* [Bootstrap](https://getbootstrap.com/) - To simplify views design + +## Contributing + +Please read [CONTRIBUTING.md](https://gist.github.com/PurpleBooth/b24679402957c63ec426) for details on our code of conduct, and the process for submitting pull requests to us. + +## Versioning + +We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags). + +## Authors + +* **Orif, domaine informatique** - *Initiating and following the project* - [GitHub account](https://github.com/OrifInformatique) + +See also the list of [contributors](https://github.com/your/project/contributors) who participated in this project. + +## License + +This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details + +## Acknowledgments + +* Hat tip to anyone whose code was used +* Inspiration +* etc + diff --git a/system/.htaccess b/system/.htaccess new file mode 100644 index 00000000..97c65d2d --- /dev/null +++ b/system/.htaccess @@ -0,0 +1,6 @@ + + Require all denied + + + Deny from all + \ No newline at end of file diff --git a/system/core/Benchmark.php b/system/core/Benchmark.php new file mode 100644 index 00000000..014220a4 --- /dev/null +++ b/system/core/Benchmark.php @@ -0,0 +1,133 @@ +marker[$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}'; + } + +} diff --git a/system/core/CodeIgniter.php b/system/core/CodeIgniter.php new file mode 100644 index 00000000..8aecc0a2 --- /dev/null +++ b/system/core/CodeIgniter.php @@ -0,0 +1,559 @@ + '_ENV', 'G' => '_GET', 'P' => '_POST', 'C' => '_COOKIE', 'S' => '_SERVER') as $key => $superglobal) + { + if (strpos($_registered, $key) === FALSE) + { + continue; + } + + foreach (array_keys($$superglobal) as $var) + { + if (isset($GLOBALS[$var]) && ! in_array($var, $_protected, TRUE)) + { + $GLOBALS[$var] = NULL; + } + } + } + } +} + + +/* + * ------------------------------------------------------ + * Define a custom error handler so we can log PHP errors + * ------------------------------------------------------ + */ + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); + +/* + * ------------------------------------------------------ + * Set the subclass_prefix + * ------------------------------------------------------ + * + * Normally the "subclass_prefix" is set in the config file. + * The subclass prefix allows CI to know if a core class is + * being extended via a library in the local application + * "libraries" folder. Since CI allows config items to be + * overridden via data set in the main index.php file, + * before proceeding we need to know if a subclass_prefix + * override exists. If so, we will set this value now, + * before any classes are loaded + * Note: Since the config file data is cached it doesn't + * hurt to load it here. + */ + if ( ! empty($assign_to_config['subclass_prefix'])) + { + get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); + } + +/* + * ------------------------------------------------------ + * Should we use a Composer autoloader? + * ------------------------------------------------------ + */ + if ($composer_autoload = config_item('composer_autoload')) + { + if ($composer_autoload === TRUE) + { + file_exists(APPPATH.'vendor/autoload.php') + ? require_once(APPPATH.'vendor/autoload.php') + : log_message('error', '$config[\'composer_autoload\'] is set to TRUE but '.APPPATH.'vendor/autoload.php was not found.'); + } + elseif (file_exists($composer_autoload)) + { + require_once($composer_autoload); + } + else + { + log_message('error', 'Could not find the specified $config[\'composer_autoload\'] path: '.$composer_autoload); + } + } + +/* + * ------------------------------------------------------ + * Start the timer... tick tock tick tock... + * ------------------------------------------------------ + */ + $BM =& load_class('Benchmark', 'core'); + $BM->mark('total_execution_time_start'); + $BM->mark('loading_time:_base_classes_start'); + +/* + * ------------------------------------------------------ + * Instantiate the hooks class + * ------------------------------------------------------ + */ + $EXT =& load_class('Hooks', 'core'); + +/* + * ------------------------------------------------------ + * Is there a "pre_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_system'); + +/* + * ------------------------------------------------------ + * Instantiate the config class + * ------------------------------------------------------ + * + * Note: It is important that Config is loaded first as + * most other classes depend on it either directly or by + * depending on another class that uses it. + * + */ + $CFG =& load_class('Config', 'core'); + + // Do we have any manually set config items in the index.php file? + if (isset($assign_to_config) && is_array($assign_to_config)) + { + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } + } + +/* + * ------------------------------------------------------ + * Important charset-related stuff + * ------------------------------------------------------ + * + * Configure mbstring and/or iconv if they are enabled + * and set MB_ENABLED and ICONV_ENABLED constants, so + * that we don't repeatedly do extension_loaded() or + * function_exists() calls. + * + * Note: UTF-8 class depends on this. It used to be done + * in it's constructor, but it's _not_ class-specific. + * + */ + $charset = strtoupper(config_item('charset')); + ini_set('default_charset', $charset); + + if (extension_loaded('mbstring')) + { + define('MB_ENABLED', TRUE); + // mbstring.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('mbstring.internal_encoding', $charset); + // This is required for mb_convert_encoding() to strip invalid characters. + // That's utilized by CI_Utf8, but it's also done for consistency with iconv. + mb_substitute_character('none'); + } + else + { + define('MB_ENABLED', FALSE); + } + + // There's an ICONV_IMPL constant, but the PHP manual says that using + // iconv's predefined constants is "strongly discouraged". + if (extension_loaded('iconv')) + { + define('ICONV_ENABLED', TRUE); + // iconv.internal_encoding is deprecated starting with PHP 5.6 + // and it's usage triggers E_DEPRECATED messages. + @ini_set('iconv.internal_encoding', $charset); + } + else + { + define('ICONV_ENABLED', FALSE); + } + + if (is_php('5.6')) + { + ini_set('php.internal_encoding', $charset); + } + +/* + * ------------------------------------------------------ + * Load compatibility features + * ------------------------------------------------------ + */ + + require_once(BASEPATH.'core/compat/mbstring.php'); + require_once(BASEPATH.'core/compat/hash.php'); + require_once(BASEPATH.'core/compat/password.php'); + require_once(BASEPATH.'core/compat/standard.php'); + +/* + * ------------------------------------------------------ + * Instantiate the UTF-8 class + * ------------------------------------------------------ + */ + $UNI =& load_class('Utf8', 'core'); + +/* + * ------------------------------------------------------ + * Instantiate the URI class + * ------------------------------------------------------ + */ + $URI =& load_class('URI', 'core'); + +/* + * ------------------------------------------------------ + * Instantiate the routing class and set the routing + * ------------------------------------------------------ + */ + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); + +/* + * ------------------------------------------------------ + * Instantiate the output class + * ------------------------------------------------------ + */ + $OUT =& load_class('Output', 'core'); + +/* + * ------------------------------------------------------ + * Is there a valid cache file? If so, we're done... + * ------------------------------------------------------ + */ + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) + { + exit; + } + +/* + * ----------------------------------------------------- + * Load the security class for xss and csrf support + * ----------------------------------------------------- + */ + $SEC =& load_class('Security', 'core'); + +/* + * ------------------------------------------------------ + * Load the Input class and sanitize globals + * ------------------------------------------------------ + */ + $IN =& load_class('Input', 'core'); + +/* + * ------------------------------------------------------ + * Load the Language class + * ------------------------------------------------------ + */ + $LANG =& load_class('Lang', 'core'); + +/* + * ------------------------------------------------------ + * Load the app controller and local controller + * ------------------------------------------------------ + * + */ + // Load the base controller class + require_once BASEPATH.'core/Controller.php'; + + /** + * Reference to the CI_Controller method. + * + * Returns current CI instance object + * + * @return CI_Controller + */ + function &get_instance() + { + return CI_Controller::get_instance(); + } + + if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) + { + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + } + + // Set a mark point for benchmarking + $BM->mark('loading_time:_base_classes_end'); + +/* + * ------------------------------------------------------ + * Sanity checks + * ------------------------------------------------------ + * + * The Router class has already validated the request, + * leaving us with 3 options here: + * + * 1) an empty class name, if we reached the default + * controller, but it didn't exist; + * 2) a query string which doesn't go through a + * file_exists() check + * 3) a regular request for a non-existing page + * + * We handle all of these as a 404 error. + * + * Furthermore, none of the methods in the app controller + * or the loader class can be called via the URI, nor can + * controller methods that begin with an underscore. + */ + + $e404 = FALSE; + $class = ucfirst($RTR->class); + $method = $RTR->method; + + if (empty($class) OR ! file_exists(APPPATH.'controllers/'.$RTR->directory.$class.'.php')) + { + $e404 = TRUE; + } + else + { + require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); + + if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)) + { + $e404 = TRUE; + } + elseif (method_exists($class, '_remap')) + { + $params = array($method, array_slice($URI->rsegments, 2)); + $method = '_remap'; + } + elseif ( ! method_exists($class, $method)) + { + $e404 = TRUE; + } + /** + * DO NOT CHANGE THIS, NOTHING ELSE WORKS! + * + * - method_exists() returns true for non-public methods, which passes the previous elseif + * - is_callable() returns false for PHP 4-style constructors, even if there's a __construct() + * - method_exists($class, '__construct') won't work because CI_Controller::__construct() is inherited + * - People will only complain if this doesn't work, even though it is documented that it shouldn't. + * + * ReflectionMethod::isConstructor() is the ONLY reliable check, + * knowing which method will be executed as a constructor. + */ + elseif ( ! is_callable(array($class, $method))) + { + $reflection = new ReflectionMethod($class, $method); + if ( ! $reflection->isPublic() OR $reflection->isConstructor()) + { + $e404 = TRUE; + } + } + } + + if ($e404) + { + if ( ! empty($RTR->routes['404_override'])) + { + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) + { + $error_method = 'index'; + } + + $error_class = ucfirst($error_class); + + if ( ! class_exists($error_class, FALSE)) + { + if (file_exists(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$RTR->directory.$error_class.'.php'); + $e404 = ! class_exists($error_class, FALSE); + } + // Were we in a directory? If so, check for a global override + elseif ( ! empty($RTR->directory) && file_exists(APPPATH.'controllers/'.$error_class.'.php')) + { + require_once(APPPATH.'controllers/'.$error_class.'.php'); + if (($e404 = ! class_exists($error_class, FALSE)) === FALSE) + { + $RTR->directory = ''; + } + } + } + else + { + $e404 = FALSE; + } + } + + // Did we reset the $e404 flag? If so, set the rsegments, starting from index 1 + if ( ! $e404) + { + $class = $error_class; + $method = $error_method; + + $URI->rsegments = array( + 1 => $class, + 2 => $method + ); + } + else + { + show_404($RTR->directory.$class.'/'.$method); + } + } + + if ($method !== '_remap') + { + $params = array_slice($URI->rsegments, 2); + } + +/* + * ------------------------------------------------------ + * Is there a "pre_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('pre_controller'); + +/* + * ------------------------------------------------------ + * Instantiate the requested controller + * ------------------------------------------------------ + */ + // Mark a start point so we can benchmark the controller + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_start'); + + $CI = new $class(); + +/* + * ------------------------------------------------------ + * Is there a "post_controller_constructor" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller_constructor'); + +/* + * ------------------------------------------------------ + * Call the requested method + * ------------------------------------------------------ + */ + call_user_func_array(array(&$CI, $method), $params); + + // Mark a benchmark end point + $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); + +/* + * ------------------------------------------------------ + * Is there a "post_controller" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_controller'); + +/* + * ------------------------------------------------------ + * Send the final rendered output to the browser + * ------------------------------------------------------ + */ + if ($EXT->call_hook('display_override') === FALSE) + { + $OUT->_display(); + } + +/* + * ------------------------------------------------------ + * Is there a "post_system" hook? + * ------------------------------------------------------ + */ + $EXT->call_hook('post_system'); diff --git a/system/core/Common.php b/system/core/Common.php new file mode 100644 index 00000000..624b5a9f --- /dev/null +++ b/system/core/Common.php @@ -0,0 +1,849 @@ +='); + } + + 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'), 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) + { + $atts = NULL; + + if (empty($attributes)) + { + return $atts; + } + + if (is_string($attributes)) + { + return ' '.$attributes; + } + + $attributes = (array) $attributes; + + 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; + } +} diff --git a/system/core/Config.php b/system/core/Config.php new file mode 100644 index 00000000..fc6c30f8 --- /dev/null +++ b/system/core/Config.php @@ -0,0 +1,379 @@ +config =& get_config(); + + // Set the base_url automatically if none was provided + if (empty($this->config['base_url'])) + { + if (isset($_SERVER['SERVER_ADDR'])) + { + if (strpos($_SERVER['SERVER_ADDR'], ':') !== FALSE) + { + $server_addr = '['.$_SERVER['SERVER_ADDR'].']'; + } + else + { + $server_addr = $_SERVER['SERVER_ADDR']; + } + + $base_url = (is_https() ? 'https' : 'http').'://'.$server_addr + .substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME']))); + } + else + { + $base_url = 'http://localhost/'; + } + + $this->set_item('base_url', $base_url); + } + + log_message('info', 'Config Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Load Config File + * + * @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 load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) + { + $file = ($file === '') ? 'config' : str_replace('.php', '', $file); + $loaded = FALSE; + + foreach ($this->_config_paths as $path) + { + foreach (array($file, ENVIRONMENT.DIRECTORY_SEPARATOR.$file) as $location) + { + $file_path = $path.'config/'.$location.'.php'; + if (in_array($file_path, $this->is_loaded, TRUE)) + { + return TRUE; + } + + if ( ! file_exists($file_path)) + { + continue; + } + + include($file_path); + + if ( ! isset($config) OR ! is_array($config)) + { + if ($fail_gracefully === TRUE) + { + return FALSE; + } + + show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); + } + + if ($use_sections === TRUE) + { + $this->config[$file] = isset($this->config[$file]) + ? array_merge($this->config[$file], $config) + : $config; + } + else + { + $this->config = array_merge($this->config, $config); + } + + $this->is_loaded[] = $file_path; + $config = NULL; + $loaded = TRUE; + log_message('debug', 'Config file loaded: '.$file_path); + } + } + + if ($loaded === TRUE) + { + return TRUE; + } + elseif ($fail_gracefully === TRUE) + { + return FALSE; + } + + show_error('The configuration file '.$file.'.php does not exist.'); + } + + // -------------------------------------------------------------------- + + /** + * Fetch a config file item + * + * @param string $item Config item name + * @param string $index Index name + * @return string|null The configuration item or NULL if the item doesn't exist + */ + public function item($item, $index = '') + { + if ($index == '') + { + return isset($this->config[$item]) ? $this->config[$item] : NULL; + } + + return isset($this->config[$index], $this->config[$index][$item]) ? $this->config[$index][$item] : NULL; + } + + // -------------------------------------------------------------------- + + /** + * Fetch a config file item with slash appended (if not empty) + * + * @param string $item Config item name + * @return string|null The configuration item or NULL if the item doesn't exist + */ + public function slash_item($item) + { + if ( ! isset($this->config[$item])) + { + return NULL; + } + elseif (trim($this->config[$item]) === '') + { + return ''; + } + + return rtrim($this->config[$item], '/').'/'; + } + + // -------------------------------------------------------------------- + + /** + * Site URL + * + * Returns base_url . index_page [. uri_string] + * + * @uses CI_Config::_uri_string() + * + * @param string|string[] $uri URI string or an array of segments + * @param string $protocol + * @return string + */ + public function site_url($uri = '', $protocol = NULL) + { + $base_url = $this->slash_item('base_url'); + + if (isset($protocol)) + { + // For protocol-relative links + if ($protocol === '') + { + $base_url = substr($base_url, strpos($base_url, '//')); + } + else + { + $base_url = $protocol.substr($base_url, strpos($base_url, '://')); + } + } + + if (empty($uri)) + { + return $base_url.$this->item('index_page'); + } + + $uri = $this->_uri_string($uri); + + if ($this->item('enable_query_strings') === FALSE) + { + $suffix = isset($this->config['url_suffix']) ? $this->config['url_suffix'] : ''; + + if ($suffix !== '') + { + if (($offset = strpos($uri, '?')) !== FALSE) + { + $uri = substr($uri, 0, $offset).$suffix.substr($uri, $offset); + } + else + { + $uri .= $suffix; + } + } + + return $base_url.$this->slash_item('index_page').$uri; + } + elseif (strpos($uri, '?') === FALSE) + { + $uri = '?'.$uri; + } + + return $base_url.$this->item('index_page').$uri; + } + + // ------------------------------------------------------------- + + /** + * Base URL + * + * Returns base_url [. uri_string] + * + * @uses CI_Config::_uri_string() + * + * @param string|string[] $uri URI string or an array of segments + * @param string $protocol + * @return string + */ + public function base_url($uri = '', $protocol = NULL) + { + $base_url = $this->slash_item('base_url'); + + if (isset($protocol)) + { + // For protocol-relative links + if ($protocol === '') + { + $base_url = substr($base_url, strpos($base_url, '//')); + } + else + { + $base_url = $protocol.substr($base_url, strpos($base_url, '://')); + } + } + + return $base_url.$this->_uri_string($uri); + } + + // ------------------------------------------------------------- + + /** + * Build URI string + * + * @used-by CI_Config::site_url() + * @used-by CI_Config::base_url() + * + * @param string|string[] $uri URI string or an array of segments + * @return string + */ + protected function _uri_string($uri) + { + if ($this->item('enable_query_strings') === FALSE) + { + is_array($uri) && $uri = implode('/', $uri); + return ltrim($uri, '/'); + } + elseif (is_array($uri)) + { + return http_build_query($uri); + } + + return $uri; + } + + // -------------------------------------------------------------------- + + /** + * System URL + * + * @deprecated 3.0.0 Encourages insecure practices + * @return string + */ + public function system_url() + { + $x = explode('/', preg_replace('|/*(.+?)/*$|', '\\1', BASEPATH)); + return $this->slash_item('base_url').end($x).'/'; + } + + // -------------------------------------------------------------------- + + /** + * Set a config file item + * + * @param string $item Config item key + * @param string $value Config item value + * @return void + */ + public function set_item($item, $value) + { + $this->config[$item] = $value; + } + +} diff --git a/system/core/Controller.php b/system/core/Controller.php new file mode 100644 index 00000000..e25b8472 --- /dev/null +++ b/system/core/Controller.php @@ -0,0 +1,103 @@ + $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; + } + +} diff --git a/system/core/Exceptions.php b/system/core/Exceptions.php new file mode 100644 index 00000000..90ff1abf --- /dev/null +++ b/system/core/Exceptions.php @@ -0,0 +1,274 @@ + '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; + } + +} diff --git a/system/core/Hooks.php b/system/core/Hooks.php new file mode 100644 index 00000000..6236dd49 --- /dev/null +++ b/system/core/Hooks.php @@ -0,0 +1,266 @@ +item('enable_hooks') === FALSE) + { + return; + } + + // Grab the "hooks" definition file. + if (file_exists(APPPATH.'config/hooks.php')) + { + include(APPPATH.'config/hooks.php'); + } + + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/hooks.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php'); + } + + // If there are no hooks, we're done. + if ( ! isset($hook) OR ! is_array($hook)) + { + return; + } + + $this->hooks =& $hook; + $this->enabled = TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Call Hook + * + * Calls a particular hook. Called by CodeIgniter.php. + * + * @uses CI_Hooks::_run_hook() + * + * @param string $which Hook name + * @return bool TRUE on success or FALSE on failure + */ + public function call_hook($which = '') + { + if ( ! $this->enabled OR ! isset($this->hooks[$which])) + { + return FALSE; + } + + if (is_array($this->hooks[$which]) && ! isset($this->hooks[$which]['function'])) + { + foreach ($this->hooks[$which] as $val) + { + $this->_run_hook($val); + } + } + else + { + $this->_run_hook($this->hooks[$which]); + } + + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Run Hook + * + * Runs a particular hook + * + * @param array $data Hook details + * @return bool TRUE on success or FALSE on failure + */ + protected function _run_hook($data) + { + // Closures/lambda functions and array($object, 'method') callables + if (is_callable($data)) + { + is_array($data) + ? $data[0]->{$data[1]}() + : $data(); + + return TRUE; + } + elseif ( ! is_array($data)) + { + return FALSE; + } + + // ----------------------------------- + // Safety - Prevents run-away loops + // ----------------------------------- + + // If the script being called happens to have the same + // hook call within it a loop can happen + if ($this->_in_progress === TRUE) + { + return; + } + + // ----------------------------------- + // Set file path + // ----------------------------------- + + if ( ! isset($data['filepath'], $data['filename'])) + { + return FALSE; + } + + $filepath = APPPATH.$data['filepath'].'/'.$data['filename']; + + if ( ! file_exists($filepath)) + { + return FALSE; + } + + // Determine and class and/or function names + $class = empty($data['class']) ? FALSE : $data['class']; + $function = empty($data['function']) ? FALSE : $data['function']; + $params = isset($data['params']) ? $data['params'] : ''; + + if (empty($function)) + { + return FALSE; + } + + // Set the _in_progress flag + $this->_in_progress = TRUE; + + // Call the requested class and/or function + if ($class !== FALSE) + { + // The object is stored? + if (isset($this->_objects[$class])) + { + if (method_exists($this->_objects[$class], $function)) + { + $this->_objects[$class]->$function($params); + } + else + { + return $this->_in_progress = FALSE; + } + } + else + { + class_exists($class, FALSE) OR require_once($filepath); + + if ( ! class_exists($class, FALSE) OR ! method_exists($class, $function)) + { + return $this->_in_progress = FALSE; + } + + // Store the object and execute the method + $this->_objects[$class] = new $class(); + $this->_objects[$class]->$function($params); + } + } + else + { + function_exists($function) OR require_once($filepath); + + if ( ! function_exists($function)) + { + return $this->_in_progress = FALSE; + } + + $function($params); + } + + $this->_in_progress = FALSE; + return TRUE; + } + +} diff --git a/system/core/Input.php b/system/core/Input.php new file mode 100644 index 00000000..30b31d0d --- /dev/null +++ b/system/core/Input.php @@ -0,0 +1,895 @@ +_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) + * @return void + */ + public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = 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') 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; + } + + setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); + } + + // -------------------------------------------------------------------- + + /** + * 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 = NULL; + 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; + } + } + +} diff --git a/system/core/Lang.php b/system/core/Lang.php new file mode 100644 index 00000000..2c8654dc --- /dev/null +++ b/system/core/Lang.php @@ -0,0 +1,203 @@ +load($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; + } + +} diff --git a/system/core/Loader.php b/system/core/Loader.php new file mode 100644 index 00000000..14888e49 --- /dev/null +++ b/system/core/Loader.php @@ -0,0 +1,1415 @@ + 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; + } +} diff --git a/system/core/Log.php b/system/core/Log.php new file mode 100644 index 00000000..f37726e0 --- /dev/null +++ b/system/core/Log.php @@ -0,0 +1,296 @@ + 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 = (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); + } +} diff --git a/system/core/Model.php b/system/core/Model.php new file mode 100644 index 00000000..0aadbcdc --- /dev/null +++ b/system/core/Model.php @@ -0,0 +1,76 @@ +$key; + } + +} diff --git a/system/core/Output.php b/system/core/Output.php new file mode 100644 index 00000000..64e7ee1f --- /dev/null +++ b/system/core/Output.php @@ -0,0 +1,842 @@ +_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 = (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) + { + // Combine headers already sent with our batched headers + $headers = array_merge( + // We only need [x][0] from our multi-dimensional array + array_map('array_shift', $this->headers), + 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); + } +} diff --git a/system/core/Router.php b/system/core/Router.php new file mode 100644 index 00000000..90b69d07 --- /dev/null +++ b/system/core/Router.php @@ -0,0 +1,515 @@ +config =& load_class('Config', 'core'); + $this->uri =& load_class('URI', 'core'); + + $this->enable_query_strings = ( ! is_cli() && $this->config->item('enable_query_strings') === TRUE); + + // If a directory override is configured, it has to be set before any dynamic routing logic + is_array($routing) && isset($routing['directory']) && $this->set_directory($routing['directory']); + $this->_set_routing(); + + // Set any routing overrides that may exist in the main index file + if (is_array($routing)) + { + empty($routing['controller']) OR $this->set_class($routing['controller']); + empty($routing['function']) OR $this->set_method($routing['function']); + } + + log_message('info', 'Router Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Set route mapping + * + * Determines what should be served based on the URI request, + * as well as any "routes" that have been set in the routing config file. + * + * @return void + */ + protected function _set_routing() + { + // Load the routes.php file. It would be great if we could + // skip this for enable_query_strings = TRUE, but then + // default_controller would be empty ... + if (file_exists(APPPATH.'config/routes.php')) + { + include(APPPATH.'config/routes.php'); + } + + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); + } + + // Validate & get reserved routes + if (isset($route) && is_array($route)) + { + isset($route['default_controller']) && $this->default_controller = $route['default_controller']; + isset($route['translate_uri_dashes']) && $this->translate_uri_dashes = $route['translate_uri_dashes']; + unset($route['default_controller'], $route['translate_uri_dashes']); + $this->routes = $route; + } + + // Are query strings enabled in the config file? Normally CI doesn't utilize query strings + // since URI segments are more search-engine friendly, but they can optionally be used. + // If this feature is enabled, we will gather the directory/class/method a little differently + if ($this->enable_query_strings) + { + // If the directory is set at this time, it means an override exists, so skip the checks + if ( ! isset($this->directory)) + { + $_d = $this->config->item('directory_trigger'); + $_d = isset($_GET[$_d]) ? trim($_GET[$_d], " \t\n\r\0\x0B/") : ''; + + if ($_d !== '') + { + $this->uri->filter_uri($_d); + $this->set_directory($_d); + } + } + + $_c = trim($this->config->item('controller_trigger')); + if ( ! empty($_GET[$_c])) + { + $this->uri->filter_uri($_GET[$_c]); + $this->set_class($_GET[$_c]); + + $_f = trim($this->config->item('function_trigger')); + if ( ! empty($_GET[$_f])) + { + $this->uri->filter_uri($_GET[$_f]); + $this->set_method($_GET[$_f]); + } + + $this->uri->rsegments = array( + 1 => $this->class, + 2 => $this->method + ); + } + else + { + $this->_set_default_controller(); + } + + // Routing rules don't apply to query strings and we don't need to detect + // directories, so we're done here + return; + } + + // Is there anything to parse? + if ($this->uri->uri_string !== '') + { + $this->_parse_routes(); + } + else + { + $this->_set_default_controller(); + } + } + + // -------------------------------------------------------------------- + + /** + * Set request route + * + * Takes an array of URI segments as input and sets the class/method + * to be called. + * + * @used-by CI_Router::_parse_routes() + * @param array $segments URI segments + * @return void + */ + protected function _set_request($segments = array()) + { + $segments = $this->_validate_request($segments); + // If we don't have any segments left - try the default controller; + // WARNING: Directories get shifted out of the segments array! + if (empty($segments)) + { + $this->_set_default_controller(); + return; + } + + if ($this->translate_uri_dashes === TRUE) + { + $segments[0] = str_replace('-', '_', $segments[0]); + if (isset($segments[1])) + { + $segments[1] = str_replace('-', '_', $segments[1]); + } + } + + $this->set_class($segments[0]); + if (isset($segments[1])) + { + $this->set_method($segments[1]); + } + else + { + $segments[1] = 'index'; + } + + array_unshift($segments, NULL); + unset($segments[0]); + $this->uri->rsegments = $segments; + } + + // -------------------------------------------------------------------- + + /** + * Set default controller + * + * @return void + */ + protected function _set_default_controller() + { + if (empty($this->default_controller)) + { + show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.'); + } + + // Is the method being specified? + if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2) + { + $method = 'index'; + } + + if ( ! file_exists(APPPATH.'controllers/'.$this->directory.ucfirst($class).'.php')) + { + // This will trigger 404 later + return; + } + + $this->set_class($class); + $this->set_method($method); + + // Assign routed segments, index starting from 1 + $this->uri->rsegments = array( + 1 => $class, + 2 => $method + ); + + log_message('debug', 'No URI present. Default controller set.'); + } + + // -------------------------------------------------------------------- + + /** + * Validate request + * + * Attempts validate the URI request and determine the controller path. + * + * @used-by CI_Router::_set_request() + * @param array $segments URI segments + * @return mixed URI segments + */ + protected function _validate_request($segments) + { + $c = count($segments); + $directory_override = isset($this->directory); + + // Loop through our segments and return as soon as a controller + // is found or when such a directory doesn't exist + while ($c-- > 0) + { + $test = $this->directory + .ucfirst($this->translate_uri_dashes === TRUE ? str_replace('-', '_', $segments[0]) : $segments[0]); + + if ( ! file_exists(APPPATH.'controllers/'.$test.'.php') + && $directory_override === FALSE + && is_dir(APPPATH.'controllers/'.$this->directory.$segments[0]) + ) + { + $this->set_directory(array_shift($segments), TRUE); + continue; + } + + return $segments; + } + + // This means that all segments were actually directories + return $segments; + } + + // -------------------------------------------------------------------- + + /** + * Parse Routes + * + * Matches any routes that may exist in the config/routes.php file + * against the URI to determine if the class/method need to be remapped. + * + * @return void + */ + protected function _parse_routes() + { + // Turn the segment array into a URI string + $uri = implode('/', $this->uri->segments); + + // Get HTTP verb + $http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli'; + + // Loop through the route array looking for wildcards + foreach ($this->routes as $key => $val) + { + // Check if route format is using HTTP verbs + if (is_array($val)) + { + $val = array_change_key_case($val, CASE_LOWER); + if (isset($val[$http_verb])) + { + $val = $val[$http_verb]; + } + else + { + continue; + } + } + + // Convert wildcards to RegEx + $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key); + + // Does the RegEx match? + if (preg_match('#^'.$key.'$#', $uri, $matches)) + { + // Are we using callbacks to process back-references? + if ( ! is_string($val) && is_callable($val)) + { + // Remove the original string from the matches array. + array_shift($matches); + + // Execute the callback using the values in matches as its parameters. + $val = call_user_func_array($val, $matches); + } + // Are we using the default routing method for back-references? + elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE) + { + $val = preg_replace('#^'.$key.'$#', $val, $uri); + } + + $this->_set_request(explode('/', $val)); + return; + } + } + + // If we got this far it means we didn't encounter a + // matching route so we'll set the site default route + $this->_set_request(array_values($this->uri->segments)); + } + + // -------------------------------------------------------------------- + + /** + * Set class name + * + * @param string $class Class name + * @return void + */ + public function set_class($class) + { + $this->class = str_replace(array('/', '.'), '', $class); + } + + // -------------------------------------------------------------------- + + /** + * Fetch the current class + * + * @deprecated 3.0.0 Read the 'class' property instead + * @return string + */ + public function fetch_class() + { + return $this->class; + } + + // -------------------------------------------------------------------- + + /** + * Set method name + * + * @param string $method Method name + * @return void + */ + public function set_method($method) + { + $this->method = $method; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the current method + * + * @deprecated 3.0.0 Read the 'method' property instead + * @return string + */ + public function fetch_method() + { + return $this->method; + } + + // -------------------------------------------------------------------- + + /** + * Set directory name + * + * @param string $dir Directory name + * @param bool $append Whether we're appending rather than setting the full value + * @return void + */ + public function set_directory($dir, $append = FALSE) + { + if ($append !== TRUE OR empty($this->directory)) + { + $this->directory = str_replace('.', '', trim($dir, '/')).'/'; + } + else + { + $this->directory .= str_replace('.', '', trim($dir, '/')).'/'; + } + } + + // -------------------------------------------------------------------- + + /** + * Fetch directory + * + * Feches the sub-directory (if any) that contains the requested + * controller class. + * + * @deprecated 3.0.0 Read the 'directory' property instead + * @return string + */ + public function fetch_directory() + { + return $this->directory; + } + +} diff --git a/system/core/Security.php b/system/core/Security.php new file mode 100644 index 00000000..6a81faff --- /dev/null +++ b/system/core/Security.php @@ -0,0 +1,1091 @@ +', '<', '>', + "'", '"', '&', '$', '#', + '{', '}', '[', ']', '=', + ';', '?', '%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(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; + } + + setcookie( + $this->_csrf_cookie_name, + $this->_csrf_hash, + $expire, + config_item('cookie_path'), + config_item('cookie_domain'), + $secure_cookie, + config_item('cookie_httponly') + ); + 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; + } + +} diff --git a/system/core/URI.php b/system/core/URI.php new file mode 100644 index 00000000..a8b98ae9 --- /dev/null +++ b/system/core/URI.php @@ -0,0 +1,643 @@ +config =& 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); + } + +} diff --git a/system/core/Utf8.php b/system/core/Utf8.php new file mode 100644 index 00000000..9ee63e92 --- /dev/null +++ b/system/core/Utf8.php @@ -0,0 +1,164 @@ +is_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); + } + +} diff --git a/system/core/compat/hash.php b/system/core/compat/hash.php new file mode 100644 index 00000000..8f5510c3 --- /dev/null +++ b/system/core/compat/hash.php @@ -0,0 +1,254 @@ + 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); + } +} diff --git a/system/core/compat/index.html b/system/core/compat/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/core/compat/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/core/compat/mbstring.php b/system/core/compat/mbstring.php new file mode 100644 index 00000000..552e7271 --- /dev/null +++ b/system/core/compat/mbstring.php @@ -0,0 +1,149 @@ + 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); + } +} diff --git a/system/core/compat/standard.php b/system/core/compat/standard.php new file mode 100644 index 00000000..2c528fd7 --- /dev/null +++ b/system/core/compat/standard.php @@ -0,0 +1,182 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/DB.php b/system/database/DB.php new file mode 100644 index 00000000..02e0e1d3 --- /dev/null +++ b/system/database/DB.php @@ -0,0 +1,218 @@ +load->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; +} diff --git a/system/database/DB_cache.php b/system/database/DB_cache.php new file mode 100644 index 00000000..afcfc4cf --- /dev/null +++ b/system/database/DB_cache.php @@ -0,0 +1,221 @@ +CI 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); + } + +} diff --git a/system/database/DB_driver.php b/system/database/DB_driver.php new file mode 100644 index 00000000..5ae0442a --- /dev/null +++ b/system/database/DB_driver.php @@ -0,0 +1,1985 @@ + $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; + } + + // -------------------------------------------------------------------- + + /** + * 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+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() + { + } + +} diff --git a/system/database/DB_forge.php b/system/database/DB_forge.php new file mode 100644 index 00000000..85b58fde --- /dev/null +++ b/system/database/DB_forge.php @@ -0,0 +1,1033 @@ +db =& $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(); + } + +} diff --git a/system/database/DB_query_builder.php b/system/database/DB_query_builder.php new file mode 100644 index 00000000..f35b9fd0 --- /dev/null +++ b/system/database/DB_query_builder.php @@ -0,0 +1,2808 @@ +_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'), 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 string $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 $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 + )); + } + +} diff --git a/system/database/DB_result.php b/system/database/DB_result.php new file mode 100644 index 00000000..ed5252d4 --- /dev/null +++ b/system/database/DB_result.php @@ -0,0 +1,665 @@ +conn_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(); + } + +} diff --git a/system/database/DB_utility.php b/system/database/DB_utility.php new file mode 100644 index 00000000..6642fda8 --- /dev/null +++ b/system/database/DB_utility.php @@ -0,0 +1,424 @@ +db =& $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, $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; + } + +} diff --git a/system/database/drivers/cubrid/cubrid_driver.php b/system/database/drivers/cubrid/cubrid_driver.php new file mode 100644 index 00000000..b3b436fe --- /dev/null +++ b/system/database/drivers/cubrid/cubrid_driver.php @@ -0,0 +1,405 @@ +dsn, $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); + } + +} diff --git a/system/database/drivers/cubrid/cubrid_forge.php b/system/database/drivers/cubrid/cubrid_forge.php new file mode 100644 index 00000000..69b53dd4 --- /dev/null +++ b/system/database/drivers/cubrid/cubrid_forge.php @@ -0,0 +1,230 @@ + '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; + } + +} diff --git a/system/database/drivers/cubrid/cubrid_result.php b/system/database/drivers/cubrid/cubrid_result.php new file mode 100644 index 00000000..75d70255 --- /dev/null +++ b/system/database/drivers/cubrid/cubrid_result.php @@ -0,0 +1,177 @@ +num_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); + } + +} diff --git a/system/database/drivers/cubrid/cubrid_utility.php b/system/database/drivers/cubrid/cubrid_utility.php new file mode 100644 index 00000000..ccf794b7 --- /dev/null +++ b/system/database/drivers/cubrid/cubrid_utility.php @@ -0,0 +1,79 @@ +db->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'); + } +} diff --git a/system/database/drivers/cubrid/index.html b/system/database/drivers/cubrid/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/cubrid/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/ibase/ibase_driver.php b/system/database/drivers/ibase/ibase_driver.php new file mode 100644 index 00000000..27e87d42 --- /dev/null +++ b/system/database/drivers/ibase/ibase_driver.php @@ -0,0 +1,413 @@ +hostname.':'.$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); + } + +} diff --git a/system/database/drivers/ibase/ibase_forge.php b/system/database/drivers/ibase/ibase_forge.php new file mode 100644 index 00000000..29a3acf6 --- /dev/null +++ b/system/database/drivers/ibase/ibase_forge.php @@ -0,0 +1,251 @@ + '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 + } + +} diff --git a/system/database/drivers/ibase/ibase_result.php b/system/database/drivers/ibase/ibase_result.php new file mode 100644 index 00000000..86530973 --- /dev/null +++ b/system/database/drivers/ibase/ibase_result.php @@ -0,0 +1,161 @@ +result_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; + } + +} diff --git a/system/database/drivers/ibase/ibase_utility.php b/system/database/drivers/ibase/ibase_utility.php new file mode 100644 index 00000000..a8087492 --- /dev/null +++ b/system/database/drivers/ibase/ibase_utility.php @@ -0,0 +1,69 @@ +db->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; + } + +} diff --git a/system/database/drivers/ibase/index.html b/system/database/drivers/ibase/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/ibase/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/index.html b/system/database/drivers/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/mssql/index.html b/system/database/drivers/mssql/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/mssql/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/mssql/mssql_driver.php b/system/database/drivers/mssql/mssql_driver.php new file mode 100644 index 00000000..e197cfb0 --- /dev/null +++ b/system/database/drivers/mssql/mssql_driver.php @@ -0,0 +1,518 @@ +port)) + { + $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); + } + +} diff --git a/system/database/drivers/mssql/mssql_forge.php b/system/database/drivers/mssql/mssql_forge.php new file mode 100644 index 00000000..07b93c24 --- /dev/null +++ b/system/database/drivers/mssql/mssql_forge.php @@ -0,0 +1,151 @@ + '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)'; + } + } + +} diff --git a/system/database/drivers/mssql/mssql_result.php b/system/database/drivers/mssql/mssql_result.php new file mode 100644 index 00000000..5d7d3bed --- /dev/null +++ b/system/database/drivers/mssql/mssql_result.php @@ -0,0 +1,198 @@ +num_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; + } + +} diff --git a/system/database/drivers/mssql/mssql_utility.php b/system/database/drivers/mssql/mssql_utility.php new file mode 100644 index 00000000..5c9941ac --- /dev/null +++ b/system/database/drivers/mssql/mssql_utility.php @@ -0,0 +1,77 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/drivers/mysql/index.html b/system/database/drivers/mysql/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/mysql/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/mysql/mysql_driver.php b/system/database/drivers/mysql/mysql_driver.php new file mode 100644 index 00000000..440715ae --- /dev/null +++ b/system/database/drivers/mysql/mysql_driver.php @@ -0,0 +1,494 @@ +port)) + { + $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); + } + +} diff --git a/system/database/drivers/mysql/mysql_forge.php b/system/database/drivers/mysql/mysql_forge.php new file mode 100644 index 00000000..b69aa36b --- /dev/null +++ b/system/database/drivers/mysql/mysql_forge.php @@ -0,0 +1,243 @@ +db->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; + } + +} diff --git a/system/database/drivers/mysql/mysql_result.php b/system/database/drivers/mysql/mysql_result.php new file mode 100644 index 00000000..842d7d39 --- /dev/null +++ b/system/database/drivers/mysql/mysql_result.php @@ -0,0 +1,199 @@ +num_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); + } + +} diff --git a/system/database/drivers/mysql/mysql_utility.php b/system/database/drivers/mysql/mysql_utility.php new file mode 100644 index 00000000..a5489297 --- /dev/null +++ b/system/database/drivers/mysql/mysql_utility.php @@ -0,0 +1,211 @@ +db->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; + } + +} diff --git a/system/database/drivers/mysqli/index.html b/system/database/drivers/mysqli/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/mysqli/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/mysqli/mysqli_driver.php b/system/database/drivers/mysqli/mysqli_driver.php new file mode 100644 index 00000000..0ca0f48f --- /dev/null +++ b/system/database/drivers/mysqli/mysqli_driver.php @@ -0,0 +1,546 @@ +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(); + } + +} diff --git a/system/database/drivers/mysqli/mysqli_forge.php b/system/database/drivers/mysqli/mysqli_forge.php new file mode 100644 index 00000000..92b1e94d --- /dev/null +++ b/system/database/drivers/mysqli/mysqli_forge.php @@ -0,0 +1,244 @@ +db->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; + } + +} diff --git a/system/database/drivers/mysqli/mysqli_result.php b/system/database/drivers/mysqli/mysqli_result.php new file mode 100644 index 00000000..0856eca4 --- /dev/null +++ b/system/database/drivers/mysqli/mysqli_result.php @@ -0,0 +1,232 @@ +num_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); + } + +} diff --git a/system/database/drivers/mysqli/mysqli_utility.php b/system/database/drivers/mysqli/mysqli_utility.php new file mode 100644 index 00000000..60642465 --- /dev/null +++ b/system/database/drivers/mysqli/mysqli_utility.php @@ -0,0 +1,211 @@ +db->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; + } + +} diff --git a/system/database/drivers/oci8/index.html b/system/database/drivers/oci8/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/oci8/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/oci8/oci8_driver.php b/system/database/drivers/oci8/oci8_driver.php new file mode 100644 index 00000000..a825c4a3 --- /dev/null +++ b/system/database/drivers/oci8/oci8_driver.php @@ -0,0 +1,701 @@ + '/^\(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() + { + 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(); + } +} diff --git a/system/database/drivers/oci8/oci8_forge.php b/system/database/drivers/oci8/oci8_forge.php new file mode 100644 index 00000000..58f3c391 --- /dev/null +++ b/system/database/drivers/oci8/oci8_forge.php @@ -0,0 +1,194 @@ +db->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) + { + // Not supported - sequences and triggers must be used instead + } + + // -------------------------------------------------------------------- + + /** + * 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; + } + } +} diff --git a/system/database/drivers/oci8/oci8_result.php b/system/database/drivers/oci8/oci8_result.php new file mode 100644 index 00000000..3da49aa7 --- /dev/null +++ b/system/database/drivers/oci8/oci8_result.php @@ -0,0 +1,229 @@ +stmt_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; + } + +} diff --git a/system/database/drivers/oci8/oci8_utility.php b/system/database/drivers/oci8/oci8_utility.php new file mode 100644 index 00000000..3a7261c1 --- /dev/null +++ b/system/database/drivers/oci8/oci8_utility.php @@ -0,0 +1,68 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/drivers/odbc/index.html b/system/database/drivers/odbc/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/odbc/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/odbc/odbc_driver.php b/system/database/drivers/odbc/odbc_driver.php new file mode 100644 index 00000000..72289bf9 --- /dev/null +++ b/system/database/drivers/odbc/odbc_driver.php @@ -0,0 +1,425 @@ +dsn)) + { + $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); + } +} diff --git a/system/database/drivers/odbc/odbc_forge.php b/system/database/drivers/odbc/odbc_forge.php new file mode 100644 index 00000000..05f9c76d --- /dev/null +++ b/system/database/drivers/odbc/odbc_forge.php @@ -0,0 +1,86 @@ +num_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; + } +} diff --git a/system/database/drivers/odbc/odbc_utility.php b/system/database/drivers/odbc/odbc_utility.php new file mode 100644 index 00000000..78720108 --- /dev/null +++ b/system/database/drivers/odbc/odbc_utility.php @@ -0,0 +1,63 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/drivers/pdo/index.html b/system/database/drivers/pdo/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/pdo/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/pdo/pdo_driver.php b/system/database/drivers/pdo/pdo_driver.php new file mode 100644 index 00000000..c5d120fd --- /dev/null +++ b/system/database/drivers/pdo/pdo_driver.php @@ -0,0 +1,329 @@ +dsn, $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; + } + + 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; + } + +} diff --git a/system/database/drivers/pdo/pdo_forge.php b/system/database/drivers/pdo/pdo_forge.php new file mode 100644 index 00000000..e512d3d6 --- /dev/null +++ b/system/database/drivers/pdo/pdo_forge.php @@ -0,0 +1,65 @@ +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); + } + 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); + } + +} diff --git a/system/database/drivers/pdo/pdo_utility.php b/system/database/drivers/pdo/pdo_utility.php new file mode 100644 index 00000000..6c40cf32 --- /dev/null +++ b/system/database/drivers/pdo/pdo_utility.php @@ -0,0 +1,63 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/index.html b/system/database/drivers/pdo/subdrivers/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php b/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php new file mode 100644 index 00000000..2e39bb23 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php @@ -0,0 +1,200 @@ +dsn)) + { + $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 : ''); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php b/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php new file mode 100644 index 00000000..306150b9 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php @@ -0,0 +1,217 @@ + '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'; + } + } + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php b/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php new file mode 100644 index 00000000..9a6b643f --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php @@ -0,0 +1,209 @@ +dsn)) + { + $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); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php b/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php new file mode 100644 index 00000000..f2ee3f5e --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php @@ -0,0 +1,230 @@ + '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; + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php b/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php new file mode 100644 index 00000000..09dbdf08 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php @@ -0,0 +1,353 @@ +dsn)) + { + $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); + } +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php b/system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php new file mode 100644 index 00000000..f38ac99b --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php @@ -0,0 +1,149 @@ + '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)'; + } + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php b/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php new file mode 100644 index 00000000..2c49f121 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php @@ -0,0 +1,279 @@ +dsn)) + { + $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; + } +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php b/system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php new file mode 100644 index 00000000..eceb5979 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php @@ -0,0 +1,237 @@ + '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 + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php b/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php new file mode 100644 index 00000000..00654d7c --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php @@ -0,0 +1,244 @@ +dsn)) + { + $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; + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php b/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php new file mode 100644 index 00000000..99d75b64 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php @@ -0,0 +1,154 @@ + '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 + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php b/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php new file mode 100644 index 00000000..114eb747 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php @@ -0,0 +1,309 @@ +dsn)) + { + $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); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php b/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php new file mode 100644 index 00000000..1f4bcd1a --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php @@ -0,0 +1,163 @@ + '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 + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php b/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php new file mode 100644 index 00000000..73b88bcf --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php @@ -0,0 +1,379 @@ +dsn)) + { + $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); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php b/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php new file mode 100644 index 00000000..01595a60 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php @@ -0,0 +1,256 @@ +db->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; + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php b/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php new file mode 100644 index 00000000..dba49585 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php @@ -0,0 +1,326 @@ +dsn)) + { + $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[1]; + } + + 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): ''); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php b/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php new file mode 100644 index 00000000..b5d3eb14 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php @@ -0,0 +1,183 @@ +db->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) + { + // Not supported - sequences and triggers must be used instead + } + + /** + * 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; + } + } +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php b/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php new file mode 100644 index 00000000..93a6420e --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php @@ -0,0 +1,229 @@ +dsn)) + { + $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); + } +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php b/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php new file mode 100644 index 00000000..47226d7a --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php @@ -0,0 +1,70 @@ +dsn)) + { + $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 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 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 : ''); + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php b/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php new file mode 100644 index 00000000..a4ccff40 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php @@ -0,0 +1,210 @@ + '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'; + } + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php b/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php new file mode 100644 index 00000000..f55d9a6c --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php @@ -0,0 +1,213 @@ +dsn)) + { + $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; + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php b/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php new file mode 100644 index 00000000..545b2a3d --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php @@ -0,0 +1,238 @@ +db->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(); + } + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php new file mode 100644 index 00000000..84109ae3 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php @@ -0,0 +1,369 @@ +dsn)) + { + $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; + } + +} diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php new file mode 100644 index 00000000..b23c6d44 --- /dev/null +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php @@ -0,0 +1,149 @@ + '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)'; + } + } + +} diff --git a/system/database/drivers/postgre/index.html b/system/database/drivers/postgre/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/postgre/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/postgre/postgre_driver.php b/system/database/drivers/postgre/postgre_driver.php new file mode 100644 index 00000000..5ce27610 --- /dev/null +++ b/system/database/drivers/postgre/postgre_driver.php @@ -0,0 +1,619 @@ +dsn)) + { + return; + } + + $this->dsn === '' 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 + */ + public function db_connect($persistent = FALSE) + { + $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 + */ + 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 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 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); + } + +} diff --git a/system/database/drivers/postgre/postgre_forge.php b/system/database/drivers/postgre/postgre_forge.php new file mode 100644 index 00000000..481e222b --- /dev/null +++ b/system/database/drivers/postgre/postgre_forge.php @@ -0,0 +1,205 @@ + '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'; + } + } + +} diff --git a/system/database/drivers/postgre/postgre_result.php b/system/database/drivers/postgre/postgre_result.php new file mode 100644 index 00000000..b0054dda --- /dev/null +++ b/system/database/drivers/postgre/postgre_result.php @@ -0,0 +1,182 @@ +num_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 (is_resource($this->result_id)) + { + pg_free_result($this->result_id); + $this->result_id = FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero. + * + * @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); + } + +} diff --git a/system/database/drivers/postgre/postgre_utility.php b/system/database/drivers/postgre/postgre_utility.php new file mode 100644 index 00000000..450aa36e --- /dev/null +++ b/system/database/drivers/postgre/postgre_utility.php @@ -0,0 +1,78 @@ +db->display_error('db_unsupported_feature'); + } +} diff --git a/system/database/drivers/sqlite/index.html b/system/database/drivers/sqlite/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/sqlite/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/sqlite/sqlite_driver.php b/system/database/drivers/sqlite/sqlite_driver.php new file mode 100644 index 00000000..aec3d748 --- /dev/null +++ b/system/database/drivers/sqlite/sqlite_driver.php @@ -0,0 +1,330 @@ +database, 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); + } + +} diff --git a/system/database/drivers/sqlite/sqlite_forge.php b/system/database/drivers/sqlite/sqlite_forge.php new file mode 100644 index 00000000..6aa9c61c --- /dev/null +++ b/system/database/drivers/sqlite/sqlite_forge.php @@ -0,0 +1,205 @@ +db->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(); + } + } + +} diff --git a/system/database/drivers/sqlite/sqlite_result.php b/system/database/drivers/sqlite/sqlite_result.php new file mode 100644 index 00000000..30c93a26 --- /dev/null +++ b/system/database/drivers/sqlite/sqlite_result.php @@ -0,0 +1,164 @@ +num_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); + } + +} diff --git a/system/database/drivers/sqlite/sqlite_utility.php b/system/database/drivers/sqlite/sqlite_utility.php new file mode 100644 index 00000000..2c7f8099 --- /dev/null +++ b/system/database/drivers/sqlite/sqlite_utility.php @@ -0,0 +1,61 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/drivers/sqlite3/index.html b/system/database/drivers/sqlite3/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/sqlite3/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/sqlite3/sqlite3_driver.php b/system/database/drivers/sqlite3/sqlite3_driver.php new file mode 100644 index 00000000..5d057ba5 --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_driver.php @@ -0,0 +1,344 @@ +password) + ? 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(); + } + +} diff --git a/system/database/drivers/sqlite3/sqlite3_forge.php b/system/database/drivers/sqlite3/sqlite3_forge.php new file mode 100644 index 00000000..4019a952 --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_forge.php @@ -0,0 +1,225 @@ +db->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(); + } + } + +} diff --git a/system/database/drivers/sqlite3/sqlite3_result.php b/system/database/drivers/sqlite3/sqlite3_result.php new file mode 100644 index 00000000..d656fed1 --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_result.php @@ -0,0 +1,194 @@ +result_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(); + } + +} diff --git a/system/database/drivers/sqlite3/sqlite3_utility.php b/system/database/drivers/sqlite3/sqlite3_utility.php new file mode 100644 index 00000000..1bdf3ae3 --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_utility.php @@ -0,0 +1,61 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/drivers/sqlsrv/index.html b/system/database/drivers/sqlsrv/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/drivers/sqlsrv/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/database/drivers/sqlsrv/sqlsrv_driver.php b/system/database/drivers/sqlsrv/sqlsrv_driver.php new file mode 100644 index 00000000..a22a8b31 --- /dev/null +++ b/system/database/drivers/sqlsrv/sqlsrv_driver.php @@ -0,0 +1,543 @@ +scrollable === 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); + } + +} diff --git a/system/database/drivers/sqlsrv/sqlsrv_forge.php b/system/database/drivers/sqlsrv/sqlsrv_forge.php new file mode 100644 index 00000000..90c3120a --- /dev/null +++ b/system/database/drivers/sqlsrv/sqlsrv_forge.php @@ -0,0 +1,149 @@ + '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)'; + } + } + +} diff --git a/system/database/drivers/sqlsrv/sqlsrv_result.php b/system/database/drivers/sqlsrv/sqlsrv_result.php new file mode 100644 index 00000000..e2649c66 --- /dev/null +++ b/system/database/drivers/sqlsrv/sqlsrv_result.php @@ -0,0 +1,193 @@ +scrollable = $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); + } + +} diff --git a/system/database/drivers/sqlsrv/sqlsrv_utility.php b/system/database/drivers/sqlsrv/sqlsrv_utility.php new file mode 100644 index 00000000..6dd01a99 --- /dev/null +++ b/system/database/drivers/sqlsrv/sqlsrv_utility.php @@ -0,0 +1,77 @@ +db->display_error('db_unsupported_feature'); + } + +} diff --git a/system/database/index.html b/system/database/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/database/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/fonts/index.html b/system/fonts/index.html new file mode 100644 index 00000000..b702fbc3 --- /dev/null +++ b/system/fonts/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/system/fonts/texb.ttf b/system/fonts/texb.ttf new file mode 100644 index 00000000..383c88b8 Binary files /dev/null and b/system/fonts/texb.ttf differ diff --git a/system/helpers/array_helper.php b/system/helpers/array_helper.php new file mode 100644 index 00000000..cb7eca68 --- /dev/null +++ b/system/helpers/array_helper.php @@ -0,0 +1,115 @@ + '', + '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 ($img_path === '' OR $img_url === '' + OR ! is_dir($img_path) OR ! is_really_writable($img_path) + OR ! extension_loaded('gd')) + { + 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); + } +} diff --git a/system/helpers/cookie_helper.php b/system/helpers/cookie_helper.php new file mode 100644 index 00000000..b9c2cb68 --- /dev/null +++ b/system/helpers/cookie_helper.php @@ -0,0 +1,113 @@ +input->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); + } +} diff --git a/system/helpers/date_helper.php b/system/helpers/date_helper.php new file mode 100644 index 00000000..5c660e2e --- /dev/null +++ b/system/helpers/date_helper.php @@ -0,0 +1,742 @@ +format('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 http://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; + } +} diff --git a/system/helpers/directory_helper.php b/system/helpers/directory_helper.php new file mode 100644 index 00000000..73777bfb --- /dev/null +++ b/system/helpers/directory_helper.php @@ -0,0 +1,101 @@ + 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; + } +} diff --git a/system/helpers/download_helper.php b/system/helpers/download_helper.php new file mode 100644 index 00000000..d8e30ae9 --- /dev/null +++ b/system/helpers/download_helper.php @@ -0,0 +1,158 @@ + 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); + } +} diff --git a/system/helpers/form_helper.php b/system/helpers/form_helper.php new file mode 100644 index 00000000..5910d8e1 --- /dev/null +++ b/system/helpers/form_helper.php @@ -0,0 +1,1055 @@ +config->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