From b96a69f59238515597738f40c2034ab23ab9674a Mon Sep 17 00:00:00 2001 From: Timothy J Warren Date: Wed, 18 Dec 2019 16:07:09 -0500 Subject: [PATCH] Update CodeIgniter version and associated config --- .travis.yml | 4 +- application/config/config.php | 171 +- application/config/database.php | 61 +- .../controllers/{account.php => Account.php} | 0 .../{calendar.php => Calendar.php} | 0 .../{category.php => Category.php} | 0 .../controllers/{friend.php => Friend.php} | 0 .../controllers/{group.php => Group.php} | 0 .../controllers/{login.php => Login.php} | 0 .../{reminder.php => Reminder.php} | 0 .../controllers/{task.php => Task.php} | 0 .../{friend_model.php => Friend_model.php} | 0 .../models/{mail_model.php => Mail_model.php} | 0 .../models/{task_model.php => Task_model.php} | 0 application/views/errors/html/error_404.php | 64 + application/views/errors/html/error_db.php | 64 + .../views/errors/html/error_exception.php | 32 + .../views/errors/html/error_general.php | 64 + application/views/errors/html/error_php.php | 33 + application/views/login/login.php | 2 +- application/views/task/list.php | 2 +- composer.json | 2 +- ...190220154203_recreate_session_db_table.php | 49 + phinx.yml | 33 + system/.htaccess | 7 +- system/core/Benchmark.php | 105 +- system/core/CodeIgniter.php | 483 ++-- system/core/Common.php | 907 ++++--- system/core/Config.php | 410 ++-- system/core/Controller.php | 74 +- system/core/Exceptions.php | 271 ++- system/core/Hooks.php | 218 +- system/core/Input.php | 1070 +++++---- system/core/Lang.php | 171 +- system/core/Loader.php | 1241 +++++----- system/core/Log.php | 296 +++ system/core/Model.php | 77 +- system/core/Output.php | 730 ++++-- system/core/Router.php | 613 +++-- system/core/Security.php | 953 +++++--- system/core/URI.php | 669 +++--- system/core/Utf8.php | 149 +- system/core/compat/hash.php | 254 ++ .../javascript => core/compat}/index.html | 3 +- system/core/compat/mbstring.php | 149 ++ system/core/compat/password.php | 251 ++ system/core/compat/standard.php | 182 ++ system/core/index.html | 3 +- system/database/DB.php | 79 +- system/database/DB_cache.php | 61 +- system/database/DB_driver.php | 353 ++- system/database/DB_forge.php | 160 +- system/database/DB_query_builder.php | 452 ++-- system/database/DB_result.php | 73 +- system/database/DB_utility.php | 59 +- .../database/drivers/cubrid/cubrid_driver.php | 110 +- .../database/drivers/cubrid/cubrid_forge.php | 51 +- .../database/drivers/cubrid/cubrid_result.php | 49 +- .../drivers/cubrid/cubrid_utility.php | 48 +- system/database/drivers/cubrid/index.html | 3 +- .../database/drivers/ibase/ibase_driver.php | 114 +- system/database/drivers/ibase/ibase_forge.php | 52 +- .../database/drivers/ibase/ibase_result.php | 49 +- .../database/drivers/ibase/ibase_utility.php | 48 +- system/database/drivers/ibase/index.html | 3 +- system/database/drivers/index.html | 3 +- system/database/drivers/mssql/index.html | 3 +- .../database/drivers/mssql/mssql_driver.php | 114 +- system/database/drivers/mssql/mssql_forge.php | 55 +- .../database/drivers/mssql/mssql_result.php | 53 +- .../database/drivers/mssql/mssql_utility.php | 50 +- system/database/drivers/mysql/index.html | 3 +- .../database/drivers/mysql/mysql_driver.php | 132 +- system/database/drivers/mysql/mysql_forge.php | 52 +- .../database/drivers/mysql/mysql_result.php | 49 +- .../database/drivers/mysql/mysql_utility.php | 48 +- system/database/drivers/mysqli/index.html | 3 +- .../database/drivers/mysqli/mysqli_driver.php | 229 +- .../database/drivers/mysqli/mysqli_forge.php | 53 +- .../database/drivers/mysqli/mysqli_result.php | 101 +- .../drivers/mysqli/mysqli_utility.php | 54 +- system/database/drivers/oci8/index.html | 3 +- system/database/drivers/oci8/oci8_driver.php | 213 +- system/database/drivers/oci8/oci8_forge.php | 98 +- system/database/drivers/oci8/oci8_result.php | 49 +- system/database/drivers/oci8/oci8_utility.php | 48 +- system/database/drivers/odbc/index.html | 3 +- system/database/drivers/odbc/odbc_driver.php | 267 ++- system/database/drivers/odbc/odbc_forge.php | 50 +- system/database/drivers/odbc/odbc_result.php | 51 +- system/database/drivers/odbc/odbc_utility.php | 50 +- system/database/drivers/pdo/index.html | 3 +- system/database/drivers/pdo/pdo_driver.php | 137 +- system/database/drivers/pdo/pdo_forge.php | 50 +- system/database/drivers/pdo/pdo_result.php | 53 +- system/database/drivers/pdo/pdo_utility.php | 50 +- .../drivers/pdo/subdrivers/index.html | 3 +- .../drivers/pdo/subdrivers/pdo_4d_driver.php | 50 +- .../drivers/pdo/subdrivers/pdo_4d_forge.php | 52 +- .../pdo/subdrivers/pdo_cubrid_driver.php | 96 +- .../pdo/subdrivers/pdo_cubrid_forge.php | 51 +- .../pdo/subdrivers/pdo_dblib_driver.php | 86 +- .../pdo/subdrivers/pdo_dblib_forge.php | 53 +- .../pdo/subdrivers/pdo_firebird_driver.php | 73 +- .../pdo/subdrivers/pdo_firebird_forge.php | 50 +- .../drivers/pdo/subdrivers/pdo_ibm_driver.php | 50 +- .../drivers/pdo/subdrivers/pdo_ibm_forge.php | 48 +- .../pdo/subdrivers/pdo_informix_driver.php | 50 +- .../pdo/subdrivers/pdo_informix_forge.php | 48 +- .../pdo/subdrivers/pdo_mysql_driver.php | 206 +- .../pdo/subdrivers/pdo_mysql_forge.php | 51 +- .../drivers/pdo/subdrivers/pdo_oci_driver.php | 87 +- .../drivers/pdo/subdrivers/pdo_oci_forge.php | 99 +- .../pdo/subdrivers/pdo_odbc_driver.php | 147 +- .../drivers/pdo/subdrivers/pdo_odbc_forge.php | 48 +- .../pdo/subdrivers/pdo_pgsql_driver.php | 70 +- .../pdo/subdrivers/pdo_pgsql_forge.php | 65 +- .../pdo/subdrivers/pdo_sqlite_driver.php | 81 +- .../pdo/subdrivers/pdo_sqlite_forge.php | 53 +- .../pdo/subdrivers/pdo_sqlsrv_driver.php | 64 +- .../pdo/subdrivers/pdo_sqlsrv_forge.php | 53 +- system/database/drivers/postgre/index.html | 3 +- .../drivers/postgre/postgre_driver.php | 146 +- .../drivers/postgre/postgre_forge.php | 67 +- .../drivers/postgre/postgre_result.php | 51 +- .../drivers/postgre/postgre_utility.php | 50 +- system/database/drivers/sqlite/index.html | 3 +- .../database/drivers/sqlite/sqlite_driver.php | 94 +- .../database/drivers/sqlite/sqlite_forge.php | 52 +- .../database/drivers/sqlite/sqlite_result.php | 49 +- .../drivers/sqlite/sqlite_utility.php | 48 +- system/database/drivers/sqlite3/index.html | 3 +- .../drivers/sqlite3/sqlite3_driver.php | 116 +- .../drivers/sqlite3/sqlite3_forge.php | 55 +- .../drivers/sqlite3/sqlite3_result.php | 51 +- .../drivers/sqlite3/sqlite3_utility.php | 48 +- system/database/drivers/sqlsrv/index.html | 3 +- .../database/drivers/sqlsrv/sqlsrv_driver.php | 118 +- .../database/drivers/sqlsrv/sqlsrv_forge.php | 53 +- .../database/drivers/sqlsrv/sqlsrv_result.php | 49 +- .../drivers/sqlsrv/sqlsrv_utility.php | 48 +- system/database/index.html | 3 +- system/fonts/index.html | 3 +- system/fonts/texb.ttf | Bin system/helpers/array_helper.php | 144 +- system/helpers/captcha_helper.php | 351 ++- system/helpers/cookie_helper.php | 136 +- system/helpers/date_helper.php | 805 ++++--- system/helpers/directory_helper.php | 83 +- system/helpers/download_helper.php | 183 +- system/helpers/email_helper.php | 84 +- system/helpers/file_helper.php | 432 ++-- system/helpers/form_helper.php | 1103 ++++----- system/helpers/html_helper.php | 398 ++-- system/helpers/index.html | 3 +- system/helpers/inflector_helper.php | 278 ++- system/helpers/language_helper.php | 79 +- system/helpers/number_helper.php | 64 +- system/helpers/path_helper.php | 92 +- system/helpers/security_helper.php | 143 +- system/helpers/smiley_helper.php | 322 ++- system/helpers/string_helper.php | 371 ++- system/helpers/text_helper.php | 508 ++-- system/helpers/typography_helper.php | 109 +- system/helpers/url_helper.php | 615 +++-- system/helpers/xml_helper.php | 81 +- system/index.html | 3 +- system/language/english/calendar_lang.php | 131 +- system/language/english/date_lang.php | 77 +- system/language/english/db_lang.php | 44 +- system/language/english/email_lang.php | 78 +- .../language/english/form_validation_lang.php | 94 +- system/language/english/ftp_lang.php | 65 +- system/language/english/imglib_lang.php | 77 +- system/language/english/index.html | 3 +- system/language/english/migration_lang.php | 56 +- system/language/english/number_lang.php | 50 +- system/language/english/pagination_lang.php | 43 + system/language/english/profiler_lang.php | 79 +- system/language/english/unit_test_lang.php | 79 +- system/language/english/upload_lang.php | 73 +- system/language/index.html | 3 +- system/libraries/Cache/Cache.php | 249 +- system/libraries/Cache/drivers/Cache_apc.php | 180 +- .../libraries/Cache/drivers/Cache_dummy.php | 108 +- system/libraries/Cache/drivers/Cache_file.php | 221 +- .../Cache/drivers/Cache_memcached.php | 295 ++- .../libraries/Cache/drivers/Cache_redis.php | 328 +++ .../Cache/drivers/Cache_wincache.php | 217 ++ system/libraries/Cache/drivers/index.html | 3 +- system/libraries/Cache/index.html | 3 +- system/libraries/Calendar.php | 471 ++-- system/libraries/Cart.php | 376 +-- system/libraries/Driver.php | 295 ++- system/libraries/Email.php | 2084 ++++++++++------- system/libraries/Encrypt.php | 323 +-- system/libraries/Encryption.php | 941 ++++++++ system/libraries/Form_validation.php | 1269 +++++----- system/libraries/Ftp.php | 413 ++-- system/libraries/Image_lib.php | 1525 +++++++----- system/libraries/Javascript.php | 285 ++- .../{javascript => Javascript}/Jquery.php | 617 ++--- system/libraries/Javascript/index.html | 11 + system/libraries/Log.php | 114 - system/libraries/Migration.php | 438 ++-- system/libraries/Pagination.php | 742 ++++-- system/libraries/Parser.php | 212 +- system/libraries/Profiler.php | 468 ++-- system/libraries/Session.php | 793 ------- system/libraries/Session/Session.php | 983 ++++++++ .../Session/SessionHandlerInterface.php | 59 + system/libraries/Session/Session_driver.php | 208 ++ .../drivers/Session_database_driver.php | 446 ++++ .../Session/drivers/Session_files_driver.php | 426 ++++ .../drivers/Session_memcached_driver.php | 397 ++++ .../Session/drivers/Session_redis_driver.php | 417 ++++ system/libraries/Session/drivers/index.html | 11 + system/libraries/Session/index.html | 11 + system/libraries/Sha1.php | 251 -- system/libraries/Table.php | 429 ++-- system/libraries/Trackback.php | 324 +-- system/libraries/Typography.php | 228 +- system/libraries/Unit_test.php | 303 +-- system/libraries/Upload.php | 1052 +++++---- system/libraries/User_agent.php | 350 ++- system/libraries/Xmlrpc.php | 1691 ++++++++----- system/libraries/Xmlrpcs.php | 377 +-- system/libraries/Zip.php | 383 +-- system/libraries/index.html | 3 +- 229 files changed, 28191 insertions(+), 17083 deletions(-) rename application/controllers/{account.php => Account.php} (100%) rename application/controllers/{calendar.php => Calendar.php} (100%) rename application/controllers/{category.php => Category.php} (100%) rename application/controllers/{friend.php => Friend.php} (100%) rename application/controllers/{group.php => Group.php} (100%) rename application/controllers/{login.php => Login.php} (100%) rename application/controllers/{reminder.php => Reminder.php} (100%) rename application/controllers/{task.php => Task.php} (100%) rename application/models/{friend_model.php => Friend_model.php} (100%) rename application/models/{mail_model.php => Mail_model.php} (100%) rename application/models/{task_model.php => Task_model.php} (100%) create mode 100644 application/views/errors/html/error_404.php create mode 100644 application/views/errors/html/error_db.php create mode 100644 application/views/errors/html/error_exception.php create mode 100644 application/views/errors/html/error_general.php create mode 100644 application/views/errors/html/error_php.php create mode 100644 migrations/20190220154203_recreate_session_db_table.php create mode 100644 phinx.yml mode change 100755 => 100644 system/.htaccess mode change 100755 => 100644 system/core/Benchmark.php mode change 100755 => 100644 system/core/CodeIgniter.php mode change 100755 => 100644 system/core/Common.php mode change 100755 => 100644 system/core/Config.php mode change 100755 => 100644 system/core/Controller.php mode change 100755 => 100644 system/core/Exceptions.php mode change 100755 => 100644 system/core/Hooks.php mode change 100755 => 100644 system/core/Input.php mode change 100755 => 100644 system/core/Lang.php mode change 100755 => 100644 system/core/Loader.php create mode 100644 system/core/Log.php mode change 100755 => 100644 system/core/Model.php mode change 100755 => 100644 system/core/Output.php mode change 100755 => 100644 system/core/Router.php mode change 100755 => 100644 system/core/Security.php mode change 100755 => 100644 system/core/URI.php mode change 100755 => 100644 system/core/Utf8.php create mode 100644 system/core/compat/hash.php rename system/{libraries/javascript => core/compat}/index.html (81%) mode change 100755 => 100644 create mode 100644 system/core/compat/mbstring.php create mode 100644 system/core/compat/password.php create mode 100644 system/core/compat/standard.php mode change 100755 => 100644 system/core/index.html mode change 100755 => 100644 system/database/DB.php mode change 100755 => 100644 system/database/DB_cache.php mode change 100755 => 100644 system/database/DB_driver.php mode change 100755 => 100644 system/database/DB_forge.php mode change 100755 => 100644 system/database/DB_query_builder.php mode change 100755 => 100644 system/database/DB_result.php mode change 100755 => 100644 system/database/DB_utility.php mode change 100755 => 100644 system/database/drivers/cubrid/cubrid_driver.php mode change 100755 => 100644 system/database/drivers/cubrid/cubrid_forge.php mode change 100755 => 100644 system/database/drivers/cubrid/cubrid_result.php mode change 100755 => 100644 system/database/drivers/cubrid/cubrid_utility.php mode change 100755 => 100644 system/database/drivers/cubrid/index.html mode change 100755 => 100644 system/database/drivers/ibase/ibase_driver.php mode change 100755 => 100644 system/database/drivers/ibase/ibase_forge.php mode change 100755 => 100644 system/database/drivers/ibase/ibase_result.php mode change 100755 => 100644 system/database/drivers/ibase/ibase_utility.php mode change 100755 => 100644 system/database/drivers/ibase/index.html mode change 100755 => 100644 system/database/drivers/index.html mode change 100755 => 100644 system/database/drivers/mssql/index.html mode change 100755 => 100644 system/database/drivers/mssql/mssql_driver.php mode change 100755 => 100644 system/database/drivers/mssql/mssql_forge.php mode change 100755 => 100644 system/database/drivers/mssql/mssql_result.php mode change 100755 => 100644 system/database/drivers/mssql/mssql_utility.php mode change 100755 => 100644 system/database/drivers/mysql/index.html mode change 100755 => 100644 system/database/drivers/mysql/mysql_driver.php mode change 100755 => 100644 system/database/drivers/mysql/mysql_forge.php mode change 100755 => 100644 system/database/drivers/mysql/mysql_result.php mode change 100755 => 100644 system/database/drivers/mysql/mysql_utility.php mode change 100755 => 100644 system/database/drivers/mysqli/index.html mode change 100755 => 100644 system/database/drivers/mysqli/mysqli_driver.php mode change 100755 => 100644 system/database/drivers/mysqli/mysqli_forge.php mode change 100755 => 100644 system/database/drivers/mysqli/mysqli_result.php mode change 100755 => 100644 system/database/drivers/mysqli/mysqli_utility.php mode change 100755 => 100644 system/database/drivers/oci8/index.html mode change 100755 => 100644 system/database/drivers/oci8/oci8_driver.php mode change 100755 => 100644 system/database/drivers/oci8/oci8_forge.php mode change 100755 => 100644 system/database/drivers/oci8/oci8_result.php mode change 100755 => 100644 system/database/drivers/oci8/oci8_utility.php mode change 100755 => 100644 system/database/drivers/odbc/index.html mode change 100755 => 100644 system/database/drivers/odbc/odbc_driver.php mode change 100755 => 100644 system/database/drivers/odbc/odbc_forge.php mode change 100755 => 100644 system/database/drivers/odbc/odbc_result.php mode change 100755 => 100644 system/database/drivers/odbc/odbc_utility.php mode change 100755 => 100644 system/database/drivers/pdo/index.html mode change 100755 => 100644 system/database/drivers/pdo/pdo_driver.php mode change 100755 => 100644 system/database/drivers/pdo/pdo_forge.php mode change 100755 => 100644 system/database/drivers/pdo/pdo_result.php mode change 100755 => 100644 system/database/drivers/pdo/pdo_utility.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/index.html mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_4d_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_4d_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_informix_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_informix_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_oci_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_oci_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php mode change 100755 => 100644 system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php mode change 100755 => 100644 system/database/drivers/postgre/index.html mode change 100755 => 100644 system/database/drivers/postgre/postgre_driver.php mode change 100755 => 100644 system/database/drivers/postgre/postgre_forge.php mode change 100755 => 100644 system/database/drivers/postgre/postgre_result.php mode change 100755 => 100644 system/database/drivers/postgre/postgre_utility.php mode change 100755 => 100644 system/database/drivers/sqlite/index.html mode change 100755 => 100644 system/database/drivers/sqlite/sqlite_driver.php mode change 100755 => 100644 system/database/drivers/sqlite/sqlite_forge.php mode change 100755 => 100644 system/database/drivers/sqlite/sqlite_result.php mode change 100755 => 100644 system/database/drivers/sqlite/sqlite_utility.php mode change 100755 => 100644 system/database/drivers/sqlite3/index.html mode change 100755 => 100644 system/database/drivers/sqlite3/sqlite3_driver.php mode change 100755 => 100644 system/database/drivers/sqlite3/sqlite3_forge.php mode change 100755 => 100644 system/database/drivers/sqlite3/sqlite3_result.php mode change 100755 => 100644 system/database/drivers/sqlite3/sqlite3_utility.php mode change 100755 => 100644 system/database/drivers/sqlsrv/index.html mode change 100755 => 100644 system/database/drivers/sqlsrv/sqlsrv_driver.php mode change 100755 => 100644 system/database/drivers/sqlsrv/sqlsrv_forge.php mode change 100755 => 100644 system/database/drivers/sqlsrv/sqlsrv_result.php mode change 100755 => 100644 system/database/drivers/sqlsrv/sqlsrv_utility.php mode change 100755 => 100644 system/database/index.html mode change 100755 => 100644 system/fonts/index.html mode change 100755 => 100644 system/fonts/texb.ttf mode change 100755 => 100644 system/helpers/array_helper.php mode change 100755 => 100644 system/helpers/captcha_helper.php mode change 100755 => 100644 system/helpers/cookie_helper.php mode change 100755 => 100644 system/helpers/date_helper.php mode change 100755 => 100644 system/helpers/directory_helper.php mode change 100755 => 100644 system/helpers/download_helper.php mode change 100755 => 100644 system/helpers/email_helper.php mode change 100755 => 100644 system/helpers/file_helper.php mode change 100755 => 100644 system/helpers/form_helper.php mode change 100755 => 100644 system/helpers/html_helper.php mode change 100755 => 100644 system/helpers/index.html mode change 100755 => 100644 system/helpers/inflector_helper.php mode change 100755 => 100644 system/helpers/language_helper.php mode change 100755 => 100644 system/helpers/number_helper.php mode change 100755 => 100644 system/helpers/path_helper.php mode change 100755 => 100644 system/helpers/security_helper.php mode change 100755 => 100644 system/helpers/smiley_helper.php mode change 100755 => 100644 system/helpers/string_helper.php mode change 100755 => 100644 system/helpers/text_helper.php mode change 100755 => 100644 system/helpers/typography_helper.php mode change 100755 => 100644 system/helpers/url_helper.php mode change 100755 => 100644 system/helpers/xml_helper.php mode change 100755 => 100644 system/index.html mode change 100755 => 100644 system/language/english/calendar_lang.php mode change 100755 => 100644 system/language/english/date_lang.php mode change 100755 => 100644 system/language/english/db_lang.php mode change 100755 => 100644 system/language/english/email_lang.php mode change 100755 => 100644 system/language/english/form_validation_lang.php mode change 100755 => 100644 system/language/english/ftp_lang.php mode change 100755 => 100644 system/language/english/imglib_lang.php mode change 100755 => 100644 system/language/english/index.html mode change 100755 => 100644 system/language/english/migration_lang.php mode change 100755 => 100644 system/language/english/number_lang.php create mode 100644 system/language/english/pagination_lang.php mode change 100755 => 100644 system/language/english/profiler_lang.php mode change 100755 => 100644 system/language/english/unit_test_lang.php mode change 100755 => 100644 system/language/english/upload_lang.php mode change 100755 => 100644 system/language/index.html mode change 100755 => 100644 system/libraries/Cache/Cache.php mode change 100755 => 100644 system/libraries/Cache/drivers/Cache_apc.php mode change 100755 => 100644 system/libraries/Cache/drivers/Cache_dummy.php mode change 100755 => 100644 system/libraries/Cache/drivers/Cache_file.php mode change 100755 => 100644 system/libraries/Cache/drivers/Cache_memcached.php create mode 100644 system/libraries/Cache/drivers/Cache_redis.php create mode 100644 system/libraries/Cache/drivers/Cache_wincache.php mode change 100755 => 100644 system/libraries/Cache/drivers/index.html mode change 100755 => 100644 system/libraries/Cache/index.html mode change 100755 => 100644 system/libraries/Calendar.php mode change 100755 => 100644 system/libraries/Cart.php mode change 100755 => 100644 system/libraries/Driver.php mode change 100755 => 100644 system/libraries/Email.php mode change 100755 => 100644 system/libraries/Encrypt.php create mode 100644 system/libraries/Encryption.php mode change 100755 => 100644 system/libraries/Form_validation.php mode change 100755 => 100644 system/libraries/Ftp.php mode change 100755 => 100644 system/libraries/Image_lib.php mode change 100755 => 100644 system/libraries/Javascript.php rename system/libraries/{javascript => Javascript}/Jquery.php (61%) mode change 100755 => 100644 create mode 100644 system/libraries/Javascript/index.html delete mode 100755 system/libraries/Log.php mode change 100755 => 100644 system/libraries/Migration.php mode change 100755 => 100644 system/libraries/Pagination.php mode change 100755 => 100644 system/libraries/Parser.php mode change 100755 => 100644 system/libraries/Profiler.php delete mode 100755 system/libraries/Session.php create mode 100644 system/libraries/Session/Session.php create mode 100644 system/libraries/Session/SessionHandlerInterface.php create mode 100644 system/libraries/Session/Session_driver.php create mode 100644 system/libraries/Session/drivers/Session_database_driver.php create mode 100644 system/libraries/Session/drivers/Session_files_driver.php create mode 100644 system/libraries/Session/drivers/Session_memcached_driver.php create mode 100644 system/libraries/Session/drivers/Session_redis_driver.php create mode 100644 system/libraries/Session/drivers/index.html create mode 100644 system/libraries/Session/index.html delete mode 100755 system/libraries/Sha1.php mode change 100755 => 100644 system/libraries/Table.php mode change 100755 => 100644 system/libraries/Trackback.php mode change 100755 => 100644 system/libraries/Typography.php mode change 100755 => 100644 system/libraries/Unit_test.php mode change 100755 => 100644 system/libraries/Upload.php mode change 100755 => 100644 system/libraries/User_agent.php mode change 100755 => 100644 system/libraries/Xmlrpc.php mode change 100755 => 100644 system/libraries/Xmlrpcs.php mode change 100755 => 100644 system/libraries/Zip.php mode change 100755 => 100644 system/libraries/index.html diff --git a/.travis.yml b/.travis.yml index cd44819..9ca2c38 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,10 +3,8 @@ language: php sudo: false php: - - 5.4 - - 5.5 - - 5.6 - 7.0 + - 7.1 - hhvm install: diff --git a/application/config/config.php b/application/config/config.php index 43e4988..6e43ed3 100755 --- a/application/config/config.php +++ b/application/config/config.php @@ -106,6 +106,27 @@ $config['enable_hooks'] = TRUE; */ $config['subclass_prefix'] = 'MY_'; +/* +|-------------------------------------------------------------------------- +| Composer auto-loading +|-------------------------------------------------------------------------- +| +| Enabling this setting will tell CodeIgniter to look for a Composer +| package auto-loader script in application/vendor/autoload.php. +| +| $config['composer_autoload'] = TRUE; +| +| Or if you have your vendor/ directory located somewhere else, you +| can opt to set a specific path as well: +| +| $config['composer_autoload'] = '/path/to/vendor/autoload.php'; +| +| For more information about Composer, please visit http://getcomposer.org/ +| +| Note: This will NOT disable or override the CodeIgniter-specific +| autoloading (application/config/autoload.php) +*/ +$config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- @@ -149,11 +170,25 @@ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; | use segment based URLs. | */ -$config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; -$config['directory_trigger'] = 'd'; // experimental not currently in use +$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; + /* |-------------------------------------------------------------------------- @@ -188,6 +223,33 @@ $config['log_threshold'] = 1; */ $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 @@ -199,6 +261,17 @@ $config['log_path'] = ''; */ $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 @@ -210,6 +283,24 @@ $config['log_date_format'] = 'Y-m-d H:i:s'; */ $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 @@ -226,21 +317,59 @@ $config['encryption_key'] = "xLx45kOkywjdvvVMxLov"; | Session Variables |-------------------------------------------------------------------------- | -| 'session_cookie_name' = the name you want for the cookie -| 'encrypt_sess_cookie' = TRUE/FALSE (boolean). Whether to encrypt the cookie -| 'session_expiration' = the number of SECONDS you want the session to last. -| by default sessions last 7200 seconds (two hours). Set to zero for no expiration. -| 'time_to_update' = how many seconds between CI refreshing Session Information +| '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_cookie_name'] = 'sess'; -$config['sess_expiration'] = 43200; //12 hours -$config['sess_encrypt_cookie'] = FALSE; -$config['sess_use_database'] = TRUE; -$config['sess_table_name'] = 'ci_sessions'; -$config['sess_match_ip'] = TRUE; -$config['sess_match_useragent'] = TRUE; -$config['sess_time_to_update'] = 300; +$config['sess_driver'] = 'database'; +$config['sess_cookie_name'] = 'sess'; +$config['sess_expiration'] = 43200; //12 hours +$config['sess_save_path'] = 'ci_sessions'; +$config['sess_match_ip'] = FALSE; +$config['sess_time_to_update'] = 300; +$config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- @@ -280,11 +409,15 @@ $config['global_xss_filtering'] = FALSE; | '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'] = TRUE; +$config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_token'; $config['csrf_cookie_name'] = 'csrf_cookie'; $config['csrf_expire'] = 7200; +$config['csrf_regenerate'] = TRUE; +$config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- @@ -296,13 +429,17 @@ $config['csrf_expire'] = 7200; | 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. +| by the output class. Do not 'echo' any values with compression enabled. | */ + $config['compress_output'] = TRUE; /* diff --git a/application/config/database.php b/application/config/database.php index 94f989d..249ce81 100755 --- a/application/config/database.php +++ b/application/config/database.php @@ -1,41 +1,79 @@ -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 mysql there is only one group (the "mysql" group). +| make active. By default there is only one group (the 'default' group). | -| The $active_record variables lets you determine whether or not to load -| the active record class +| The $query_builder variables lets you determine whether or not to load +| the query builder class. */ + $active_group = "todo"; -$active_record = TRUE; +$query_builder = TRUE; $db = [ 'todo' => [ @@ -45,7 +83,7 @@ $db = [ 'database' => 'todo', 'dbdriver' => 'postgre', 'dbprefix' => 'todo_', - 'pconnect' => TRUE, + 'pconnect' => FALSE, 'db_debug' => TRUE, 'cache_on' => FALSE, 'cachedir' => '', @@ -53,7 +91,8 @@ $db = [ 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'autoinit' => TRUE, - 'stricton' => FALSE + 'stricton' => TRUE, + 'save_queries' => TRUE, ], ]; diff --git a/application/controllers/account.php b/application/controllers/Account.php similarity index 100% rename from application/controllers/account.php rename to application/controllers/Account.php diff --git a/application/controllers/calendar.php b/application/controllers/Calendar.php similarity index 100% rename from application/controllers/calendar.php rename to application/controllers/Calendar.php diff --git a/application/controllers/category.php b/application/controllers/Category.php similarity index 100% rename from application/controllers/category.php rename to application/controllers/Category.php diff --git a/application/controllers/friend.php b/application/controllers/Friend.php similarity index 100% rename from application/controllers/friend.php rename to application/controllers/Friend.php diff --git a/application/controllers/group.php b/application/controllers/Group.php similarity index 100% rename from application/controllers/group.php rename to application/controllers/Group.php diff --git a/application/controllers/login.php b/application/controllers/Login.php similarity index 100% rename from application/controllers/login.php rename to application/controllers/Login.php diff --git a/application/controllers/reminder.php b/application/controllers/Reminder.php similarity index 100% rename from application/controllers/reminder.php rename to application/controllers/Reminder.php diff --git a/application/controllers/task.php b/application/controllers/Task.php similarity index 100% rename from application/controllers/task.php rename to application/controllers/Task.php diff --git a/application/models/friend_model.php b/application/models/Friend_model.php similarity index 100% rename from application/models/friend_model.php rename to application/models/Friend_model.php diff --git a/application/models/mail_model.php b/application/models/Mail_model.php similarity index 100% rename from application/models/mail_model.php rename to application/models/Mail_model.php diff --git a/application/models/task_model.php b/application/models/Task_model.php similarity index 100% rename from application/models/task_model.php rename to application/models/Task_model.php diff --git a/application/views/errors/html/error_404.php b/application/views/errors/html/error_404.php new file mode 100644 index 0000000..756ea9d --- /dev/null +++ b/application/views/errors/html/error_404.php @@ -0,0 +1,64 @@ + + + + +404 Page Not Found + + + +
+

+ +
+ + \ 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 0000000..f5a43f6 --- /dev/null +++ b/application/views/errors/html/error_db.php @@ -0,0 +1,64 @@ + + + + +Database Error + + + +
+

+ +
+ + \ 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 0000000..8784886 --- /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 0000000..fc3b2eb --- /dev/null +++ b/application/views/errors/html/error_general.php @@ -0,0 +1,64 @@ + + + + +Error + + + +
+

+ +
+ + \ 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 0000000..b146f9c --- /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/login/login.php b/application/views/login/login.php index 3ebf1b0..c1b925a 100755 --- a/application/views/login/login.php +++ b/application/views/login/login.php @@ -18,7 +18,7 @@

If it sounds interesting, or useful, sign up and try it out.

Want to try it without creating an account? Login with username: guest and password: guest

-

It's nice to have feedback. Send suggestions/comments/criticism to tim (at) timshomepage.net or @timw4mail on Twitter.

+

It's nice to have feedback. Send suggestions/comments/criticism to tim (at) timshomepage.net.

diff --git a/application/views/task/list.php b/application/views/task/list.php index 0dd5fd1..07e57b2 100755 --- a/application/views/task/list.php +++ b/application/views/task/list.php @@ -46,7 +46,7 @@ pagination->create_links(); ?>
- +

Tasks

You currently have no tasks.

diff --git a/composer.json b/composer.json index f6c07c9..4f250e6 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ "role": "Developer" }], "require": { - "php": ">=5.4", + "php": ">=7.0", "robmorgan/phinx": "*", "ircmaxell/password-compat": "1.0.*" } diff --git a/migrations/20190220154203_recreate_session_db_table.php b/migrations/20190220154203_recreate_session_db_table.php new file mode 100644 index 0000000..579e69f --- /dev/null +++ b/migrations/20190220154203_recreate_session_db_table.php @@ -0,0 +1,49 @@ +hasTable('todo_ci_sessions')) + { + $this->table('todo_ci_sessions')->drop(); + + $this->table('todo_ci_sessions', [ + 'id' => FALSE, + 'primary_key' => 'id' + ])->addColumn('id' , 'string', ['limit' => 128, 'null' => FALSE]) + ->addColumn('ip_address', 'string', ['limit' => 45, 'null' => FALSE]) + ->addColumn('timestamp', 'integer', ['default' => 0, 'null' => FALSE]) + ->addColumn('data', 'text', ['default' => '', 'null' => FALSE]) + ->create(); + } + } + + + /** + * Migrate Up. + */ + public function up() + { + + } + + /** + * Migrate Down. + */ + public function down() + { + + } +} \ No newline at end of file diff --git a/phinx.yml b/phinx.yml new file mode 100644 index 0000000..b12e960 --- /dev/null +++ b/phinx.yml @@ -0,0 +1,33 @@ +paths: + migrations: %%PHINX_CONFIG_DIR%%/migrations + +environments: + default_migration_table: phinxlog + default_database: development + + development: + adapter: pgsql + host: localhost + name: todo + user: todo + pass: todo + port: 5432 + charset: utf8 + + testing: + adapter: pgsql + host: localhost + name: todo_test + user: todo_test + pass: test + port: 5432 + charset: utf8 + + node: + adapter: mysql + host: localhost + name: node + user: node + pass: node + port: 3306 + charset: utf8 diff --git a/system/.htaccess b/system/.htaccess old mode 100755 new mode 100644 index 14249c5..97c65d2 --- a/system/.htaccess +++ b/system/.htaccess @@ -1 +1,6 @@ -Deny from all \ No newline at end of file + + Require all denied + + + Deny from all + \ No newline at end of file diff --git a/system/core/Benchmark.php b/system/core/Benchmark.php old mode 100755 new mode 100644 index a5c3e99..014220a --- a/system/core/Benchmark.php +++ b/system/core/Benchmark.php @@ -1,61 +1,82 @@ -marker[$name] = microtime(); + $this->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 @@ -63,15 +84,17 @@ class CI_Benchmark { * execution time to be shown in a template. The output class will * swap the real value for this variable. * - * @access public - * @param string a particular marked point - * @param string a particular marked point - * @param integer the number of decimal places - * @return mixed + * @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. */ - function elapsed_time($point1 = '', $point2 = '', $decimals = 4) + public function elapsed_time($point1 = '', $point2 = '', $decimals = 4) { - if ($point1 == '') + if ($point1 === '') { return '{elapsed_time}'; } @@ -83,13 +106,10 @@ class CI_Benchmark { if ( ! isset($this->marker[$point2])) { - $this->marker[$point2] = microtime(); + $this->marker[$point2] = microtime(TRUE); } - list($sm, $ss) = explode(' ', $this->marker[$point1]); - list($em, $es) = explode(' ', $this->marker[$point2]); - - return number_format(($em + $es) - ($sm + $ss), $decimals); + return number_format($this->marker[$point2] - $this->marker[$point1], $decimals); } // -------------------------------------------------------------------- @@ -97,22 +117,17 @@ class CI_Benchmark { /** * Memory Usage * - * This function returns the {memory_usage} pseudo-variable. + * 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. * - * @access public - * @return string + * @return string '{memory_usage}' */ - function memory_usage() + public function memory_usage() { return '{memory_usage}'; } } - -// END CI_Benchmark class - -/* End of file Benchmark.php */ -/* Location: ./system/core/Benchmark.php */ \ No newline at end of file diff --git a/system/core/CodeIgniter.php b/system/core/CodeIgniter.php old mode 100755 new mode 100644 index 3407817..56826f1 --- a/system/core/CodeIgniter.php +++ b/system/core/CodeIgniter.php @@ -1,19 +1,41 @@ - '_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('_exception_handler'); - - if ( ! is_php('5.3')) - { - @set_magic_quotes_runtime(0); // Kill magic quotes - } + set_error_handler('_error_handler'); + set_exception_handler('_exception_handler'); + register_shutdown_function('_shutdown_handler'); /* * ------------------------------------------------------ @@ -85,26 +148,39 @@ * 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 - * overriden via data set in the main index. php file, + * 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, + * 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 (isset($assign_to_config['subclass_prefix']) AND $assign_to_config['subclass_prefix'] != '') + if ( ! empty($assign_to_config['subclass_prefix'])) { get_config(array('subclass_prefix' => $assign_to_config['subclass_prefix'])); } /* * ------------------------------------------------------ - * Set a liberal script execution time limit + * Should we use a Composer autoloader? * ------------------------------------------------------ */ - if (function_exists("set_time_limit") == TRUE AND @ini_get("safe_mode") == 0) + if ($composer_autoload = config_item('composer_autoload')) { - @set_time_limit(300); + 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); + } } /* @@ -128,33 +204,96 @@ * Is there a "pre_system" hook? * ------------------------------------------------------ */ - $EXT->_call_hook('pre_system'); + $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)) + if (isset($assign_to_config) && is_array($assign_to_config)) { - $CFG->_assign_to_config($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 * ------------------------------------------------------ - * - * Note: Order here is rather important as the UTF-8 - * class needs to be used very early on, but it cannot - * properly determine if UTf-8 can be supported until - * after the Config class is instantiated. - * */ - $UNI =& load_class('Utf8', 'core'); /* @@ -169,14 +308,7 @@ * Instantiate the routing class and set the routing * ------------------------------------------------------ */ - $RTR =& load_class('Router', 'core'); - $RTR->_set_routing(); - - // Set any routing overrides that may exist in the main index file - if (isset($routing)) - { - $RTR->_set_overrides($routing); - } + $RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL); /* * ------------------------------------------------------ @@ -187,15 +319,12 @@ /* * ------------------------------------------------------ - * Is there a valid cache file? If so, we're done... + * Is there a valid cache file? If so, we're done... * ------------------------------------------------------ */ - if ($EXT->_call_hook('cache_override') === FALSE) + if ($EXT->call_hook('cache_override') === FALSE && $OUT->_display_cache($CFG, $URI) === TRUE) { - if ($OUT->_display_cache($CFG, $URI) == TRUE) - { - exit; - } + exit; } /* @@ -226,76 +355,157 @@ * */ // Load the base controller class - require BASEPATH.'core/Controller.php'; + 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 APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; + require_once APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; } - // Load the local application controller - // Note: The Router class automatically validates the controller path using the router->_validate_request(). - // If this include fails it means that the default controller in the Routes.php file is not resolving to something valid. - if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().'.php')) - { - show_error('Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.'); - } - - include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->fetch_class().'.php'); - // Set a mark point for benchmarking $BM->mark('loading_time:_base_classes_end'); /* * ------------------------------------------------------ - * Security check + * Sanity checks * ------------------------------------------------------ * - * None of the functions in the app controller or the - * loader class can be called via the URI, nor can - * controller functions that begin with an underscore + * 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. */ - $class = $RTR->fetch_class(); - $method = $RTR->fetch_method(); - if ( ! class_exists($class) - OR strncmp($method, '_', 1) == 0 - OR in_array(strtolower($method), array_map('strtolower', get_class_methods('CI_Controller'))) - ) + $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'])) { - $x = explode('/', $RTR->routes['404_override']); - $class = $x[0]; - $method = (isset($x[1]) ? $x[1] : 'index'); - if ( ! class_exists($class)) + if (sscanf($RTR->routes['404_override'], '%[^/]/%s', $error_class, $error_method) !== 2) { - if ( ! file_exists(APPPATH.'controllers/'.$class.'.php')) - { - show_404("{$class}/{$method}"); - } - - include_once(APPPATH.'controllers/'.$class.'.php'); + $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("{$class}/{$method}"); + 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'); + $EXT->call_hook('pre_controller'); /* * ------------------------------------------------------ @@ -312,53 +522,14 @@ * Is there a "post_controller_constructor" hook? * ------------------------------------------------------ */ - $EXT->_call_hook('post_controller_constructor'); + $EXT->call_hook('post_controller_constructor'); /* * ------------------------------------------------------ * Call the requested method * ------------------------------------------------------ */ - // Is there a "remap" function? If so, we call it instead - if (method_exists($CI, '_remap')) - { - $CI->_remap($method, array_slice($URI->rsegments, 2)); - } - else - { - // is_callable() returns TRUE on some versions of PHP 5 for private and protected - // methods, so we'll use this workaround for consistent behavior - if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI)))) - { - // Check and see if we are using a 404 override and use it. - if ( ! empty($RTR->routes['404_override'])) - { - $x = explode('/', $RTR->routes['404_override']); - $class = $x[0]; - $method = (isset($x[1]) ? $x[1] : 'index'); - if ( ! class_exists($class)) - { - if ( ! file_exists(APPPATH.'controllers/'.$class.'.php')) - { - show_404("{$class}/{$method}"); - } - - include_once(APPPATH.'controllers/'.$class.'.php'); - unset($CI); - $CI = new $class(); - } - } - else - { - show_404("{$class}/{$method}"); - } - } - - // Call the requested method. - // Any URI segments present (besides the class/function) will be passed to the method for convenience - call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2)); - } - + call_user_func_array(array(&$CI, $method), $params); // Mark a benchmark end point $BM->mark('controller_execution_time_( '.$class.' / '.$method.' )_end'); @@ -368,14 +539,14 @@ * Is there a "post_controller" hook? * ------------------------------------------------------ */ - $EXT->_call_hook('post_controller'); + $EXT->call_hook('post_controller'); /* * ------------------------------------------------------ * Send the final rendered output to the browser * ------------------------------------------------------ */ - if ($EXT->_call_hook('display_override') === FALSE) + if ($EXT->call_hook('display_override') === FALSE) { $OUT->_display(); } @@ -385,18 +556,4 @@ * Is there a "post_system" hook? * ------------------------------------------------------ */ - $EXT->_call_hook('post_system'); - -/* - * ------------------------------------------------------ - * Close the DB connection if one exists - * ------------------------------------------------------ - */ - if (class_exists('CI_DB') AND isset($CI->db)) - { - $CI->db->close(); - } - - -/* End of file CodeIgniter.php */ -/* Location: ./system/core/CodeIgniter.php */ \ No newline at end of file + $EXT->call_hook('post_system'); diff --git a/system/core/Common.php b/system/core/Common.php old mode 100755 new mode 100644 index 751a85d..624b5a9 --- a/system/core/Common.php +++ b/system/core/Common.php @@ -1,19 +1,41 @@ - 5 -* we'll set a static variable. -* -* @access public -* @param string -* @return bool TRUE if the current version is $version or higher -*/ if ( ! function_exists('is_php')) { - function is_php($version = '5.0.0') + /** + * Determines if the current version of PHP is equal to or greater than the supplied value + * + * @param string + * @return bool TRUE if the current version is $version or higher + */ + function is_php($version) { static $_is_php; - $version = (string)$version; + $version = (string) $version; if ( ! isset($_is_php[$version])) { - $_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE; + $_is_php[$version] = version_compare(PHP_VERSION, $version, '>='); } return $_is_php[$version]; @@ -57,43 +75,44 @@ if ( ! function_exists('is_php')) // ------------------------------------------------------------------------ -/** - * Tests for file writability - * - * is_writable() returns TRUE on Windows servers when you really can't write to - * the file, based on the read-only attribute. is_writable() is also unreliable - * on Unix servers if safe_mode is on. - * - * @access private - * @return void - */ if ( ! function_exists('is_really_writable')) { + /** + * 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 == '/' AND @ini_get("safe_mode") == FALSE) + 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... + /* For Windows servers and safe_mode "on" installations we'll actually + * write a file then read it. Bah... + */ if (is_dir($file)) { - $file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100)); - - if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) + $file = rtrim($file, '/').'/'.md5(mt_rand()); + if (($fp = @fopen($file, 'ab')) === FALSE) { return FALSE; } fclose($fp); - @chmod($file, DIR_WRITE_MODE); + @chmod($file, 0777); @unlink($file); return TRUE; } - elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) + elseif ( ! is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) { return FALSE; } @@ -105,26 +124,25 @@ if ( ! function_exists('is_really_writable')) // ------------------------------------------------------------------------ -/** -* Class registry -* -* This function acts as a singleton. If the requested class does not -* exist it is instantiated and set to a static variable. If it has -* previously been instantiated the variable is returned. -* -* @access public -* @param string the class name being requested -* @param string the directory where the class should be found -* @param string the class name prefix -* @return object -*/ if ( ! function_exists('load_class')) { - function &load_class($class, $directory = 'libraries', $prefix = 'CI_') + /** + * 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... + // Does the class exist? If so, we're done... if (isset($_classes[$class])) { return $_classes[$class]; @@ -138,60 +156,64 @@ if ( ! function_exists('load_class')) { if (file_exists($path.$directory.'/'.$class.'.php')) { - $name = $prefix.$class; + $name = 'CI_'.$class; - if (class_exists($name) === FALSE) + if (class_exists($name, FALSE) === FALSE) { - require($path.$directory.'/'.$class.'.php'); + require_once($path.$directory.'/'.$class.'.php'); } break; } } - // Is the request a class extension? If so we load it too + // 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) + if (class_exists($name, FALSE) === FALSE) { - require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'); + 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 Excptions class - exit('Unable to locate the specified class: '.$class.'.php'); + // 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] = new $name(); + $_classes[$class] = isset($param) + ? new $name($param) + : new $name(); return $_classes[$class]; } } // -------------------------------------------------------------------- -/** -* Keeps track of which libraries have been loaded. This function is -* called by the load_class() function above -* -* @access public -* @return array -*/ if ( ! function_exists('is_loaded')) { + /** + * 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 != '') + if ($class !== '') { $_is_loaded[strtolower($class)] = $class; } @@ -202,326 +224,498 @@ if ( ! function_exists('is_loaded')) // ------------------------------------------------------------------------ -/** -* Loads the main config.php file -* -* This function lets us grab the config file even if the Config class -* hasn't been instantiated yet -* -* @access private -* @return array -*/ if ( ! function_exists('get_config')) { - function get_config($replace = array()) + /** + * 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 (isset($_config)) + if (empty($_config)) { - return $_config[0]; + // references cannot be directly assigned to static variables, so we use an array + $_config[0] =& get_config(); } - // Is the config file in the environment folder? - if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php')) - { - $file_path = APPPATH.'config/config.php'; - } - - // Fetch the config file - if ( ! file_exists($file_path)) - { - exit('The configuration file does not exist.'); - } - - require($file_path); - - // Does the $config array exist in the file? - if ( ! isset($config) OR ! is_array($config)) - { - exit('Your config file does not appear to be formatted correctly.'); - } - - // Are any values being dynamically replaced? - if (count($replace) > 0) - { - foreach ($replace as $key => $val) - { - if (isset($config[$key])) - { - $config[$key] = $val; - } - } - } - - return $_config[0] =& $config; + return isset($_config[0][$item]) ? $_config[0][$item] : NULL; } } // ------------------------------------------------------------------------ -/** -* Returns the specified config item -* -* @access public -* @return mixed -*/ -if ( ! function_exists('config_item')) +if ( ! function_exists('get_mimes')) { - function config_item($item) + /** + * Returns the MIME types array from config/mimes.php + * + * @return array + */ + function &get_mimes() { - static $_config_item = array(); + static $_mimes; - if ( ! isset($_config_item[$item])) + if (empty($_mimes)) { - $config = get_config(); + $_mimes = file_exists(APPPATH.'config/mimes.php') + ? include(APPPATH.'config/mimes.php') + : array(); - if ( ! isset($config[$item])) + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { - return FALSE; + $_mimes = array_merge($_mimes, include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')); } - $_config_item[$item] = $config[$item]; } - return $_config_item[$item]; + 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')); } } // ------------------------------------------------------------------------ -/** -* Error Handler -* -* This function lets us invoke the exception class and -* display errors using the standard error template located -* in application/errors/errors.php -* This function will send the error page directly to the -* browser and exit. -* -* @access public -* @return void -*/ if ( ! function_exists('show_error')) { + /** + * 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($exit_status); } } // ------------------------------------------------------------------------ -/** -* 404 Page Handler -* -* This function is similar to the show_error() function above -* However, instead of the standard error template it displays -* 404 errors. -* -* @access public -* @return void -*/ if ( ! function_exists('show_404')) { + /** + * 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; + exit(4); // EXIT_UNKNOWN_FILE } } // ------------------------------------------------------------------------ -/** -* Error Logging Interface -* -* We use this as a simple mechanism to access the logging -* class and send messages to be logged. -* -* @access public -* @return void -*/ if ( ! function_exists('log_message')) { - function log_message($level = 'error', $message, $php_error = FALSE) + /** + * 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 (config_item('log_threshold') == 0) + 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; } - $_log =& load_class('Log'); - $_log->write_log($level, $message, $php_error); - } -} - -// ------------------------------------------------------------------------ - -/** - * Set HTTP Status Header - * - * @access public - * @param int the status code - * @param string - * @return void - */ -if ( ! function_exists('set_status_header')) -{ - function set_status_header($code = 200, $text = '') - { - $stati = array( - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authoritative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 307 => 'Temporary Redirect', - - 400 => 'Bad Request', - 401 => 'Unauthorized', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported' - ); - - if ($code == '' OR ! is_numeric($code)) + if (empty($code) OR ! is_numeric($code)) { show_error('Status codes must be numeric', 500); } - if (isset($stati[$code]) AND $text == '') + if (empty($text)) { - $text = $stati[$code]; + 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 ($text == '') + if (strpos(PHP_SAPI, 'cgi') === 0) { - show_error('No status text available. Please check your status code number or supply your own message text.', 500); + header('Status: '.$code.' '.$text, TRUE); + return; } - $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE; - - if (substr(php_sapi_name(), 0, 3) == 'cgi') - { - header("Status: {$code} {$text}", TRUE); - } - elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') - { - header($server_protocol." {$code} {$text}", TRUE, $code); - } - else - { - header("HTTP/1.1 {$code} {$text}", TRUE, $code); - } + $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); } } // -------------------------------------------------------------------- -/** -* Exception Handler -* -* This is the custom exception handler that is declaired at the top -* of Codeigniter.php. The main reason we use this is to permit -* PHP errors to be logged in our own log files since the user may -* not have access to server logs. Since this function -* effectively intercepts PHP errors, however, we also need -* to display errors based on the current error_reporting level. -* We do that with the use of a PHP error template. -* -* @access private -* @return void -*/ -if ( ! function_exists('_exception_handler')) +if ( ! function_exists('_error_handler')) { - function _exception_handler($severity, $message, $filepath, $line) + /** + * 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) { - // We don't bother with "strict" notices since they tend to fill up - // the log file with excess information that isn't normally very helpful. - // For example, if you are running PHP 5 and you use version 4 style - // class functions (without prefixes like "public", "private", etc.) - // you'll get notices telling you that these have been deprecated. - if ($severity == E_STRICT) + $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? We'll get the current error_reporting - // level and add its bits with the severity bits to find out. - if (($severity & error_reporting()) == $severity) + // 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); } - // Should we log the error? No? We're done... - if (config_item('log_threshold') == 0) + // 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) { - return; + 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); } - $_error->log_exception($severity, $message, $filepath, $line); + 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']); + } } } // -------------------------------------------------------------------- -/** - * Remove Invisible Characters - * - * This prevents sandwiching null characters - * between ascii characters, like Java\0script. - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('remove_invisible_characters')) { + /** + * 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) - + // every control character except newline (dec 10), + // carriage return (dec 13) and horizontal tab (dec 09) if ($url_encoded) { - $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15 - $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31 + $non_displayables[] = '/%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 @@ -538,27 +732,118 @@ if ( ! function_exists('remove_invisible_characters')) // ------------------------------------------------------------------------ -/** -* Returns HTML escaped variable -* -* @access public -* @param mixed -* @return mixed -*/ if ( ! function_exists('html_escape')) { - function html_escape($var) + /** + * 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)) { - return array_map('html_escape', $var); - } - else - { - return htmlspecialchars($var, ENT_QUOTES, config_item('charset')); + 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); } } -/* End of file Common.php */ -/* Location: ./system/core/Common.php */ \ No newline at end of file +// ------------------------------------------------------------------------ + +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 old mode 100755 new mode 100644 index 5fce1c0..fc6c30f --- a/system/core/Config.php +++ b/system/core/Config.php @@ -1,78 +1,107 @@ -config = get_config(); - log_message('debug', "Config Class Initialized"); + $this->config =& get_config(); // Set the base_url automatically if none was provided - if ($this->config['base_url'] == '') + if (empty($this->config['base_url'])) { - if (isset($_SERVER['HTTP_HOST'])) + if (isset($_SERVER['SERVER_ADDR'])) { - $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; - $base_url .= '://'. $_SERVER['HTTP_HOST']; - $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); - } + 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/'; @@ -80,6 +109,8 @@ class CI_Config { $this->set_item('base_url', $base_url); } + + log_message('info', 'Config Class Initialized'); } // -------------------------------------------------------------------- @@ -87,91 +118,71 @@ class CI_Config { /** * Load Config File * - * @access public - * @param string the config file name - * @param boolean if configuration values should be loaded into their own section - * @param boolean true if errors should just return false, false if an error message should be displayed - * @return boolean if the file was loaded correctly + * @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 */ - function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) + public function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { - $file = ($file == '') ? 'config' : str_replace('.php', '', $file); - $found = FALSE; + $file = ($file === '') ? 'config' : str_replace('.php', '', $file); $loaded = FALSE; - $check_locations = defined('ENVIRONMENT') - ? array(ENVIRONMENT.'/'.$file, $file) - : array($file); - foreach ($this->_config_paths as $path) { - foreach ($check_locations as $location) + foreach (array($file, ENVIRONMENT.DIRECTORY_SEPARATOR.$file) as $location) { $file_path = $path.'config/'.$location.'.php'; - if (in_array($file_path, $this->is_loaded, TRUE)) { - $loaded = TRUE; - continue 2; + return TRUE; } - if (file_exists($file_path)) + if ( ! file_exists($file_path)) { - $found = TRUE; - break; + continue; } - } - if ($found === FALSE) - { - continue; - } + include($file_path); - include($file_path); - - if ( ! isset($config) OR ! is_array($config)) - { - if ($fail_gracefully === TRUE) + if ( ! isset($config) OR ! is_array($config)) { - return FALSE; + if ($fail_gracefully === TRUE) + { + return FALSE; + } + + show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); } - show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); - } - if ($use_sections === TRUE) - { - if (isset($this->config[$file])) + if ($use_sections === TRUE) { - $this->config[$file] = array_merge($this->config[$file], $config); + $this->config[$file] = isset($this->config[$file]) + ? array_merge($this->config[$file], $config) + : $config; } else { - $this->config[$file] = $config; + $this->config = array_merge($this->config, $config); } - } - else - { - $this->config = array_merge($this->config, $config); - } - $this->is_loaded[] = $file_path; - unset($config); - - $loaded = TRUE; - log_message('debug', 'Config file loaded: '.$file_path); - break; + $this->is_loaded[] = $file_path; + $config = NULL; + $loaded = TRUE; + log_message('debug', 'Config file loaded: '.$file_path); + } } - if ($loaded === FALSE) + if ($loaded === TRUE) { - if ($fail_gracefully === TRUE) - { - return FALSE; - } - show_error('The configuration file '.$file.'.php does not exist.'); + return TRUE; + } + elseif ($fail_gracefully === TRUE) + { + return FALSE; } - return TRUE; + show_error('The configuration file '.$file.'.php does not exist.'); } // -------------------------------------------------------------------- @@ -179,59 +190,35 @@ class CI_Config { /** * Fetch a config file item * - * - * @access public - * @param string the config item name - * @param string the index name - * @param bool - * @return string + * @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 */ - function item($item, $index = '') + public function item($item, $index = '') { if ($index == '') { - if ( ! isset($this->config[$item])) - { - return FALSE; - } - - $pref = $this->config[$item]; - } - else - { - if ( ! isset($this->config[$index])) - { - return FALSE; - } - - if ( ! isset($this->config[$index][$item])) - { - return FALSE; - } - - $pref = $this->config[$index][$item]; + return isset($this->config[$item]) ? $this->config[$item] : NULL; } - return $pref; + return isset($this->config[$index], $this->config[$index][$item]) ? $this->config[$index][$item] : NULL; } // -------------------------------------------------------------------- /** - * Fetch a config file item - adds slash after item (if item is not empty) + * Fetch a config file item with slash appended (if not empty) * - * @access public - * @param string the config item name - * @param bool - * @return string + * @param string $item Config item name + * @return string|null The configuration item or NULL if the item doesn't exist */ - function slash_item($item) + public function slash_item($item) { if ( ! isset($this->config[$item])) { - return FALSE; + return NULL; } - if( trim($this->config[$item]) == '') + elseif (trim($this->config[$item]) === '') { return ''; } @@ -243,80 +230,122 @@ class CI_Config { /** * Site URL + * * Returns base_url . index_page [. uri_string] * - * @access public - * @param string the URI string + * @uses CI_Config::_uri_string() + * + * @param string|string[] $uri URI string or an array of segments + * @param string $protocol * @return string */ - function site_url($uri = '') + public function site_url($uri = '', $protocol = NULL) { - if ($uri == '') + $base_url = $this->slash_item('base_url'); + + if (isset($protocol)) { - return $this->slash_item('base_url').$this->item('index_page'); + // 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 ($this->item('enable_query_strings') == FALSE) + if (empty($uri)) { - $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix'); - return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix; + return $base_url.$this->item('index_page'); } - else + + $uri = $this->_uri_string($uri); + + if ($this->item('enable_query_strings') === FALSE) { - return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri); + $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] * - * @access public - * @param string $uri - * @return string + * @uses CI_Config::_uri_string() + * + * @param string|string[] $uri URI string or an array of segments + * @param string $protocol + * @return string */ - function base_url($uri = '') + public function base_url($uri = '', $protocol = NULL) { - return $this->slash_item('base_url').ltrim($this->_uri_string($uri), '/'); + $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 for use in Config::site_url() and Config::base_url() + * Build URI string * - * @access protected - * @param $uri - * @return 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) + if ($this->item('enable_query_strings') === FALSE) { - if (is_array($uri)) - { - $uri = implode('/', $uri); - } - $uri = trim($uri, '/'); + is_array($uri) && $uri = implode('/', $uri); + return ltrim($uri, '/'); } - else + elseif (is_array($uri)) { - if (is_array($uri)) - { - $i = 0; - $str = ''; - foreach ($uri as $key => $val) - { - $prefix = ($i == 0) ? '' : '&'; - $str .= $prefix.$key.'='.$val; - $i++; - } - $uri = $str; - } + return http_build_query($uri); } - return $uri; + + return $uri; } // -------------------------------------------------------------------- @@ -324,12 +353,12 @@ class CI_Config { /** * System URL * - * @access public + * @deprecated 3.0.0 Encourages insecure practices * @return string */ - function system_url() + public function system_url() { - $x = explode("/", preg_replace("|/*(.+?)/*$|", "\\1", BASEPATH)); + $x = explode('/', preg_replace('|/*(.+?)/*$|', '\\1', BASEPATH)); return $this->slash_item('base_url').end($x).'/'; } @@ -338,42 +367,13 @@ class CI_Config { /** * Set a config file item * - * @access public - * @param string the config item key - * @param string the config item value + * @param string $item Config item key + * @param string $value Config item value * @return void */ - function set_item($item, $value) + public function set_item($item, $value) { $this->config[$item] = $value; } - // -------------------------------------------------------------------- - - /** - * Assign to Config - * - * This function is called by the front controller (CodeIgniter.php) - * after the Config class is instantiated. It permits config items - * to be assigned or overriden by variables contained in the index.php file - * - * @access private - * @param array - * @return void - */ - function _assign_to_config($items = array()) - { - if (is_array($items)) - { - foreach ($items as $key => $val) - { - $this->set_item($key, $val); - } - } - } } - -// END CI_Config class - -/* End of file Config.php */ -/* Location: ./system/core/Config.php */ diff --git a/system/core/Controller.php b/system/core/Controller.php old mode 100755 new mode 100644 index 6ccaf97..2bb1578 --- a/system/core/Controller.php +++ b/system/core/Controller.php @@ -1,22 +1,44 @@ -load =& load_class('Loader', 'core'); - $this->load->initialize(); - - log_message('debug', "Controller Class Initialized"); + log_message('info', 'Controller Class Initialized'); } + // -------------------------------------------------------------------- + + /** + * Get the CI singleton + * + * @static + * @return object + */ public static function &get_instance() { return self::$instance; } -} -// END Controller class -/* End of file Controller.php */ -/* Location: ./system/core/Controller.php */ \ No newline at end of file +} diff --git a/system/core/Exceptions.php b/system/core/Exceptions.php old mode 100755 new mode 100644 index 4512096..90ff1ab --- a/system/core/Exceptions.php +++ b/system/core/Exceptions.php @@ -1,19 +1,41 @@ - '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' - ); - + public $levels = array( + E_ERROR => 'Error', + E_WARNING => 'Warning', + E_PARSE => 'Parsing Error', + E_NOTICE => 'Notice', + E_CORE_ERROR => 'Core Error', + E_CORE_WARNING => 'Core Warning', + E_COMPILE_ERROR => 'Compile Error', + E_COMPILE_WARNING => 'Compile Warning', + E_USER_ERROR => 'User Error', + E_USER_WARNING => 'User Warning', + E_USER_NOTICE => 'User Notice', + E_STRICT => 'Runtime Notice' + ); /** - * Constructor + * Class constructor + * + * @return void */ public function __construct() { $this->ob_level = ob_get_level(); - // Note: Do not log messages from this constructor. + // Note: Do not log messages from this constructor. } // -------------------------------------------------------------------- @@ -75,45 +91,52 @@ class CI_Exceptions { /** * Exception Logger * - * This function logs PHP generated error messages + * Logs PHP generated error messages * - * @access private - * @param string the error severity - * @param string the error string - * @param string the error filepath - * @param string the error line number - * @return string + * @param int $severity Log level + * @param string $message Error message + * @param string $filepath File path + * @param int $line Line number + * @return void */ - function log_exception($severity, $message, $filepath, $line) + public function log_exception($severity, $message, $filepath, $line) { - $severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity]; - - log_message('error', 'Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line, TRUE); + $severity = isset($this->levels[$severity]) ? $this->levels[$severity] : $severity; + log_message('error', 'Severity: '.$severity.' --> '.$message.' '.$filepath.' '.$line); } // -------------------------------------------------------------------- /** - * 404 Page Not Found Handler + * 404 Error Handler * - * @access private - * @param string the page - * @param bool log error yes/no - * @return string + * @uses CI_Exceptions::show_error() + * + * @param string $page Page URI + * @param bool $log_error Whether to log the error + * @return void */ - function show_404($page = '', $log_error = TRUE) + public function show_404($page = '', $log_error = TRUE) { - $heading = "404 Page Not Found"; - $message = "The page you requested was not found."; + 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', '404 Page Not Found --> '.$page); + log_message('error', $heading.': '.$page); } echo $this->show_error($heading, $message, 'error_404', 404); - exit; + exit(4); // EXIT_UNKNOWN_FILE } // -------------------------------------------------------------------- @@ -121,29 +144,42 @@ class CI_Exceptions { /** * General Error Page * - * This function takes an error message as input - * (either as a string or an array) and displays - * it using the specified template. + * Takes an error message as input (either as a string or an array) + * and displays it using the specified template. * - * @access private - * @param string the heading - * @param string the message - * @param string the template name - * @param int the status code - * @return string + * @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 */ - function show_error($heading, $message, $template = 'error_general', $status_code = 500) + public function show_error($heading, $message, $template = 'error_general', $status_code = 500) { - set_status_header($status_code); + $templates_path = config_item('error_views_path'); + if (empty($templates_path)) + { + $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR; + } - $message = '

'.implode('

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

'; + 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(APPPATH.'errors/'.$template.'.php'); + include($templates_path.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); return $buffer; @@ -151,27 +187,77 @@ class CI_Exceptions { // -------------------------------------------------------------------- + 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 * - * @access private - * @param string the error severity - * @param string the error string - * @param string the error filepath - * @param string the error line number - * @return string + * @param int $severity Error level + * @param string $message Error message + * @param string $filepath File path + * @param int $line Line number + * @return void */ - function show_php_error($severity, $message, $filepath, $line) + public function show_php_error($severity, $message, $filepath, $line) { - $severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity]; - - $filepath = str_replace("\\", "/", $filepath); - - // For safety reasons we do not show the full file path - if (FALSE !== strpos($filepath, '/')) + $templates_path = config_item('error_views_path'); + if (empty($templates_path)) { - $x = explode('/', $filepath); - $filepath = $x[count($x)-2].'/'.end($x); + $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) @@ -179,15 +265,10 @@ class CI_Exceptions { ob_end_flush(); } ob_start(); - include(APPPATH.'errors/error_php.php'); + include($templates_path.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); echo $buffer; } - } -// END Exceptions Class - -/* End of file Exceptions.php */ -/* Location: ./system/core/Exceptions.php */ \ No newline at end of file diff --git a/system/core/Hooks.php b/system/core/Hooks.php old mode 100755 new mode 100644 index ee5c230..6236dd4 --- a/system/core/Hooks.php +++ b/system/core/Hooks.php @@ -1,95 +1,114 @@ -_initialize(); - log_message('debug', "Hooks Class Initialized"); - } - - // -------------------------------------------------------------------- - - /** - * Initialize the Hooks Preferences - * - * @access private * @return void */ - function _initialize() + public function __construct() { $CFG =& load_class('Config', 'core'); + log_message('info', 'Hooks Class Initialized'); // If hooks are not enabled in the config file // there is nothing else to do - - if ($CFG->item('enable_hooks') == FALSE) + if ($CFG->item('enable_hooks') === FALSE) { return; } // Grab the "hooks" definition file. - // If there are no hooks, we're done. - - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/hooks.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/hooks.php'); - } - elseif (is_file(APPPATH.'config/hooks.php')) + 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; @@ -104,20 +123,21 @@ class CI_Hooks { /** * Call Hook * - * Calls a particular hook + * Calls a particular hook. Called by CodeIgniter.php. * - * @access private - * @param string the hook name - * @return mixed + * @uses CI_Hooks::_run_hook() + * + * @param string $which Hook name + * @return bool TRUE on success or FALSE on failure */ - function _call_hook($which = '') + public function call_hook($which = '') { if ( ! $this->enabled OR ! isset($this->hooks[$which])) { return FALSE; } - if (isset($this->hooks[$which][0]) AND is_array($this->hooks[$which][0])) + if (is_array($this->hooks[$which]) && ! isset($this->hooks[$which]['function'])) { foreach ($this->hooks[$which] as $val) { @@ -139,13 +159,21 @@ class CI_Hooks { * * Runs a particular hook * - * @access private - * @param array the hook details - * @return bool + * @param array $data Hook details + * @return bool TRUE on success or FALSE on failure */ - function _run_hook($data) + protected function _run_hook($data) { - if ( ! is_array($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; } @@ -156,8 +184,7 @@ class CI_Hooks { // If the script being called happens to have the same // hook call within it a loop can happen - - if ($this->in_progress == TRUE) + if ($this->_in_progress === TRUE) { return; } @@ -166,7 +193,7 @@ class CI_Hooks { // Set file path // ----------------------------------- - if ( ! isset($data['filepath']) OR ! isset($data['filename'])) + if ( ! isset($data['filepath'], $data['filename'])) { return FALSE; } @@ -178,71 +205,62 @@ class CI_Hooks { return FALSE; } - // ----------------------------------- - // Set class/function name - // ----------------------------------- + // 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'] : ''; - $class = FALSE; - $function = FALSE; - $params = ''; - - if (isset($data['class']) AND $data['class'] != '') - { - $class = $data['class']; - } - - if (isset($data['function'])) - { - $function = $data['function']; - } - - if (isset($data['params'])) - { - $params = $data['params']; - } - - if ($class === FALSE AND $function === FALSE) + if (empty($function)) { return FALSE; } - // ----------------------------------- - // Set the in_progress flag - // ----------------------------------- + // Set the _in_progress flag + $this->_in_progress = TRUE; - $this->in_progress = TRUE; - - // ----------------------------------- // Call the requested class and/or function - // ----------------------------------- - if ($class !== FALSE) { - if ( ! class_exists($class)) + // The object is stored? + if (isset($this->_objects[$class])) { - require($filepath); + 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); - $HOOK = new $class; - $HOOK->$function($params); + 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)) { - require($filepath); + return $this->_in_progress = FALSE; } $function($params); } - $this->in_progress = FALSE; + $this->_in_progress = FALSE; return TRUE; } } - -// END CI_Hooks class - -/* End of file Hooks.php */ -/* Location: ./system/core/Hooks.php */ \ No newline at end of file diff --git a/system/core/Input.php b/system/core/Input.php old mode 100755 new mode 100644 index 88afa8c..30b31d0 --- a/system/core/Input.php +++ b/system/core/Input.php @@ -1,19 +1,41 @@ -_allow_get_array = (config_item('allow_get_array') === TRUE); + $this->_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'); - global $SEC; - $this->security =& $SEC; + $this->security =& load_class('Security', 'core'); // Do we need the UTF-8 class? if (UTF8_ENABLED === TRUE) { - global $UNI; - $this->uni =& $UNI; + $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'); } // -------------------------------------------------------------------- @@ -108,147 +167,204 @@ class CI_Input { /** * Fetch from array * - * This is a helper function to retrieve values from global arrays + * Internal method used to retrieve values from global arrays. * - * @access private - * @param array - * @param string - * @param bool - * @return string + * @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 */ - function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE) + protected function _fetch_from_array(&$array, $index = NULL, $xss_clean = NULL) { - if ( ! isset($array[$index])) + 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)) { - return FALSE; + $output = array(); + foreach ($index as $key) + { + $output[$key] = $this->_fetch_from_array($array, $key, $xss_clean); + } + + return $output; } - if ($xss_clean === TRUE) + if (isset($array[$index])) { - return $this->security->xss_clean($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 $array[$index]; + return ($xss_clean === TRUE) + ? $this->security->xss_clean($value) + : $value; } // -------------------------------------------------------------------- /** - * Fetch an item from the GET array - * - * @access public - * @param string - * @param bool - * @return string - */ - function get($index = NULL, $xss_clean = FALSE) + * 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) { - // Check if a field has been provided - if ($index === NULL AND ! empty($_GET)) - { - $get = array(); - - // loop through the full _GET array - foreach (array_keys($_GET) as $key) - { - $get[$key] = $this->_fetch_from_array($_GET, $key, $xss_clean); - } - return $get; - } - return $this->_fetch_from_array($_GET, $index, $xss_clean); } // -------------------------------------------------------------------- /** - * Fetch an item from the POST array - * - * @access public - * @param string - * @param bool - * @return string - */ - function post($index = NULL, $xss_clean = FALSE) + * 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) { - // Check if a field has been provided - if ($index === NULL AND ! empty($_POST)) - { - $post = array(); - - // Loop through the full _POST array and return it - foreach (array_keys($_POST) as $key) - { - $post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean); - } - return $post; - } - return $this->_fetch_from_array($_POST, $index, $xss_clean); } - // -------------------------------------------------------------------- /** - * Fetch an item from either the GET array or the POST - * - * @access public - * @param string The index key - * @param bool XSS cleaning - * @return string - */ - function get_post($index = '', $xss_clean = FALSE) + * 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) { - if ( ! isset($_POST[$index]) ) - { - return $this->get($index, $xss_clean); - } - else - { - return $this->post($index, $xss_clean); - } + return isset($_POST[$index]) + ? $this->post($index, $xss_clean) + : $this->get($index, $xss_clean); } // -------------------------------------------------------------------- /** - * Fetch an item from the COOKIE array - * - * @access public - * @param string - * @param bool - * @return string - */ - function cookie($index = '', $xss_clean = FALSE) + * 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); + } + // ------------------------------------------------------------------------ /** - * Set cookie - * - * Accepts six parameter, or you can submit an associative - * array in the first parameter containing all the values. - * - * @access public - * @param mixed - * @param string the value of the cookie - * @param string the number of seconds until expiration - * @param string the cookie domain. Usually: .yourdomain.com - * @param string the cookie path - * @param string the cookie prefix - * @param bool true makes the cookie secure - * @return void - */ - function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE) + * 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', 'name') as $item) + foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') as $item) { if (isset($name[$item])) { @@ -257,22 +373,28 @@ class CI_Input { } } - if ($prefix == '' AND config_item('cookie_prefix') != '') + if ($prefix === '' && config_item('cookie_prefix') !== '') { $prefix = config_item('cookie_prefix'); } - if ($domain == '' AND config_item('cookie_domain') != '') + + if ($domain == '' && config_item('cookie_domain') != '') { $domain = config_item('cookie_domain'); } - if ($path == '/' AND config_item('cookie_path') != '/') + + if ($path === '/' && config_item('cookie_path') !== '/') { $path = config_item('cookie_path'); } - if ($secure == FALSE AND config_item('cookie_secure') != FALSE) - { - $secure = config_item('cookie_secure'); - } + + $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)) { @@ -283,31 +405,18 @@ class CI_Input { $expire = ($expire > 0) ? time() + $expire : 0; } - setcookie($prefix.$name, $value, $expire, $path, $domain, $secure); + setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); } // -------------------------------------------------------------------- /** - * Fetch an item from the SERVER array - * - * @access public - * @param string - * @param bool - * @return string - */ - function server($index = '', $xss_clean = FALSE) - { - return $this->_fetch_from_array($_SERVER, $index, $xss_clean); - } - - // -------------------------------------------------------------------- - - /** - * Fetch the IP Address - * - * @return string - */ + * 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) @@ -316,25 +425,27 @@ class CI_Input { } $proxy_ips = config_item('proxy_ips'); - if ( ! empty($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)) !== FALSE) + 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. - if (strpos($spoof, ',') !== FALSE) - { - $spoof = explode(',', $spoof, 2); - $spoof = $spoof[0]; - } + sscanf($spoof, '%[^,]', $spoof); if ( ! $this->valid_ip($spoof)) { - $spoof = FALSE; + $spoof = NULL; } else { @@ -343,17 +454,92 @@ class CI_Input { } } - $this->ip_address = ($spoof !== FALSE && in_array($_SERVER['REMOTE_ADDR'], $proxy_ips, TRUE)) - ? $spoof : $_SERVER['REMOTE_ADDR']; - } - else - { - $this->ip_address = $_SERVER['REMOTE_ADDR']; + if ($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)) { - $this->ip_address = '0.0.0.0'; + return $this->ip_address = '0.0.0.0'; } return $this->ip_address; @@ -362,256 +548,72 @@ class CI_Input { // -------------------------------------------------------------------- /** - * Validate IP Address - * - * @access public - * @param string - * @param string ipv4 or ipv6 - * @return bool - */ + * Validate IP Address + * + * @param string $ip IP address + * @param string $which IP protocol: 'ipv4' or 'ipv6' + * @return bool + */ public function valid_ip($ip, $which = '') { - $which = strtolower($which); - - // First check if filter_var is available - if (is_callable('filter_var')) + switch (strtolower($which)) { - switch ($which) { - case 'ipv4': - $flag = FILTER_FLAG_IPV4; - break; - case 'ipv6': - $flag = FILTER_FLAG_IPV6; - break; - default: - $flag = ''; - break; - } - - return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flag); + case 'ipv4': + $which = FILTER_FLAG_IPV4; + break; + case 'ipv6': + $which = FILTER_FLAG_IPV6; + break; + default: + $which = NULL; + break; } - if ($which !== 'ipv6' && $which !== 'ipv4') - { - if (strpos($ip, ':') !== FALSE) - { - $which = 'ipv6'; - } - elseif (strpos($ip, '.') !== FALSE) - { - $which = 'ipv4'; - } - else - { - return FALSE; - } - } - - $func = '_valid_'.$which; - return $this->$func($ip); + return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which); } // -------------------------------------------------------------------- /** - * Validate IPv4 Address - * - * Updated version suggested by Geert De Deckere - * - * @access protected - * @param string - * @return bool - */ - protected function _valid_ipv4($ip) + * Fetch User Agent string + * + * @return string|null User Agent string or NULL if it doesn't exist + */ + public function user_agent($xss_clean = NULL) { - $ip_segments = explode('.', $ip); - - // Always 4 segments needed - if (count($ip_segments) !== 4) - { - return FALSE; - } - // IP can not start with 0 - if ($ip_segments[0][0] == '0') - { - return FALSE; - } - - // Check each segment - foreach ($ip_segments as $segment) - { - // IP segments must be digits and can not be - // longer than 3 digits or greater then 255 - if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3) - { - return FALSE; - } - } - - return TRUE; + return $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean); } // -------------------------------------------------------------------- /** - * Validate IPv6 Address - * - * @access protected - * @param string - * @return bool - */ - protected function _valid_ipv6($str) + * 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() { - // 8 groups, separated by : - // 0-ffff per group - // one set of consecutive 0 groups can be collapsed to :: - - $groups = 8; - $collapsed = FALSE; - - $chunks = array_filter( - preg_split('/(:{1,2})/', $str, NULL, PREG_SPLIT_DELIM_CAPTURE) - ); - - // Rule out easy nonsense - if (current($chunks) == ':' OR end($chunks) == ':') - { - return FALSE; - } - - // PHP supports IPv4-mapped IPv6 addresses, so we'll expect those as well - if (strpos(end($chunks), '.') !== FALSE) - { - $ipv4 = array_pop($chunks); - - if ( ! $this->_valid_ipv4($ipv4)) - { - return FALSE; - } - - $groups--; - } - - while ($seg = array_pop($chunks)) - { - if ($seg[0] == ':') - { - if (--$groups == 0) - { - return FALSE; // too many groups - } - - if (strlen($seg) > 2) - { - return FALSE; // long separator - } - - if ($seg == '::') - { - if ($collapsed) - { - return FALSE; // multiple collapsed - } - - $collapsed = TRUE; - } - } - elseif (preg_match("/[^0-9a-f]/i", $seg) OR strlen($seg) > 4) - { - return FALSE; // invalid segment - } - } - - return $collapsed OR $groups == 1; - } - - // -------------------------------------------------------------------- - - /** - * User Agent - * - * @access public - * @return string - */ - function user_agent() - { - if ($this->user_agent !== FALSE) - { - return $this->user_agent; - } - - $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT']; - - return $this->user_agent; - } - - // -------------------------------------------------------------------- - - /** - * Sanitize Globals - * - * This function does the following: - * - * Unsets $_GET data (if query strings are not enabled) - * - * Unsets all globals if register_globals is enabled - * - * Standardizes newline characters to \n - * - * @access private - * @return void - */ - function _sanitize_globals() - { - // It would be "wrong" to unset any of these GLOBALS. - $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST', - '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA', - 'system_folder', 'application_folder', 'BM', 'EXT', - 'CFG', 'URI', 'RTR', 'OUT', 'IN'); - - // Unset globals for securiy. - // This is effectively the same as register_globals = off - foreach (array($_GET, $_POST, $_COOKIE) as $global) - { - if ( ! is_array($global)) - { - if ( ! in_array($global, $protected)) - { - global $$global; - $$global = NULL; - } - } - else - { - foreach ($global as $key => $val) - { - if ( ! in_array($key, $protected)) - { - global $$key; - $$key = NULL; - } - } - } - } - // Is $_GET data allowed? If not we'll set the $_GET to an empty array - if ($this->_allow_get_array == FALSE) + if ($this->_allow_get_array === FALSE) { $_GET = array(); } - else + elseif (is_array($_GET)) { - if (is_array($_GET) AND count($_GET) > 0) + foreach ($_GET as $key => $val) { - foreach ($_GET as $key => $val) - { - $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); - } + $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Clean $_POST Data - if (is_array($_POST) AND count($_POST) > 0) + if (is_array($_POST)) { foreach ($_POST as $key => $val) { @@ -620,56 +622,57 @@ class CI_Input { } // Clean $_COOKIE Data - if (is_array($_COOKIE) AND count($_COOKIE) > 0) + 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']); - unset($_COOKIE['$Path']); - unset($_COOKIE['$Domain']); + unset( + $_COOKIE['$Version'], + $_COOKIE['$Path'], + $_COOKIE['$Domain'] + ); foreach ($_COOKIE as $key => $val) { - $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($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']); - - // CSRF Protection check on HTTP requests - if ($this->_enable_csrf == TRUE && ! $this->is_cli_request()) - { - $this->security->csrf_verify(); - } - - log_message('debug', "Global POST and COOKIE data sanitized"); + log_message('debug', 'Global POST, GET and COOKIE data sanitized'); } // -------------------------------------------------------------------- /** - * Clean Input Data - * - * This is a helper function. It escapes data and - * standardizes newline characters to \n - * - * @access private - * @param string - * @return string - */ - function _clean_input_data($str) + * 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 ($str as $key => $val) + foreach (array_keys($str) as $key) { - $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); + $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($str[$key]); } return $new_array; } @@ -677,7 +680,7 @@ class CI_Input { /* 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. + it will probably not exist in future versions at all. */ if ( ! is_php('5.4') && get_magic_quotes_gpc()) { @@ -691,21 +694,12 @@ class CI_Input { } // Remove control characters - $str = remove_invisible_characters($str); - - // Should we filter the input data? - if ($this->_enable_xss === TRUE) - { - $str = $this->security->xss_clean($str); - } + $str = remove_invisible_characters($str, FALSE); // Standardize newlines if needed - if ($this->_standardize_newlines == TRUE) + if ($this->_standardize_newlines === TRUE) { - if (strpos($str, "\r") !== FALSE) - { - $str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str); - } + return preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $str); } return $str; @@ -714,27 +708,38 @@ class CI_Input { // -------------------------------------------------------------------- /** - * Clean Keys - * - * This is a helper function. To prevent malicious users - * from trying to exploit keys we make sure that keys are - * only named with alpha-numeric text and a few other items. - * - * @access private - * @param string - * @return string - */ - function _clean_input_keys($str) + * 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 ( ! preg_match('/^[a-z0-9:_\/|-]+$/i', $str)) { - exit('Disallowed Key Characters.'); + 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) { - $str = $this->uni->clean_string($str); + return $this->uni->clean_string($str); } return $str; @@ -745,43 +750,40 @@ class CI_Input { /** * Request Headers * - * In Apache, you can simply call apache_request_headers(), however for - * people running other webservers the function is undefined. - * - * @param bool XSS cleaning - * - * @return array + * @param bool $xss_clean Whether to apply XSS filtering + * @return array */ public function request_headers($xss_clean = FALSE) { - // Look at Apache go! + // 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')) { - $headers = apache_request_headers(); + $this->headers = apache_request_headers(); } else { - $headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE'); + isset($_SERVER['CONTENT_TYPE']) && $this->headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; foreach ($_SERVER as $key => $val) { - if (strncmp($key, 'HTTP_', 5) === 0) + if (sscanf($key, 'HTTP_%s', $header) === 1) { - $headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean); + // take SOME_HEADER and turn it into Some-Header + $header = str_replace('_', ' ', strtolower($header)); + $header = str_replace(' ', '-', ucwords($header)); + + $this->headers[$header] = $_SERVER[$key]; } } } - // take SOME_HEADER and turn it into Some-Header - foreach ($headers as $key => $val) - { - $key = str_replace('_', ' ', strtolower($key)); - $key = str_replace(' ', '-', ucwords($key)); - - $this->headers[$key] = $val; - } - - return $this->headers; + return $this->_fetch_from_array($this->headers, NULL, $xss_clean); } // -------------------------------------------------------------------- @@ -791,59 +793,103 @@ class CI_Input { * * Returns the value of a single member of the headers class member * - * @param string array key for $this->headers - * @param boolean XSS Clean or not - * @return mixed FALSE on failure, string on success + * @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) { - if (empty($this->headers)) + static $headers; + + if ( ! isset($headers)) { - $this->request_headers(); + empty($this->headers) && $this->request_headers(); + foreach ($this->headers as $key => $value) + { + $headers[strtolower($key)] = $value; + } } - if ( ! isset($this->headers[$index])) + $index = strtolower($index); + + if ( ! isset($headers[$index])) { - return FALSE; + return NULL; } - if ($xss_clean === TRUE) - { - return $this->security->xss_clean($this->headers[$index]); - } - - return $this->headers[$index]; + return ($xss_clean === TRUE) + ? $this->security->xss_clean($headers[$index]) + : $headers[$index]; } // -------------------------------------------------------------------- /** - * Is ajax Request? + * Is AJAX request? * - * Test to see if a request contains the HTTP_X_REQUESTED_WITH header - * - * @return boolean - */ - public function is_ajax_request() - { - return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest'); - } - - // -------------------------------------------------------------------- - - /** - * Is cli Request? - * - * Test to see if a request was made from the command line + * 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 (php_sapi_name() === 'cli' OR defined('STDIN')); + 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; + } } } - -/* End of file Input.php */ -/* Location: ./system/core/Input.php */ \ No newline at end of file diff --git a/system/core/Lang.php b/system/core/Lang.php old mode 100755 new mode 100644 index dbe1b2b..2c8654d --- a/system/core/Lang.php +++ b/system/core/Lang.php @@ -1,19 +1,41 @@ -load($value, $idiom, $return, $add_suffix, $alt_path); + } + + return; + } + $langfile = str_replace('.php', '', $langfile); - if ($add_suffix == TRUE) + if ($add_suffix === TRUE) { - $langfile = str_replace('_lang.', '', $langfile).'_lang'; + $langfile = preg_replace('/_lang$/', '', $langfile).'_lang'; } $langfile .= '.php'; - if (in_array($langfile, $this->is_loaded, TRUE)) + 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; } - $config = get_config(); - - if ($idiom == '') + // Load the base file, so any others found can override it + $basepath = BASEPATH.'language/'.$idiom.'/'.$langfile; + if (($found = file_exists($basepath)) === TRUE) { - $deft_lang = ( ! isset($config['language'])) ? 'english' : $config['language']; - $idiom = ($deft_lang == '') ? 'english' : $deft_lang; + include($basepath); } - // Determine where the language file is and load it - if ($alt_path != '' && file_exists($alt_path.'language/'.$idiom.'/'.$langfile)) + // Do we have an alternative path to look in? + if ($alt_path !== '') { - include($alt_path.'language/'.$idiom.'/'.$langfile); + $alt_path .= 'language/'.$idiom.'/'.$langfile; + if (file_exists($alt_path)) + { + include($alt_path); + $found = TRUE; + } } else { - $found = FALSE; - foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) { - if (file_exists($package_path.'language/'.$idiom.'/'.$langfile)) + $package_path .= 'language/'.$idiom.'/'.$langfile; + if ($basepath !== $package_path && file_exists($package_path)) { - include($package_path.'language/'.$idiom.'/'.$langfile); + include($package_path); $found = TRUE; break; } } - - if ($found !== TRUE) - { - show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile); - } } + if ($found !== TRUE) + { + show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile); + } - if ( ! isset($lang)) + 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) + if ($return === TRUE) { return $lang; } - $this->is_loaded[] = $langfile; + $this->is_loaded[$langfile] = $idiom; $this->language = array_merge($this->language, $lang); - unset($lang); - log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile); + log_message('info', 'Language file loaded: language/'.$idiom.'/'.$langfile); return TRUE; } // -------------------------------------------------------------------- /** - * Fetch a single line of text from the language array + * Language line * - * @access public - * @param string $line the language line - * @return string + * 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 */ - function line($line = '') + public function line($line, $log_errors = TRUE) { - $value = ($line == '' OR ! isset($this->language[$line])) ? FALSE : $this->language[$line]; + $value = isset($this->language[$line]) ? $this->language[$line] : FALSE; // Because killer robots like unicorns! - if ($value === FALSE) + if ($value === FALSE && $log_errors === TRUE) { log_message('error', 'Could not find the language line "'.$line.'"'); } @@ -154,7 +201,3 @@ class CI_Lang { } } -// END Language Class - -/* End of file Lang.php */ -/* Location: ./system/core/Lang.php */ diff --git a/system/core/Loader.php b/system/core/Loader.php old mode 100755 new mode 100644 index b5b0634..14888e4 --- a/system/core/Loader.php +++ b/system/core/Loader.php @@ -1,30 +1,52 @@ - TRUE); + /** * List of paths to load libraries from * - * @var array - * @access protected + * @var array */ - protected $_ci_library_paths = array(); + protected $_ci_library_paths = array(APPPATH, BASEPATH); + /** * List of paths to load models from * - * @var array - * @access protected + * @var array */ - protected $_ci_model_paths = array(); + protected $_ci_model_paths = array(APPPATH); + /** * List of paths to load helpers from * - * @var array - * @access protected + * @var array */ - protected $_ci_helper_paths = array(); - /** - * List of loaded base classes - * Set by the controller class - * - * @var array - * @access protected - */ - protected $_base_classes = array(); // Set by the controller class + protected $_ci_helper_paths = array(APPPATH, BASEPATH); + /** * List of cached variables * - * @var array - * @access protected + * @var array */ - protected $_ci_cached_vars = array(); + protected $_ci_cached_vars = array(); + /** * List of loaded classes * - * @var array - * @access protected + * @var array */ - protected $_ci_classes = array(); - /** - * List of loaded files - * - * @var array - * @access protected - */ - protected $_ci_loaded_files = array(); + protected $_ci_classes = array(); + /** * List of loaded models * - * @var array - * @access protected + * @var array */ - protected $_ci_models = array(); + protected $_ci_models = array(); + /** * List of loaded helpers * - * @var array - * @access protected + * @var array */ - protected $_ci_helpers = array(); + protected $_ci_helpers = array(); + /** * List of class name mappings * - * @var array - * @access protected + * @var array */ - protected $_ci_varmap = array('unit_test' => 'unit', - 'user_agent' => 'agent'); + protected $_ci_varmap = array( + 'unit_test' => 'unit', + 'user_agent' => 'agent' + ); + + // -------------------------------------------------------------------- /** - * Constructor + * Class constructor * - * Sets the path to the view files and gets the initial output buffering level + * Sets component load paths, gets the initial output buffering level. + * + * @return void */ public function __construct() { - $this->_ci_ob_level = ob_get_level(); - $this->_ci_library_paths = array(APPPATH, BASEPATH); - $this->_ci_helper_paths = array(APPPATH, BASEPATH); - $this->_ci_model_paths = array(APPPATH); - $this->_ci_view_paths = array(APPPATH.'views/' => TRUE); + $this->_ci_ob_level = ob_get_level(); + $this->_ci_classes =& is_loaded(); - log_message('debug', "Loader Class Initialized"); + log_message('info', 'Loader Class Initialized'); } // -------------------------------------------------------------------- /** - * Initialize the Loader + * Initializer * - * This method is called once in CI_Controller. - * - * @param array - * @return object + * @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_classes = array(); - $this->_ci_loaded_files = array(); - $this->_ci_models = array(); - $this->_base_classes =& is_loaded(); - $this->_ci_autoloader(); - - return $this; } // -------------------------------------------------------------------- @@ -159,61 +162,61 @@ class CI_Loader { /** * Is Loaded * - * A utility function to test if a class is in the self::$_ci_classes array. - * This function returns the object name if the class tested for is loaded, - * and returns FALSE if it isn't. + * A utility method to test if a class is in the self::$_ci_classes array. * - * It is mainly used in the form_helper -> _get_validation_object() + * @used-by Mainly used by Form Helper function _get_validation_object(). * - * @param string class being checked for - * @return mixed class object name on the CI SuperObject or FALSE + * @param string $class Class name to check for + * @return string|bool Class object name if loaded or FALSE */ public function is_loaded($class) { - if (isset($this->_ci_classes[$class])) - { - return $this->_ci_classes[$class]; - } - - return FALSE; + return array_search(ucfirst($class), $this->_ci_classes, TRUE); } // -------------------------------------------------------------------- /** - * Class Loader + * Library Loader * - * This function lets users load and instantiate classes. - * It is designed to be called from a user's app controllers. + * Loads and instantiates libraries. + * Designed to be called from application controllers. * - * @param string the name of the class - * @param mixed the optional parameters - * @param string an optional object name - * @return void + * @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) + public function library($library, $params = NULL, $object_name = NULL) { - if (is_array($library)) + if (empty($library)) { - foreach ($library as $class) + return $this; + } + elseif (is_array($library)) + { + foreach ($library as $key => $value) { - $this->library($class, $params); + if (is_int($key)) + { + $this->library($value, $params); + } + else + { + $this->library($key, $params, $value); + } } - return; + return $this; } - if ($library == '' OR isset($this->_base_classes[$library])) - { - return FALSE; - } - - if ( ! is_null($params) && ! is_array($params)) + if ($params !== NULL && ! is_array($params)) { $params = NULL; } - $this->_ci_load_class($library, $params, $object_name); + $this->_ci_load_library($library, $params, $object_name); + return $this; } // -------------------------------------------------------------------- @@ -221,27 +224,27 @@ class CI_Loader { /** * Model Loader * - * This function lets users load and instantiate models. + * Loads and instantiates models. * - * @param string the name of the class - * @param string name for the model - * @param bool database connection - * @return void + * @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 (is_array($model)) + if (empty($model)) { - foreach ($model as $babe) - { - $this->model($babe); - } - return; + return $this; } - - if ($model == '') + elseif (is_array($model)) { - return; + foreach ($model as $key => $value) + { + is_int($key) ? $this->model($value, '', $db_conn) : $this->model($key, $value, $db_conn); + } + + return $this; } $path = ''; @@ -250,64 +253,111 @@ class CI_Loader { if (($last_slash = strrpos($model, '/')) !== FALSE) { // The path is in front of the last slash - $path = substr($model, 0, $last_slash + 1); + $path = substr($model, 0, ++$last_slash); // And the model name behind it - $model = substr($model, $last_slash + 1); + $model = substr($model, $last_slash); } - if ($name == '') + if (empty($name)) { $name = $model; } if (in_array($name, $this->_ci_models, TRUE)) { - return; + 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); + throw new RuntimeException('The model name you are loading is the name of a resource that is already being used: '.$name); } - $model = strtolower($model); - - foreach ($this->_ci_model_paths as $mod_path) + if ($db_conn !== FALSE && ! class_exists('CI_DB', FALSE)) { - if ( ! file_exists($mod_path.'models/'.$path.$model.'.php')) + if ($db_conn === TRUE) { - continue; + $db_conn = ''; } - if ($db_conn !== FALSE AND ! class_exists('CI_DB')) + $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')) { - if ($db_conn === TRUE) + require_once($app_path.'Model.php'); + if ( ! class_exists('CI_Model', FALSE)) { - $db_conn = ''; + throw new RuntimeException($app_path."Model.php exists, but doesn't declare class CI_Model"); } - $CI->load->database($db_conn, FALSE, TRUE); + log_message('info', 'CI_Model class loaded'); } - - if ( ! class_exists('CI_Model')) + elseif ( ! class_exists('CI_Model', FALSE)) { - load_class('Model', 'core'); + require_once(BASEPATH.'core'.DIRECTORY_SEPARATOR.'Model.php'); } - require_once($mod_path.'models/'.$path.$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); - - $CI->$name = new $model(); - - $this->_ci_models[] = $name; - return; + log_message('info', config_item('subclass_prefix').'Model class loaded'); + } } - // couldn't find the model - show_error('Unable to locate the model you have specified: '.$model); + $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; } // -------------------------------------------------------------------- @@ -315,18 +365,21 @@ class CI_Loader { /** * Database Loader * - * @param string the DB credentials - * @param bool whether to return the DB object - * @param bool whether to enable active record (this allows us to override the config setting) - * @return object + * @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, $active_record = NULL) + 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 (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db)) + if ($return === FALSE && $query_builder === NULL && isset($CI->db) && is_object($CI->db) && ! empty($CI->db->conn_id)) { return FALSE; } @@ -335,42 +388,48 @@ class CI_Loader { if ($return === TRUE) { - return DB($params, $active_record); + return DB($params, $query_builder); } - // Initialize the db variable. Needed to prevent + // Initialize the db variable. Needed to prevent // reference errors with some configurations $CI->db = ''; // Load the DB class - $CI->db =& DB($params, $active_record); + $CI->db =& DB($params, $query_builder); + return $this; } // -------------------------------------------------------------------- /** - * Load the Utilities Class + * Load the Database Utilities Class * - * @return string + * @param object $db Database object + * @param bool $return Whether to return the DB Utilities class object or not + * @return object */ - public function dbutil() + public function dbutil($db = NULL, $return = FALSE) { - if ( ! class_exists('CI_DB')) - { - $this->database(); - } - $CI =& get_instance(); - // for backwards compatibility, load dbforge so we can extend dbutils off it - // this use is deprecated and strongly discouraged - $CI->load->dbforge(); + 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/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility.php'); - $class = 'CI_DB_'.$CI->db->dbdriver.'_utility'; + require_once(BASEPATH.'database/drivers/'.$db->dbdriver.'/'.$db->dbdriver.'_utility.php'); + $class = 'CI_DB_'.$db->dbdriver.'_utility'; - $CI->dbutil = new $class(); + if ($return === TRUE) + { + return new $class($db); + } + + $CI->dbutil = new $class($db); + return $this; } // -------------------------------------------------------------------- @@ -378,57 +437,72 @@ class CI_Loader { /** * Load the Database Forge Class * - * @return string + * @param object $db Database object + * @param bool $return Whether to return the DB Forge class object or not + * @return object */ - public function dbforge() + public function dbforge($db = NULL, $return = FALSE) { - if ( ! class_exists('CI_DB')) + $CI =& get_instance(); + if ( ! is_object($db) OR ! ($db instanceof CI_DB)) { - $this->database(); + class_exists('CI_DB', FALSE) OR $this->database(); + $db =& $CI->db; } - $CI =& get_instance(); - require_once(BASEPATH.'database/DB_forge.php'); - require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge.php'); - $class = 'CI_DB_'.$CI->db->dbdriver.'_forge'; + require_once(BASEPATH.'database/drivers/'.$db->dbdriver.'/'.$db->dbdriver.'_forge.php'); - $CI->dbforge = new $class(); + 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; } // -------------------------------------------------------------------- /** - * Load View + * View Loader * - * This function is used to load a "view" file. It has three parameters: + * Loads "view" files. * - * 1. The name of the "view" file to be included. - * 2. An associative array of data to be extracted for use in the view. - * 3. TRUE/FALSE - whether to return the data or load it. In - * some cases it's advantageous to be able to return data so that - * a developer can process it in some way. - * - * @param string - * @param array - * @param bool - * @return void + * @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)); + return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return)); } // -------------------------------------------------------------------- /** - * Load File + * Generic File Loader * - * This is a generic file loader - * - * @param string - * @param bool - * @return string + * @param string $path File path + * @param bool $return Whether to return the file output + * @return object|string */ public function file($path, $return = FALSE) { @@ -443,26 +517,39 @@ class CI_Loader { * Once variables are set they become available within * the controller class and its "view" files. * - * @param array - * @param string - * @return void + * @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 = array(), $val = '') + public function vars($vars, $val = '') { - if ($val != '' AND is_string($vars)) + $vars = is_string($vars) + ? array($vars => $val) + : $this->_ci_prepare_view_vars($vars); + + foreach ($vars as $key => $val) { - $vars = array($vars => $val); + $this->_ci_cached_vars[$key] = $val; } - $vars = $this->_ci_object_to_array($vars); + return $this; + } - if (is_array($vars) AND count($vars) > 0) - { - foreach ($vars as $key => $val) - { - $this->_ci_cached_vars[$key] = $val; - } - } + // -------------------------------------------------------------------- + + /** + * Clear Cached Variables + * + * Clears the cached variables. + * + * @return CI_Loader + */ + public function clear_vars() + { + $this->_ci_cached_vars = array(); + return $this; } // -------------------------------------------------------------------- @@ -472,8 +559,8 @@ class CI_Loader { * * Check if a variable is set and retrieve it. * - * @param array - * @return void + * @param string $key Variable name + * @return mixed The variable or NULL if not found */ public function get_var($key) { @@ -483,43 +570,68 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Load Helper + * Get Variables * - * This function loads the specified helper file. + * Retrieves all loaded variables. * - * @param mixed - * @return void + * @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) + 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; } - $ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.'.php'; - // Is this a helper extension request? - if (file_exists($ext_helper)) + $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($ext_helper); include_once($base_helper); - $this->_ci_helpers[$helper] = TRUE; - log_message('debug', 'Helper loaded: '.$helper); + log_message('info', 'Helper loaded: '.$helper); continue; } - // Try to load the helper + // No extensions found ... try loading regular helpers and/or overrides foreach ($this->_ci_helper_paths as $path) { if (file_exists($path.'helpers/'.$helper.'.php')) @@ -527,7 +639,7 @@ class CI_Loader { include_once($path.'helpers/'.$helper.'.php'); $this->_ci_helpers[$helper] = TRUE; - log_message('debug', 'Helper loaded: '.$helper); + log_message('info', 'Helper loaded: '.$helper); break; } } @@ -538,6 +650,8 @@ class CI_Loader { show_error('Unable to load the requested file: helpers/'.$helper.'.php'); } } + + return $this; } // -------------------------------------------------------------------- @@ -545,82 +659,96 @@ class CI_Loader { /** * Load Helpers * - * This is simply an alias to the above function in case the - * user has written the plural form of this function. + * An alias for the helper() method in case the developer has + * written the plural form of it. * - * @param array - * @return void + * @uses CI_Loader::helper() + * @param string|string[] $helpers Helper name(s) + * @return object */ public function helpers($helpers = array()) { - $this->helper($helpers); + return $this->helper($helpers); } // -------------------------------------------------------------------- /** - * Loads a language file + * Language Loader * - * @param array - * @param string - * @return void + * Loads language files. + * + * @param string|string[] $files List of language file names to load + * @param string Language name + * @return object */ - public function language($file = array(), $lang = '') + public function language($files, $lang = '') { - $CI =& get_instance(); - - if ( ! is_array($file)) - { - $file = array($file); - } - - foreach ($file as $langfile) - { - $CI->lang->load($langfile, $lang); - } + get_instance()->lang->load($files, $lang); + return $this; } // -------------------------------------------------------------------- /** - * Loads a config file + * Config Loader * - * @param string - * @param bool - * @param bool - * @return void + * 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) + public function config($file, $use_sections = FALSE, $fail_gracefully = FALSE) { - $CI =& get_instance(); - $CI->config->load($file, $use_sections, $fail_gracefully); + return get_instance()->config->load($file, $use_sections, $fail_gracefully); } // -------------------------------------------------------------------- /** - * Driver + * Driver Loader * - * Loads a driver library + * Loads a driver library. * - * @param string the name of the class - * @param mixed the optional parameters - * @param string an optional object name - * @return void + * @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) + public function driver($library, $params = NULL, $object_name = NULL) { - if ( ! class_exists('CI_Driver_Library')) + if (is_array($library)) { - // we aren't instantiating an object here, that'll be done by the Library itself - require BASEPATH.'libraries/Driver.php'; - } + foreach ($library as $key => $value) + { + if (is_int($key)) + { + $this->driver($value, $params); + } + else + { + $this->driver($key, $params, $value); + } + } - if ($library == '') + 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, '/')) @@ -636,13 +764,19 @@ class CI_Loader { /** * Add Package Path * - * Prepends a parent path to the library, model, helper, and config path arrays + * Prepends a parent path to the library, model, helper and config + * path arrays. * - * @param string - * @param boolean - * @return void + * @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) + public function add_package_path($path, $view_cascade = TRUE) { $path = rtrim($path, '/').'/'; @@ -654,7 +788,9 @@ class CI_Loader { // Add config file path $config =& $this->_ci_get_component('config'); - array_unshift($config->_config_paths, $path); + $config->_config_paths[] = $path; + + return $this; } // -------------------------------------------------------------------- @@ -662,14 +798,14 @@ class CI_Loader { /** * Get Package Paths * - * Return a list of all package paths, by default it will ignore BASEPATH. + * Return a list of all package paths. * - * @param string - * @return void + * @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; + return ($include_base === TRUE) ? $this->_ci_library_paths : $this->_ci_model_paths; } // -------------------------------------------------------------------- @@ -677,24 +813,24 @@ class CI_Loader { /** * Remove Package Path * - * Remove a path from the library, model, and helper path arrays if it exists - * If no path is provided, the most recently added path is removed. + * 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 type - * @param bool - * @return type + * @param string $path Path to remove + * @return object */ - public function remove_package_path($path = '', $remove_config_path = TRUE) + public function remove_package_path($path = '') { $config =& $this->_ci_get_component('config'); - if ($path == '') + if ($path === '') { - $void = array_shift($this->_ci_library_paths); - $void = array_shift($this->_ci_model_paths); - $void = array_shift($this->_ci_helper_paths); - $void = array_shift($this->_ci_view_paths); - $void = array_shift($config->_config_paths); + 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 { @@ -724,32 +860,37 @@ class CI_Loader { $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; } // -------------------------------------------------------------------- /** - * Loader + * Internal CI Data Loader + * + * Used to load views and files. * - * This function is used to load views and files. * Variables are prefixed with _ci_ to avoid symbol collision with - * variables made available to view files + * variables made available to view files. * - * @param array - * @return void + * @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])) ? FALSE : $_ci_data[$_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 ($_ci_path != '') + if (is_string($_ci_path) && $_ci_path !== '') { $_ci_x = explode('/', $_ci_path); $_ci_file = end($_ci_x); @@ -757,13 +898,13 @@ class CI_Loader { else { $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION); - $_ci_file = ($_ci_ext == '') ? $_ci_view.'.php' : $_ci_view; + $_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view; - foreach ($this->_ci_view_paths as $view_file => $cascade) + foreach ($this->_ci_view_paths as $_ci_view_file => $cascade) { - if (file_exists($view_file.$_ci_file)) + if (file_exists($_ci_view_file.$_ci_file)) { - $_ci_path = $view_file.$_ci_file; + $_ci_path = $_ci_view_file.$_ci_file; $file_exists = TRUE; break; } @@ -782,7 +923,6 @@ class CI_Loader { // 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) { @@ -795,15 +935,12 @@ class CI_Loader { /* * Extract and cache variables * - * You can either set variables using the dedicated $this->load_vars() + * 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); - } + empty($_ci_vars) OR $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); extract($this->_ci_cached_vars); /* @@ -811,29 +948,27 @@ class CI_Loader { * * 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. + * 2. So that the final rendered template can be post-processed by + * the output class. Why do we need post processing? For one thing, + * in order to show the elapsed page load time. Unless we can + * intercept the content right before it's sent to the browser and + * then stop the timer it won't be accurate. */ ob_start(); // If the PHP installation does not support short tags we'll // do a little string replacement, changing the short tags // to standard PHP echo statements. - - if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE) + if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE) { - echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace(''.preg_replace('/;*\s*\?>/', '; ?>', str_replace(' $this->_ci_ob_level + 1) { @@ -862,21 +996,24 @@ class CI_Loader { $_ci_CI->output->append_output(ob_get_contents()); @ob_end_clean(); } + + return $this; } // -------------------------------------------------------------------- /** - * Load class + * Internal CI Library Loader * - * This function loads the requested class. + * @used-by CI_Loader::library() + * @uses CI_Loader::_ci_init_library() * - * @param string the item that is being loaded - * @param mixed any additional parameters - * @param string an optional object name + * @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_class($class, $params = NULL, $object_name = NULL) + 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, @@ -885,128 +1022,182 @@ class CI_Loader { // Was the path included with the class name? // We look for a slash to determine this - $subdir = ''; if (($last_slash = strrpos($class, '/')) !== FALSE) { // Extract the path - $subdir = substr($class, 0, $last_slash + 1); + $subdir = substr($class, 0, ++$last_slash); // Get the filename from the path - $class = substr($class, $last_slash + 1); + $class = substr($class, $last_slash); + } + else + { + $subdir = ''; } - // We'll test for both lowercase and capitalized versions of the file name - foreach (array(ucfirst($class), strtolower($class)) as $class) + $class = ucfirst($class); + + // Is this a stock library? There are a few special conditions if so ... + if (file_exists(BASEPATH.'libraries/'.$subdir.$class.'.php')) { - $subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php'; + return $this->_ci_load_stock_library($class, $subdir, $params, $object_name); + } - // Is this a class extension request? - if (file_exists($subclass)) + // Safety: Was the class already loaded by a previous call? + if (class_exists($class, FALSE)) + { + $property = $object_name; + if (empty($property)) { - $baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php'; - - if ( ! file_exists($baseclass)) - { - log_message('error', "Unable to load the requested class: ".$class); - show_error("Unable to load the requested class: ".$class); - } - - // Safety: Was the class already loaded by a previous call? - if (in_array($subclass, $this->_ci_loaded_files)) - { - // Before we deem this to be a duplicate request, let's see - // if a custom object name is being supplied. If so, we'll - // return a new instance of the object - if ( ! is_null($object_name)) - { - $CI =& get_instance(); - if ( ! isset($CI->$object_name)) - { - return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); - } - } - - $is_duplicate = TRUE; - log_message('debug', $class." class already loaded. Second attempt ignored."); - return; - } - - include_once($baseclass); - include_once($subclass); - $this->_ci_loaded_files[] = $subclass; - - return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); + $property = strtolower($class); + isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property]; } - // Lets search for the requested library file and load it. - $is_duplicate = FALSE; - foreach ($this->_ci_library_paths as $path) + $CI =& get_instance(); + if (isset($CI->$property)) { - $filepath = $path.'libraries/'.$subdir.$class.'.php'; - - // Does the file exist? No? Bummer... - if ( ! file_exists($filepath)) - { - continue; - } - - // Safety: Was the class already loaded by a previous call? - if (in_array($filepath, $this->_ci_loaded_files)) - { - // Before we deem this to be a duplicate request, let's see - // if a custom object name is being supplied. If so, we'll - // return a new instance of the object - if ( ! is_null($object_name)) - { - $CI =& get_instance(); - if ( ! isset($CI->$object_name)) - { - return $this->_ci_init_class($class, '', $params, $object_name); - } - } - - $is_duplicate = TRUE; - log_message('debug', $class." class already loaded. Second attempt ignored."); - return; - } - - include_once($filepath); - $this->_ci_loaded_files[] = $filepath; - return $this->_ci_init_class($class, '', $params, $object_name); + log_message('debug', $class.' class already loaded. Second attempt ignored.'); + return; } - } // END FOREACH + 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 == '') + // Let's search for the requested library file and load it. + foreach ($this->_ci_library_paths as $path) { - $path = strtolower($class).'/'.$class; - return $this->_ci_load_class($path, $params); + // 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. - // We do not issue errors if the load call failed due to a duplicate request - if ($is_duplicate == FALSE) - { - log_message('error', "Unable to load the requested class: ".$class); - show_error("Unable to load the requested class: ".$class); - } + log_message('error', 'Unable to load the requested class: '.$class); + show_error('Unable to load the requested class: '.$class); } // -------------------------------------------------------------------- /** - * Instantiates a class + * Internal CI Stock Library Loader * - * @param string - * @param string - * @param bool - * @param string an optional object name - * @return null + * @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_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL) + protected function _ci_load_stock_library($library_name, $file_path, $params, $object_name) { - // Is there an associated config file for this class? Note: these should always be lowercase + $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 @@ -1014,117 +1205,111 @@ class CI_Loader { if (is_array($config_component->_config_paths)) { - // Break on the first found file, thus package files - // are not overridden by default 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. Check for environment - // first, global next - if (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php')) + // 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/'.ENVIRONMENT.'/'.strtolower($class).'.php'); - break; + include($path.'config/'.strtolower($class).'.php'); + $found = TRUE; } - elseif (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php')) + elseif (file_exists($path.'config/'.ucfirst(strtolower($class)).'.php')) { - include($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'); - break; + include($path.'config/'.ucfirst(strtolower($class)).'.php'); + $found = TRUE; } - elseif (file_exists($path .'config/'.strtolower($class).'.php')) + + if (file_exists($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php')) { - include($path .'config/'.strtolower($class).'.php'); - break; + include($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'); + $found = TRUE; } - elseif (file_exists($path .'config/'.ucfirst(strtolower($class)).'.php')) + 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) { - include($path .'config/'.ucfirst(strtolower($class)).'.php'); break; } } } } - if ($prefix == '') - { - if (class_exists('CI_'.$class)) - { - $name = 'CI_'.$class; - } - elseif (class_exists(config_item('subclass_prefix').$class)) - { - $name = config_item('subclass_prefix').$class; - } - else - { - $name = $class; - } - } - else - { - $name = $prefix.$class; - } + $class_name = $prefix.$class; // Is the class name valid? - if ( ! class_exists($name)) + if ( ! class_exists($class_name, FALSE)) { - log_message('error', "Non-existent class: ".$name); - show_error("Non-existent class: ".$class); + 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 - $class = strtolower($class); - - if (is_null($object_name)) + // Was a custom class name supplied? If so we'll use it + if (empty($object_name)) { - $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class]; + $object_name = strtolower($class); + if (isset($this->_ci_varmap[$object_name])) + { + $object_name = $this->_ci_varmap[$object_name]; + } } - else + + // Don't overwrite existing properties + $CI =& get_instance(); + if (isset($CI->$object_name)) { - $classvar = $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[$class] = $classvar; + $this->_ci_classes[$object_name] = $class; // Instantiate the class - $CI =& get_instance(); - if ($config !== NULL) - { - $CI->$classvar = new $name($config); - } - else - { - $CI->$classvar = new $name; - } + $CI->$object_name = isset($config) + ? new $class_name($config) + : new $class_name(); } // -------------------------------------------------------------------- /** - * Autoloader + * CI Autoloader * - * The config/autoload.php file contains an array that permits sub-systems, - * libraries, and helpers to be loaded automatically. + * Loads component listed in the config/autoload.php file. * - * @param array + * @used-by CI_Loader::initialize() * @return void */ - private function _ci_autoloader() + protected function _ci_autoloader() { - if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'); - } - else + 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 FALSE; + return; } // Autoload packages @@ -1139,31 +1324,29 @@ class CI_Loader { // Load any custom config file if (count($autoload['config']) > 0) { - $CI =& get_instance(); - foreach ($autoload['config'] as $key => $val) + foreach ($autoload['config'] as $val) { - $CI->config->load($val); + $this->config($val); } } // Autoload helpers and languages foreach (array('helper', 'language') as $type) { - if (isset($autoload[$type]) AND count($autoload[$type]) > 0) + if (isset($autoload[$type]) && count($autoload[$type]) > 0) { $this->$type($autoload[$type]); } } - // A little tweak to remain backward compatible - // The $autoload['core'] item was deprecated - if ( ! isset($autoload['libraries']) AND isset($autoload['core'])) + // Autoload drivers + if (isset($autoload['drivers'])) { - $autoload['libraries'] = $autoload['core']; + $this->driver($autoload['drivers']); } // Load libraries - if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0) + if (isset($autoload['libraries']) && count($autoload['libraries']) > 0) { // Load the database driver. if (in_array('database', $autoload['libraries'])) @@ -1173,10 +1356,7 @@ class CI_Loader { } // Load all other libraries - foreach ($autoload['libraries'] as $item) - { - $this->library($item); - } + $this->library($autoload['libraries']); } // Autoload models @@ -1189,24 +1369,42 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Object to Array + * Prepare variables for _ci_vars, to be later extract()-ed inside views * - * Takes an object as input and converts the class variables to array key/vals + * Converts objects to associative arrays and filters-out internal + * variable names (i.e. keys prefixed with '_ci_'). * - * @param object + * @param mixed $vars * @return array */ - protected function _ci_object_to_array($object) + protected function _ci_prepare_view_vars($vars) { - return (is_object($object)) ? get_object_vars($object) : $object; + 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; } // -------------------------------------------------------------------- /** - * Get a reference to a specific library or model + * CI Component getter * - * @param string + * Get a reference to a specific library or model. + * + * @param string $component Component name * @return bool */ protected function &_ci_get_component($component) @@ -1214,35 +1412,4 @@ class CI_Loader { $CI =& get_instance(); return $CI->$component; } - - // -------------------------------------------------------------------- - - /** - * Prep filename - * - * This function preps the name of various items to make loading them more reliable. - * - * @param mixed - * @param string - * @return array - */ - protected function _ci_prep_filename($filename, $extension) - { - if ( ! is_array($filename)) - { - return array(strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension)); - } - else - { - foreach ($filename as $key => $val) - { - $filename[$key] = strtolower(str_replace('.php', '', str_replace($extension, '', $val)).$extension); - } - - return $filename; - } - } } - -/* End of file Loader.php */ -/* Location: ./system/core/Loader.php */ \ No newline at end of file diff --git a/system/core/Log.php b/system/core/Log.php new file mode 100644 index 0000000..4338aa9 --- /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 '\n' at the end + */ + protected function _format_line($level, $date, $message) + { + return $level.' - '.$date.' --> '.$message."\n"; + } + + // -------------------------------------------------------------------- + + /** + * 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 old mode 100755 new mode 100644 index 1f14250..0aadbcd --- a/system/core/Model.php +++ b/system/core/Model.php @@ -1,57 +1,76 @@ -$key; + // Debugging note: + // If you're here because you're getting an error message + // saying 'Undefined Property: system/core/Model.php', it's + // most likely a typo in your model code. + return get_instance()->$key; } -} -// END Model Class -/* End of file Model.php */ -/* Location: ./system/core/Model.php */ \ No newline at end of file +} diff --git a/system/core/Output.php b/system/core/Output.php old mode 100755 new mode 100644 index 7959bef..64e7ee1 --- a/system/core/Output.php +++ b/system/core/Output.php @@ -1,112 +1,156 @@ -_zlib_oc = @ini_get('zlib.output_compression'); + $this->_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 - if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) - { - include APPPATH.'config/'.ENVIRONMENT.'/mimes.php'; - } - else - { - include APPPATH.'config/mimes.php'; - } + $this->mimes =& get_mimes(); - - $this->mime_types = $mimes; - - log_message('debug', "Output Class Initialized"); + log_message('info', 'Output Class Initialized'); } // -------------------------------------------------------------------- @@ -114,12 +158,11 @@ class CI_Output { /** * Get Output * - * Returns the current output string + * Returns the current output string. * - * @access public * @return string */ - function get_output() + public function get_output() { return $this->final_output; } @@ -129,16 +172,14 @@ class CI_Output { /** * Set Output * - * Sets the output string + * Sets the output string. * - * @access public - * @param string - * @return void + * @param string $output Output data + * @return CI_Output */ - function set_output($output) + public function set_output($output) { $this->final_output = $output; - return $this; } @@ -147,23 +188,14 @@ class CI_Output { /** * Append Output * - * Appends data onto the output string + * Appends data onto the output string. * - * @access public - * @param string - * @return void + * @param string $output Data to append + * @return CI_Output */ - function append_output($output) + public function append_output($output) { - if ($this->final_output == '') - { - $this->final_output = $output; - } - else - { - $this->final_output .= $output; - } - + $this->final_output .= $output; return $this; } @@ -172,52 +204,49 @@ class CI_Output { /** * Set Header * - * Lets you set a server header which will be outputted with the final display. + * 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. We need to figure out - * how to permit header data to be saved with the cache data... + * Note: If a file is cached, headers will not be sent. + * @todo We need to figure out how to permit headers to be cached. * - * @access public - * @param string - * @param bool - * @return void + * @param string $header Header + * @param bool $replace Whether to replace the old header value, if already set + * @return CI_Output */ - function set_header($header, $replace = TRUE) + 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) + if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) === 0) { - return; + return $this; } $this->headers[] = array($header, $replace); - return $this; } // -------------------------------------------------------------------- /** - * Set Content Type Header + * Set Content-Type Header * - * @access public - * @param string extension of the file we're outputting - * @return void + * @param string $mime_type Extension of the file we're outputting + * @param string $charset Character set (default: NULL) + * @return CI_Output */ - function set_content_type($mime_type) + 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->mime_types[$extension])) + if (isset($this->mimes[$extension])) { - $mime_type =& $this->mime_types[$extension]; + $mime_type =& $this->mimes[$extension]; if (is_array($mime_type)) { @@ -226,28 +255,89 @@ class CI_Output { } } - $header = 'Content-Type: '.$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; } // -------------------------------------------------------------------- /** - * Set HTTP Status Header - * moved to Common procedural functions in 1.7.2 + * Get Current Content-Type Header * - * @access public - * @param int the status code - * @param string - * @return void + * @return string 'text/html', if not already set */ - function set_status_header($code = 200, $text = '') + 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; } @@ -256,14 +346,12 @@ class CI_Output { /** * Enable/disable Profiler * - * @access public - * @param bool - * @return void + * @param bool $val TRUE to enable or FALSE to disable + * @return CI_Output */ - function enable_profiler($val = TRUE) + public function enable_profiler($val = TRUE) { - $this->enable_profiler = (is_bool($val)) ? $val : TRUE; - + $this->enable_profiler = is_bool($val) ? $val : TRUE; return $this; } @@ -272,17 +360,23 @@ class CI_Output { /** * Set Profiler Sections * - * Allows override of default / config settings for Profiler section display + * Allows override of default/config settings for + * Profiler section display. * - * @access public - * @param array - * @return void + * @param array $sections Profiler sections + * @return CI_Output */ - function set_profiler_sections($sections) + 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) ? TRUE : FALSE; + $this->_profiler_sections[$section] = ($enable !== FALSE); } return $this; @@ -293,14 +387,12 @@ class CI_Output { /** * Set Cache * - * @access public - * @param integer - * @return void + * @param int $time Cache expiration time in minutes + * @return CI_Output */ - function cache($time) + public function cache($time) { - $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time; - + $this->cache_expiration = is_numeric($time) ? $time : 0; return $this; } @@ -309,27 +401,27 @@ class CI_Output { /** * Display Output * - * All "view" data is automatically put into this variable by the controller class: + * 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. * - * $this->final_output + * Note: All "view" data is automatically put into $this->final_output + * by controller class. * - * This function sends the finalized output data to the browser along - * with any server headers and profile data. It also stops the - * benchmark timer so the page rendering speed and memory usage can be shown. - * - * @access public - * @param string - * @return mixed + * @uses CI_Output::$final_output + * @param string $output Output data override + * @return void */ - function _display($output = '') + public function _display($output = '') { - // Note: We use globals because we can't use $CI =& get_instance() + // 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. - global $BM, $CFG; + $BM =& load_class('Benchmark', 'core'); + $CFG =& load_class('Config', 'core'); // Grab the super object if we can. - if (class_exists('CI_Controller')) + if (class_exists('CI_Controller', FALSE)) { $CI =& get_instance(); } @@ -337,14 +429,14 @@ class CI_Output { // -------------------------------------------------------------------- // Set the output data - if ($output == '') + if ($output === '') { $output =& $this->final_output; } // -------------------------------------------------------------------- - // Do we need to write a cache file? Only if the controller does not have its + // 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')) @@ -361,24 +453,18 @@ class CI_Output { if ($this->parse_exec_vars === TRUE) { - $memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB'; - - $output = str_replace('{elapsed_time}', $elapsed, $output); - $output = str_replace('{memory_usage}', $memory, $output); + $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 ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE) + 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) { - if (extension_loaded('zlib')) - { - if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) - { - ob_start('ob_gzhandler'); - } - } + ob_start('ob_gzhandler'); } // -------------------------------------------------------------------- @@ -399,20 +485,34 @@ class CI_Output { // 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('debug', "Final output sent to browser"); - log_message('debug', "Total execution time: ".$elapsed); - return TRUE; + 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) + if ($this->enable_profiler === TRUE) { $CI->load->library('profiler'); - if ( ! empty($this->_profiler_sections)) { $CI->profiler->set_sections($this->_profiler_sections); @@ -420,20 +520,13 @@ class CI_Output { // If the output data contains closing and tags // we will remove them and add them back after we insert the profile data - if (preg_match("|.*?|is", $output)) + $output = preg_replace('|.*?|is', '', $output, -1, $count).$CI->profiler->run(); + if ($count > 0) { - $output = preg_replace("|.*?|is", '', $output); - $output .= $CI->profiler->run(); $output .= ''; } - else - { - $output .= $CI->profiler->run(); - } } - // -------------------------------------------------------------------- - // Does the controller contain a function named _output()? // If so send the output there. Otherwise, echo it. if (method_exists($CI, '_output')) @@ -442,133 +535,308 @@ class CI_Output { } else { - echo $output; // Send it to the browser! + echo $output; // Send it to the browser! } - log_message('debug', "Final output sent to browser"); - log_message('debug', "Total execution time: ".$elapsed); + log_message('info', 'Final output sent to browser'); + log_message('debug', 'Total execution time: '.$elapsed); } // -------------------------------------------------------------------- /** - * Write a Cache File + * Write Cache * - * @access public - * @param string + * @param string $output Output data to cache * @return void */ - function _write_cache($output) + public function _write_cache($output) { $CI =& get_instance(); $path = $CI->config->item('cache_path'); - - $cache_path = ($path == '') ? APPPATH.'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); + 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(); + $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, FOPEN_WRITE_CREATE_DESTRUCTIVE)) + if ( ! $fp = @fopen($cache_path, 'w+b')) { - log_message('error', "Unable to write cache file: ".$cache_path); + 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); - if (flock($fp, LOCK_EX)) + // 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) { - fwrite($fp, $expire.'TS--->'.$output); - flock($fp, LOCK_UN); + if (($result = fwrite($fp, self::substr($output, $written))) === FALSE) + { + break; + } } - else + + flock($fp, LOCK_UN); + fclose($fp); + + if ( ! is_int($result)) { - log_message('error', "Unable to secure a file lock for file at: ".$cache_path); + @unlink($cache_path); + log_message('error', 'Unable to write the complete cache content at: '.$cache_path); return; } - fclose($fp); - @chmod($cache_path, FILE_WRITE_MODE); - log_message('debug', "Cache file written: ".$cache_path); + 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 a cached file + * Update/serve cached output * - * @access public - * @param object config class - * @param object uri class - * @return void + * @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 */ - function _display_cache(&$CFG, &$URI) + public function _display_cache(&$CFG, &$URI) { - $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path'); + $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; + // 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)) - { - return FALSE; - } - - if ( ! $fp = @fopen($filepath, FOPEN_READ)) + if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb')) { return FALSE; } flock($fp, LOCK_SH); - $cache = ''; - if (filesize($filepath) > 0) - { - $cache = fread($fp, filesize($filepath)); - } + $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : ''; flock($fp, LOCK_UN); fclose($fp); - // Strip out the embedded timestamp - if ( ! preg_match("/(\d+TS--->)/", $cache, $match)) + // Look for embedded serialized file info. + if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match)) { return FALSE; } - // Has the file expired? If so we'll delete it. - if (time() >= trim(str_replace('TS--->', '', $match['1']))) + $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 (is_really_writable($cache_path)) - { - @unlink($filepath); - log_message('debug', "Cache file has expired. File deleted"); - return FALSE; - } + // 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(str_replace($match['0'], '', $cache)); - log_message('debug', "Cache file is current. Sending it to browser."); + $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); + } } -// END Output Class - -/* End of file Output.php */ -/* Location: ./system/core/Output.php */ \ No newline at end of file diff --git a/system/core/Router.php b/system/core/Router.php old mode 100755 new mode 100644 index b48a345..90b69d0 --- a/system/core/Router.php +++ b/system/core/Router.php @@ -1,19 +1,41 @@ -config =& load_class('Config', 'core'); $this->uri =& load_class('URI', 'core'); - log_message('debug', "Router Class Initialized"); + + $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 the route mapping + * Set route mapping * - * This function determines what should be served based on the URI request, + * Determines what should be served based on the URI request, * as well as any "routes" that have been set in the routing config file. * - * @access private * @return void */ - function _set_routing() + protected function _set_routing() { - // Are query strings enabled in the config file? Normally CI doesn't utilize query strings - // since URI segments are more search-engine friendly, but they can optionally be used. - // If this feature is enabled, we will gather the directory/class/method a little differently - $segments = array(); - if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')])) - { - if (isset($_GET[$this->config->item('directory_trigger')])) - { - $this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')]))); - $segments[] = $this->fetch_directory(); - } - - if (isset($_GET[$this->config->item('controller_trigger')])) - { - $this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')]))); - $segments[] = $this->fetch_class(); - } - - if (isset($_GET[$this->config->item('function_trigger')])) - { - $this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')]))); - $segments[] = $this->fetch_method(); - } - } - - // Load the routes.php file. - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); - } - elseif (is_file(APPPATH.'config/routes.php')) + // 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'); } - $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route; - unset($route); - - // Set the default controller so we can display it in the event - // the URI doesn't correlated to a valid controller. - $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']); - - // Were there any query string segments? If so, we'll validate them and bail out since we're done. - if (count($segments) > 0) + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) { - return $this->_validate_request($segments); + include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); } - // Fetch the complete URI string - $this->uri->_fetch_uri_string(); - - // Is there a URI string? If not, the default controller specified in the "routes" file will be shown. - if ($this->uri->uri_string == '') + // Validate & get reserved routes + if (isset($route) && is_array($route)) { - return $this->_set_default_controller(); + 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; } - // Do we need to remove the URL suffix? - $this->uri->_remove_url_suffix(); - - // Compile the segments into an array - $this->uri->_explode_segments(); - - // Parse any custom routing that may exist - $this->_parse_routes(); - - // Re-index the segment array so that it starts with 1 rather than 0 - $this->uri->_reindex_segments(); - } - - // -------------------------------------------------------------------- - - /** - * Set the default controller - * - * @access private - * @return void - */ - function _set_default_controller() - { - if ($this->default_controller === FALSE) + // 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) { - show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file."); + // 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 the method being specified? - if (strpos($this->default_controller, '/') !== FALSE) - { - $x = explode('/', $this->default_controller); - $this->set_class($x[0]); - $this->set_method($x[1]); - $this->_set_request($x); + // Is there anything to parse? + if ($this->uri->uri_string !== '') + { + $this->_parse_routes(); } else { - $this->set_class($this->default_controller); - $this->set_method('index'); - $this->_set_request(array($this->default_controller, 'index')); + $this->_set_default_controller(); } - - // re-index the routed segments array so it starts with 1 rather than 0 - $this->uri->_reindex_segments(); - - log_message('debug', "No URI present. Default controller set."); } // -------------------------------------------------------------------- /** - * Set the Route + * Set request route * - * This function takes an array of URI segments as - * input, and sets the current class/method + * Takes an array of URI segments as input and sets the class/method + * to be called. * - * @access private - * @param array - * @param bool + * @used-by CI_Router::_parse_routes() + * @param array $segments URI segments * @return void */ - function _set_request($segments = array()) + protected function _set_request($segments = array()) { $segments = $this->_validate_request($segments); - - if (count($segments) == 0) + // If we don't have any segments left - try the default controller; + // WARNING: Directories get shifted out of the segments array! + if (empty($segments)) { - return $this->_set_default_controller(); + $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])) { - // A standard method request $this->set_method($segments[1]); } else { - // This lets the "routed" segment array identify that the default - // index method is being used. $segments[1] = 'index'; } - // Update our "routed" segment array to contain the segments. - // Note: If there is no custom routing, this array will be - // identical to $this->uri->segments + array_unshift($segments, NULL); + unset($segments[0]); $this->uri->rsegments = $segments; } // -------------------------------------------------------------------- /** - * Validates the supplied segments. Attempts to determine the path to - * the controller. + * Set default controller * - * @access private - * @param array - * @return array + * @return void */ - function _validate_request($segments) + protected function _set_default_controller() { - if (count($segments) == 0) + if (empty($this->default_controller)) { - return $segments; + show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.'); } - // Does the requested controller exist in the root folder? - if (file_exists(APPPATH.'controllers/'.$segments[0].'.php')) + // Is the method being specified? + if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2) { - return $segments; + $method = 'index'; } - // Is the controller in a sub-folder? - if (is_dir(APPPATH.'controllers/'.$segments[0])) + if ( ! file_exists(APPPATH.'controllers/'.$this->directory.ucfirst($class).'.php')) { - // Set the directory and remove it from the segment array - $this->set_directory($segments[0]); - $segments = array_slice($segments, 1); - - if (count($segments) > 0) - { - // Does the requested controller exist in the sub-folder? - if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php')) - { - if ( ! empty($this->routes['404_override'])) - { - $x = explode('/', $this->routes['404_override']); - - $this->set_directory(''); - $this->set_class($x[0]); - $this->set_method(isset($x[1]) ? $x[1] : 'index'); - - return $x; - } - else - { - show_404($this->fetch_directory().$segments[0]); - } - } - } - else - { - // Is the method being specified in the route? - if (strpos($this->default_controller, '/') !== FALSE) - { - $x = explode('/', $this->default_controller); - - $this->set_class($x[0]); - $this->set_method($x[1]); - } - else - { - $this->set_class($this->default_controller); - $this->set_method('index'); - } - - // Does the default controller exist in the sub-folder? - if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) - { - $this->directory = ''; - return array(); - } - - } - - return $segments; + // This will trigger 404 later + return; } + $this->set_class($class); + $this->set_method($method); - // If we've gotten this far it means that the URI does not correlate to a valid - // controller class. We will now see if there is an override - if ( ! empty($this->routes['404_override'])) - { - $x = explode('/', $this->routes['404_override']); + // Assign routed segments, index starting from 1 + $this->uri->rsegments = array( + 1 => $class, + 2 => $method + ); - $this->set_class($x[0]); - $this->set_method(isset($x[1]) ? $x[1] : 'index'); - - return $x; - } - - - // Nothing else to do at this point but show a 404 - show_404($segments[0]); + log_message('debug', 'No URI present. Default controller set.'); } // -------------------------------------------------------------------- /** - * Parse Routes + * Validate request * - * This function matches any routes that may exist in - * the config/routes.php file against the URI to - * determine if the class/method need to be remapped. + * 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. * - * @access private * @return void */ - function _parse_routes() + protected function _parse_routes() { // Turn the segment array into a URI string $uri = implode('/', $this->uri->segments); - // Is there a literal match? If so we're done - if (isset($this->routes[$uri])) - { - return $this->_set_request(explode('/', $this->routes[$uri])); - } + // Get HTTP verb + $http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli'; - // Loop through the route array looking for wild-cards + // Loop through the route array looking for wildcards foreach ($this->routes as $key => $val) { - // Convert wild-cards to RegEx - $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key)); + // 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)) + if (preg_match('#^'.$key.'$#', $uri, $matches)) { - // Do we have a back-reference? - if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) + // 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); } - return $this->_set_request(explode('/', $val)); + $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($this->uri->segments); + $this->_set_request(array_values($this->uri->segments)); } // -------------------------------------------------------------------- /** - * Set the class name + * Set class name * - * @access public - * @param string + * @param string $class Class name * @return void */ - function set_class($class) + public function set_class($class) { $this->class = str_replace(array('/', '.'), '', $class); } @@ -414,10 +441,10 @@ class CI_Router { /** * Fetch the current class * - * @access public + * @deprecated 3.0.0 Read the 'class' property instead * @return string */ - function fetch_class() + public function fetch_class() { return $this->class; } @@ -425,13 +452,12 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the method name + * Set method name * - * @access public - * @param string + * @param string $method Method name * @return void */ - function set_method($method) + public function set_method($method) { $this->method = $method; } @@ -439,84 +465,51 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Fetch the current method + * Fetch the current method * - * @access public + * @deprecated 3.0.0 Read the 'method' property instead * @return string */ - function fetch_method() + public function fetch_method() { - if ($this->method == $this->fetch_class()) - { - return 'index'; - } - return $this->method; } // -------------------------------------------------------------------- /** - * Set the directory name + * Set directory name * - * @access public - * @param string + * @param string $dir Directory name + * @param bool $append Whether we're appending rather than setting the full value * @return void */ - function set_directory($dir) + public function set_directory($dir, $append = FALSE) { - $this->directory = str_replace(array('/', '.'), '', $dir).'/'; + if ($append !== TRUE OR empty($this->directory)) + { + $this->directory = str_replace('.', '', trim($dir, '/')).'/'; + } + else + { + $this->directory .= str_replace('.', '', trim($dir, '/')).'/'; + } } // -------------------------------------------------------------------- /** - * Fetch the sub-directory (if any) that contains the requested controller class + * Fetch directory * - * @access public + * Feches the sub-directory (if any) that contains the requested + * controller class. + * + * @deprecated 3.0.0 Read the 'directory' property instead * @return string */ - function fetch_directory() + public function fetch_directory() { return $this->directory; } - // -------------------------------------------------------------------- - - /** - * Set the controller overrides - * - * @access public - * @param array - * @return null - */ - function _set_overrides($routing) - { - if ( ! is_array($routing)) - { - return; - } - - if (isset($routing['directory'])) - { - $this->set_directory($routing['directory']); - } - - if (isset($routing['controller']) AND $routing['controller'] != '') - { - $this->set_class($routing['controller']); - } - - if (isset($routing['function'])) - { - $routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function']; - $this->set_method($routing['function']); - } - } - - } -// END Router Class - -/* End of file Router.php */ -/* Location: ./system/core/Router.php */ \ No newline at end of file diff --git a/system/core/Security.php b/system/core/Security.php old mode 100755 new mode 100644 index efa2df9..883968e --- a/system/core/Security.php +++ b/system/core/Security.php @@ -1,19 +1,41 @@ -', '<', '>', + "'", '"', '&', '$', '#', + '{', '}', '[', ']', '=', + ';', '?', '%20', '%22', + '%3c', // < + '%253c', // < + '%3e', // > + '%0e', // > + '%28', // ( + '%29', // ) + '%2528', // ( + '%26', // & + '%24', // $ + '%3f', // ? + '%3b', // ; + '%3d' // = + ); + /** - * Random Hash for Cross Site Request Forgery Protection Cookie + * Character set * - * @var string - * @access protected + * Will be overridden by the constructor. + * + * @var string */ - protected $_csrf_hash = ''; + public $charset = 'UTF-8'; + /** - * Expiration time for Cross Site Request Forgery Protection Cookie - * Defaults to two hours (in seconds) + * XSS Hash * - * @var int - * @access protected + * Random Hash for protecting URLs. + * + * @var string */ - protected $_csrf_expire = 7200; + protected $_xss_hash; + /** - * Token name for Cross Site Request Forgery Protection Cookie + * CSRF Hash * - * @var string - * @access protected + * Random hash for Cross Site Request Forgery protection cookie + * + * @var string */ - protected $_csrf_token_name = 'ci_csrf_token'; + protected $_csrf_hash; + /** - * Cookie name for Cross Site Request Forgery Protection Cookie + * CSRF Expire time * - * @var string - * @access protected + * Expiration time for Cross Site Request Forgery protection cookie. + * Defaults to two hours (in seconds). + * + * @var int */ - protected $_csrf_cookie_name = 'ci_csrf_token'; + 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 - * @access protected + * @var array */ - protected $_never_allowed_str = array( - 'document.cookie' => '[removed]', - 'document.write' => '[removed]', - '.parentNode' => '[removed]', - '.innerHTML' => '[removed]', - 'window.location' => '[removed]', - '-moz-binding' => '[removed]', - '' => '-->', - ' '<![CDATA[', - '' => '<comment>' + 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>', + '<%' => '<%' ); - /* never allowed, regex replacement */ /** - * List of never allowed regex replacement + * List of never allowed regex replacements * - * @var array - * @access protected + * @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! - 'Redirect\s+302', + 'wscript\s*:', // IE + 'jscript\s*:', // IE + 'vbs\s*:', // IE + 'Redirect\s+30\d', "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?" ); /** - * Constructor + * Class constructor * * @return void */ public function __construct() { // Is CSRF protection enabled? - if (config_item('csrf_protection') === TRUE) + if (config_item('csrf_protection')) { // CSRF config foreach (array('csrf_expire', 'csrf_token_name', 'csrf_cookie_name') as $key) { - if (FALSE !== ($val = config_item($key))) + if (NULL !== ($val = config_item($key))) { $this->{'_'.$key} = $val; } } // Append application specific cookie prefix - if (config_item('cookie_prefix')) + if ($cookie_prefix = config_item('cookie_prefix')) { - $this->_csrf_cookie_name = config_item('cookie_prefix').$this->_csrf_cookie_name; + $this->_csrf_cookie_name = $cookie_prefix.$this->_csrf_cookie_name; } // Set the CSRF hash $this->_csrf_set_hash(); } - log_message('debug', "Security Class Initialized"); + $this->charset = strtoupper(config_item('charset')); + + log_message('info', 'Security Class Initialized'); } // -------------------------------------------------------------------- /** - * Verify Cross Site Request Forgery Protection + * CSRF Verify * - * @return object + * @return CI_Security */ public function csrf_verify() { @@ -143,52 +213,74 @@ class CI_Security { return $this->csrf_set_cookie(); } - // Do the tokens exist in both the _POST and _COOKIE arrays? - if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])) + // Check if URI has been whitelisted from CSRF checks + if ($exclude_uris = config_item('csrf_exclude_uris')) { - $this->csrf_show_error(); + $uri = load_class('URI', 'core'); + foreach ($exclude_uris as $excluded) + { + if (preg_match('#^'.$excluded.'$#i'.(UTF8_ENABLED ? 'u' : ''), $uri->uri_string())) + { + return $this; + } + } } - // Do the tokens match? - if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name]) - { - $this->csrf_show_error(); - } + // 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]) + && 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 - // polute the _POST array + // We kill this since we're done and we don't want to pollute the _POST array unset($_POST[$this->_csrf_token_name]); - // Nothing should last forever - unset($_COOKIE[$this->_csrf_cookie_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(); - log_message('debug', 'CSRF token verified'); + if ($valid !== TRUE) + { + $this->csrf_show_error(); + } + log_message('info', 'CSRF token verified'); return $this; } // -------------------------------------------------------------------- /** - * Set Cross Site Request Forgery Protection Cookie + * CSRF Set Cookie * - * @return object + * @codeCoverageIgnore + * @return CI_Security */ public function csrf_set_cookie() { $expire = time() + $this->_csrf_expire; - $secure_cookie = (config_item('cookie_secure') === TRUE) ? 1 : 0; + $secure_cookie = (bool) config_item('cookie_secure'); - if ($secure_cookie && (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) === 'off')) + 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); - - log_message('debug', "CRSF cookie Set"); + 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; } @@ -202,7 +294,7 @@ class CI_Security { */ public function csrf_show_error() { - show_error('The action you have requested is not allowed.'); + show_error('The action you have requested is not allowed.', 403); } // -------------------------------------------------------------------- @@ -210,9 +302,8 @@ class CI_Security { /** * Get CSRF Hash * - * Getter Method - * - * @return string self::_csrf_hash + * @see CI_Security::$_csrf_hash + * @return string CSRF hash */ public function get_csrf_hash() { @@ -224,9 +315,8 @@ class CI_Security { /** * Get CSRF Token Name * - * Getter Method - * - * @return string self::csrf_token_name + * @see CI_Security::$_csrf_token_name + * @return string CSRF token name */ public function get_csrf_token_name() { @@ -239,52 +329,44 @@ class CI_Security { * XSS Clean * * Sanitizes data so that Cross Site Scripting Hacks can be - * prevented. This function does a fair amount of work but + * 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: This function should only be used to deal with data - * upon submission. It's not something that should - * be used for general runtime processing. + * Note: Should only be used to deal with data upon submission. + * It's not something that should be used for general + * runtime processing. * - * This function was based in part on some code and ideas I - * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention + * @link http://channel.bitflux.ch/wiki/XSS_Prevention + * Based in part on some code and ideas from Bitflux. * - * To help develop this script I used this great list of - * vulnerabilities along with a few other hacks I've - * harvested from examining vulnerabilities in other programs: - * http://ha.ckers.org/xss.html + * @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 mixed string or array - * @param bool + * @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? - * - */ + // Is the string an array? if (is_array($str)) { - while (list($key) = each($str)) + foreach ($str as $key => &$value) { - $str[$key] = $this->xss_clean($str[$key]); + $str[$key] = $this->xss_clean($value); } return $str; } - /* - * Remove Invisible Characters - */ + // Remove Invisible Characters $str = remove_invisible_characters($str); - // Validate Entities in URLs - $str = $this->_validate_entities($str); - /* * URL Decode * @@ -293,9 +375,18 @@ class CI_Security { * Google * * Note: Use rawurldecode() so it does not remove plus signs - * */ - $str = rawurldecode($str); + 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 @@ -303,16 +394,11 @@ class CI_Security { * 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); - $str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", array($this, '_convert_attribute'), $str); - - $str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", array($this, '_decode_entity'), $str); - - /* - * Remove Invisible Characters Again! - */ + // Remove Invisible Characters Again! $str = remove_invisible_characters($str); /* @@ -323,15 +409,9 @@ class CI_Security { * 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); - if (strpos($str, "\t") !== FALSE) - { - $str = str_replace("\t", ' ', $str); - } - - /* - * Capture converted string for later comparison - */ + // Capture converted string for later comparison $converted_string = $str; // Remove Strings that are never allowed @@ -351,11 +431,11 @@ class CI_Security { // Images have a tendency to have the PHP short opening and // closing tags every so often so we skip those and only // do the long opening tags. - $str = preg_replace('/<\?(php)/i', "<?\\1", $str); + $str = preg_replace('/<\?(php)/i', '<?\\1', $str); } else { - $str = str_replace(array(''), array('<?', '?>'), $str); + $str = str_replace(array(''), array('<?', '?>'), $str); } /* @@ -365,56 +445,54 @@ class CI_Security { * These words are compacted back to their correct state. */ $words = array( - 'javascript', 'expression', 'vbscript', 'script', 'base64', - 'applet', 'alert', 'document', 'write', 'cookie', 'window' + 'javascript', 'expression', 'vbscript', 'jscript', 'wscript', + 'vbs', 'script', 'base64', 'applet', 'alert', 'document', + 'write', 'cookie', 'window', 'confirm', 'prompt', 'eval' ); foreach ($words as $word) { - $temp = ''; - - for ($i = 0, $wordlen = strlen($word); $i < $wordlen; $i++) - { - $temp .= substr($word, $i, 1)."\s*"; - } + $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($temp, 0, -3).')(\W)#is', array($this, '_compact_exploded_words'), $str); + $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 for PHP5, + * 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); + $str = preg_replace_callback('#]+([^>]*?)(?:>|$)#si', array($this, '_js_link_removal'), $str); } - if (preg_match("/]*?)(\s?/?>|$)#si", array($this, '_js_img_removal'), $str); + $str = preg_replace_callback('#]*?)(?:\s?/?>|$)#si', array($this, '_js_img_removal'), $str); } - if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str)) + if (preg_match('/script|xss/i', $str)) { - $str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '[removed]', $str); + $str = preg_replace('##si', '[removed]', $str); } } - while($original != $str); - + while ($original !== $str); unset($original); - // Remove evil attributes such as style, onclick and xmlns - $str = $this->_remove_evil_attributes($str, $is_image); - /* * Sanitize naughty HTML elements * @@ -424,23 +502,55 @@ class CI_Security { * So this: * Becomes: <blink> */ - $naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss'; - $str = preg_replace_callback('#<(/*\s*)('.$naughty.')([^><]*)([><]*)#is', array($this, '_sanitize_naughty_html'), $str); + $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 + * 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') + * Becomes: eval('some code') */ - $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str); + $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 @@ -456,29 +566,32 @@ class CI_Security { * string post-removal of XSS, then it fails, as there was unwanted XSS * code found and removed/changed during processing. */ - if ($is_image === TRUE) { - return ($str == $converted_string) ? TRUE: FALSE; + return ($str === $converted_string); } - log_message('debug', "XSS Filtering completed"); return $str; } // -------------------------------------------------------------------- /** - * Random Hash for protecting URLs + * XSS Hash * - * @return string + * 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 == '') + if ($this->_xss_hash === NULL) { - mt_srand(); - $this->_xss_hash = md5(time() + mt_rand(0, 1999999999)); + $rand = $this->get_random_bytes(16); + $this->_xss_hash = ($rand === FALSE) + ? md5(uniqid(mt_rand(), TRUE)) + : bin2hex($rand); } return $this->_xss_hash; @@ -487,76 +600,158 @@ class CI_Security { // -------------------------------------------------------------------- /** - * HTML Entities Decode + * Get random bytes * - * This function is a replacement for html_entity_decode() - * - * The reason we are not using html_entity_decode() by itself is because - * while it is not technically correct to leave out the semicolon - * at the end of an entity most browsers will still interpret the entity - * correctly. html_entity_decode() does not convert entities without - * semicolons, so we are left with our own little solution here. Bummer. - * - * @param string - * @param string + * @param int $length Output length * @return string */ - public function entity_decode($str, $charset='UTF-8') + public function get_random_bytes($length) { - if (stristr($str, '&') === FALSE) + if (empty($length) OR ! ctype_digit((string) $length)) { - return $str; + return FALSE; } - $str = html_entity_decode($str, ENT_COMPAT, $charset); - $str = preg_replace('~&#x(0*[0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str); - return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str); + 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; } // -------------------------------------------------------------------- /** - * Filename Security + * HTML Entities Decode * - * @param string - * @param bool + * 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 = array( - "../", - "", - "<", - ">", - "'", - '"', - '&', - '$', - '#', - '{', - '}', - '[', - ']', - '=', - ';', - '?', - "%20", - "%22", - "%3c", // < - "%253c", // < - "%3e", // > - "%0e", // > - "%28", // ( - "%29", // ) - "%2528", // ( - "%26", // & - "%24", // $ - "%3f", // ? - "%3b", // ; - "%3d" // = - ); + $bad = $this->filename_bad_chars; if ( ! $relative_path) { @@ -565,7 +760,53 @@ class CI_Security { } $str = remove_invisible_characters($str, FALSE); - return stripslashes(str_replace($bad, '', $str)); + + 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); } // ---------------------------------------------------------------- @@ -573,11 +814,12 @@ class CI_Security { /** * Compact Exploded Words * - * Callback function for xss_clean() to remove whitespace from - * things like j a v a s c r i p t + * Callback method for xss_clean() to remove whitespace from + * things like 'j a v a s c r i p t'. * - * @param type - * @return type + * @used-by CI_Security::xss_clean() + * @param array $matches + * @return string */ protected function _compact_exploded_words($matches) { @@ -586,86 +828,93 @@ class CI_Security { // -------------------------------------------------------------------- - /* - * Remove Evil HTML Attributes (like evenhandlers and style) - * - * It removes the evil attribute and either: - * - Everything up until a space - * For example, everything between the pipes: - * - * - Everything inside the quotes - * For example, everything between the pipes: - * - * - * @param string $str The string to check - * @param boolean $is_image TRUE if this is an image - * @return string The string with the evil attributes removed - */ - protected function _remove_evil_attributes($str, $is_image) - { - // All javascript event handlers (e.g. onload, onclick, onmouseover), style, and xmlns - $evil_attributes = array('on\w*', 'style', 'xmlns', 'formaction'); - - if ($is_image === TRUE) - { - /* - * Adobe Photoshop puts XML metadata into JFIF images, - * including namespacing, so we have to allow this for images. - */ - unset($evil_attributes[array_search('xmlns', $evil_attributes)]); - } - - do { - $count = 0; - $attribs = array(); - - // find occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes) - preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*(\042|\047)([^\\2]*?)(\\2)/is', $str, $matches, PREG_SET_ORDER); - - foreach ($matches as $attr) - { - $attribs[] = preg_quote($attr[0], '/'); - } - - // find occurrences of illegal attribute strings without quotes - preg_match_all('/('.implode('|', $evil_attributes).')\s*=\s*([^\s>]*)/is', $str, $matches, PREG_SET_ORDER); - - foreach ($matches as $attr) - { - $attribs[] = preg_quote($attr[0], '/'); - } - - // replace illegal attribute strings that are inside an html tag - if (count($attribs) > 0) - { - $str = preg_replace('/(<]+?)([^A-Za-z<>\-])(.*?)('.implode('|', $attribs).')(.*?)([\s><]?)([><]*)/i', '$1$2 $4$6$7$8', $str, -1, $count); - } - - } while ($count); - - return $str; - } - - // -------------------------------------------------------------------- - /** * Sanitize Naughty HTML * - * Callback function for xss_clean() to remove naughty HTML elements + * Callback method for xss_clean() to remove naughty HTML elements. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $matches * @return string */ protected function _sanitize_naughty_html($matches) { - // encode opening brace - $str = '<'.$matches[1].$matches[2].$matches[3]; + 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' + ); - // encode captured opening or closing brace to prevent recursive vectors - $str .= str_replace(array('>', '<'), array('>', '<'), - $matches[4]); + static $evil_attributes = array( + 'on\w+', 'style', 'xmlns', 'formaction', 'form', 'xlink:href', 'FSCommand', 'seekSegmentTime' + ); - return $str; + // 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]; } // -------------------------------------------------------------------- @@ -673,12 +922,14 @@ class CI_Security { /** * JS Link Removal * - * Callback function for xss_clean() to sanitize links + * 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 + * PHP 5.2+ on link-heavy strings. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _js_link_removal($match) @@ -686,9 +937,9 @@ class CI_Security { return str_replace( $match[1], preg_replace( - '#href=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>'), '', $match[1])) + $this->_filter_attributes($match[1]) ), $match[0] ); @@ -699,12 +950,14 @@ class CI_Security { /** * JS Image Removal * - * Callback function for xss_clean() to sanitize image tags + * 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 + * PHP 5.2+ on image tag heavy strings. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _js_img_removal($match) @@ -712,9 +965,9 @@ class CI_Security { return str_replace( $match[1], preg_replace( - '#src=.*?(alert\(|alert&\#40;|javascript\:|livescript\:|mocha\:|charset\=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>'), '', $match[1])) + $this->_filter_attributes($match[1]) ), $match[0] ); @@ -725,9 +978,8 @@ class CI_Security { /** * Attribute Conversion * - * Used as a callback for XSS Clean - * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _convert_attribute($match) @@ -740,20 +992,21 @@ class CI_Security { /** * Filter Attributes * - * Filters tag attributes for consistency and safety + * Filters tag attributes for consistency and safety. * - * @param string + * @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); + $out .= preg_replace('#/\*.*?\*/#s', '', $match); } } @@ -765,68 +1018,30 @@ class CI_Security { /** * HTML Entity Decode Callback * - * Used as a callback for XSS Clean - * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _decode_entity($match) { - return $this->entity_decode($match[0], strtoupper(config_item('charset'))); + // 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) + ); } // -------------------------------------------------------------------- - /** - * Validate URL entities - * - * Called by xss_clean() - * - * @param string - * @return string - */ - protected function _validate_entities($str) - { - /* - * Protect GET variables in URLs - */ - - // 901119URL5918AMP18930PROTECT8198 - - $str = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-]+)|i', $this->xss_hash()."\\1=\\2", $str); - - /* - * Validate standard character entities - * - * Add a semicolon if missing. We do this to enable - * the conversion of entities to ASCII later. - * - */ - $str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str); - - /* - * Validate UTF16 two byte encoding (x00) - * - * Just as above, adds a semicolon if missing. - * - */ - $str = preg_replace('#(&\#x?)([0-9A-F]+);?#i',"\\1\\2;",$str); - - /* - * Un-Protect GET variables in URLs - */ - $str = str_replace($this->xss_hash(), '&', $str); - - return $str; - } - - // ---------------------------------------------------------------------- - /** * Do Never Allowed * - * A utility function for xss_clean() - * + * @used-by CI_Security::xss_clean() * @param string * @return string */ @@ -845,31 +1060,31 @@ class CI_Security { // -------------------------------------------------------------------- /** - * Set Cross Site Request Forgery Protection Cookie + * Set CSRF Hash and Cookie * * @return string */ protected function _csrf_set_hash() { - if ($this->_csrf_hash == '') + if ($this->_csrf_hash === NULL) { - // If the cookie exists we will use it's value. + // 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]) && - preg_match('#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name]) === 1) + 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]; } - return $this->_csrf_hash = md5(uniqid(rand(), TRUE)); + $rand = $this->get_random_bytes(16); + $this->_csrf_hash = ($rand === FALSE) + ? md5(uniqid(mt_rand(), TRUE)) + : bin2hex($rand); } return $this->_csrf_hash; } } - -/* End of file Security.php */ -/* Location: ./system/libraries/Security.php */ diff --git a/system/core/URI.php b/system/core/URI.php old mode 100755 new mode 100644 index a2f3b23..a8b98ae --- a/system/core/URI.php +++ b/system/core/URI.php @@ -1,19 +1,41 @@ -config =& load_class('Config', 'core'); - log_message('debug', "URI Class Initialized"); - } - - // -------------------------------------------------------------------- - - /** - * Get the URI String - * - * @access private - * @return string - */ - function _fetch_uri_string() - { - if (strtoupper($this->config->item('uri_protocol')) == 'AUTO') + // 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) { - // Is the request coming from the command line? - if (php_sapi_name() == 'cli' or defined('STDIN')) + $this->_permitted_uri_chars = $this->config->item('permitted_uri_chars'); + + // If it's a CLI request, ignore the configuration + if (is_cli()) { - $this->_set_uri_string($this->_parse_cli_args()); - return; + $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; + } } - // Let's try the REQUEST_URI first, this will work in most situations - if ($uri = $this->_detect_uri()) - { - $this->_set_uri_string($uri); - return; - } - - // Is there a PATH_INFO variable? - // Note: some servers seem to have trouble with getenv() so we'll test it two ways - $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'); - if (trim($path, '/') != '' && $path != "/".SELF) - { - $this->_set_uri_string($path); - return; - } - - // No PATH_INFO?... What about QUERY_STRING? - $path = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING'); - if (trim($path, '/') != '') - { - $this->_set_uri_string($path); - return; - } - - // As a last ditch effort lets try using the $_GET array - if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '') - { - $this->_set_uri_string(key($_GET)); - return; - } - - // We've exhausted all our options... - $this->uri_string = ''; - return; + $this->_set_uri_string($uri); } - $uri = strtoupper($this->config->item('uri_protocol')); - - if ($uri == 'REQUEST_URI') - { - $this->_set_uri_string($this->_detect_uri()); - return; - } - elseif ($uri == 'CLI') - { - $this->_set_uri_string($this->_parse_cli_args()); - return; - } - - $path = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri); - $this->_set_uri_string($path); + log_message('info', 'URI Class Initialized'); } // -------------------------------------------------------------------- /** - * Set the URI String + * Set URI String * - * @access public - * @param string - * @return string + * @param string $str + * @return void */ - function _set_uri_string($str) + protected function _set_uri_string($str) { - // Filter out control characters - $str = remove_invisible_characters($str, FALSE); + // Filter out control characters and trim slashes + $this->uri_string = trim(remove_invisible_characters($str, FALSE), '/'); - // If the URI contains only a slash we'll kill it - $this->uri_string = ($str == '/') ? '' : $str; + 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]); + } } // -------------------------------------------------------------------- /** - * Detects the URI + * Parse REQUEST_URI * - * This function will detect the URI automatically and fix the query string - * if necessary. + * Will parse REQUEST_URI and automatically detect the URI from it, + * while fixing the query string if necessary. * - * @access private * @return string */ - private function _detect_uri() + protected function _parse_request_uri() { - if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME'])) + if ( ! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) { return ''; } - $uri = $_SERVER['REQUEST_URI']; - if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) + // 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])) { - $uri = substr($uri, strlen($_SERVER['SCRIPT_NAME'])); - } - elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0) - { - $uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME']))); + 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 (strncmp($uri, '?/', 2) === 0) + if (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0) { - $uri = substr($uri, 2); - } - $parts = preg_split('#\?#i', $uri, 2); - $uri = $parts[0]; - if (isset($parts[1])) - { - $_SERVER['QUERY_STRING'] = $parts[1]; - parse_str($_SERVER['QUERY_STRING'], $_GET); + $query = explode('?', $query, 2); + $uri = $query[0]; + $_SERVER['QUERY_STRING'] = isset($query[1]) ? $query[1] : ''; } else { - $_SERVER['QUERY_STRING'] = ''; - $_GET = array(); + $_SERVER['QUERY_STRING'] = $query; } - if ($uri == '/' || empty($uri)) + parse_str($_SERVER['QUERY_STRING'], $_GET); + + if ($uri === '/' OR $uri === '') { return '/'; } - $uri = parse_url($uri, PHP_URL_PATH); - // Do some final cleaning of the URI and return it - return str_replace(array('//', '../'), '/', trim($uri, '/')); + return $this->_remove_relative_directory($uri); } // -------------------------------------------------------------------- /** - * Parse cli arguments + * 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. * - * @access private * @return string */ - private function _parse_cli_args() + protected function _parse_argv() { $args = array_slice($_SERVER['argv'], 1); - - return $args ? '/' . implode('/', $args) : ''; + return $args ? implode('/', $args) : ''; } // -------------------------------------------------------------------- /** - * Filter segments for malicious characters + * Remove relative directory (../) and multi slashes (///) * - * @access private - * @param string + * Do some final cleaning of the URI and return it, currently only used in self::_parse_request_uri() + * + * @param string $uri * @return string */ - function _filter_uri($str) + protected function _remove_relative_directory($uri) { - if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE) + $uris = array(); + $tok = strtok($uri, '/'); + while ($tok !== FALSE) { - // preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards - // compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern - if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str)) + if (( ! empty($tok) OR $tok === '0') && $tok !== '..') { - show_error('The URI you submitted has disallowed characters.', 400); + $uris[] = $tok; } + $tok = strtok('/'); } - // Convert programatic characters to entities - $bad = array('$', '(', ')', '%28', '%29'); - $good = array('$', '(', ')', '(', ')'); - - return str_replace($bad, $good, $str); + return implode('/', $uris); } // -------------------------------------------------------------------- /** - * Remove the suffix from the URL if needed + * Filter URI * - * @access private + * Filters segments for malicious characters. + * + * @param string $str * @return void */ - function _remove_url_suffix() + public function filter_uri(&$str) { - if ($this->config->item('url_suffix') != "") + if ( ! empty($str) && ! empty($this->_permitted_uri_chars) && ! preg_match('/^['.$this->_permitted_uri_chars.']+$/i'.(UTF8_ENABLED ? 'u' : ''), $str)) { - $this->uri_string = preg_replace("|".preg_quote($this->config->item('url_suffix'))."$|", "", $this->uri_string); + show_error('The URI you submitted has disallowed characters.', 400); } } // -------------------------------------------------------------------- /** - * Explode the URI Segments. The individual segments will - * be stored in the $this->segments array. + * Fetch URI Segment * - * @access private - * @return void + * @see CI_URI::$segments + * @param int $n Index + * @param mixed $no_result What to return if the segment index is not found + * @return mixed */ - function _explode_segments() + public function segment($n, $no_result = NULL) { - foreach (explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val) - { - // Filter segments for security - $val = trim($this->_filter_uri($val)); - - if ($val != '') - { - $this->segments[] = $val; - } - } - } - - // -------------------------------------------------------------------- - /** - * Re-index Segments - * - * This function re-indexes the $this->segment array so that it - * starts at 1 rather than 0. Doing so makes it simpler to - * use functions like $this->uri->segment(n) since there is - * a 1:1 relationship between the segment array and the actual segments. - * - * @access private - * @return void - */ - function _reindex_segments() - { - array_unshift($this->segments, NULL); - array_unshift($this->rsegments, NULL); - unset($this->segments[0]); - unset($this->rsegments[0]); + return isset($this->segments[$n]) ? $this->segments[$n] : $no_result; } // -------------------------------------------------------------------- /** - * Fetch a URI Segment + * Fetch URI "routed" Segment * - * This function returns the URI segment based on the number provided. + * 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(). * - * @access public - * @param integer - * @param bool - * @return string + * @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 */ - function segment($n, $no_result = FALSE) + public function rsegment($n, $no_result = NULL) { - return ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n]; + return isset($this->rsegments[$n]) ? $this->rsegments[$n] : $no_result; } // -------------------------------------------------------------------- /** - * Fetch a URI "routed" Segment + * URI to assoc * - * This function returns the re-routed URI segment (assuming routing rules are used) - * based on the number provided. If there is no routing this function returns the - * same result as $this->segment() - * - * @access public - * @param integer - * @param bool - * @return string - */ - function rsegment($n, $no_result = FALSE) - { - return ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n]; - } - - // -------------------------------------------------------------------- - - /** - * Generate a key value pair from the URI string - * - * This function generates and associative array of URI data starting - * at the supplied segment. For example, if this is your URI: + * 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 function to generate an array with this prototype: + * You can use this method to generate an array with this prototype: * - * array ( - * name => joe - * location => UK - * gender => male - * ) + * array ( + * name => joe + * location => UK + * gender => male + * ) * - * @access public - * @param integer the starting segment number - * @param array an array of default values + * @param int $n Index (default: 3) + * @param array $default Default values * @return array */ - function uri_to_assoc($n = 3, $default = array()) + public function uri_to_assoc($n = 3, $default = array()) { return $this->_uri_to_assoc($n, $default, 'segment'); } + + // -------------------------------------------------------------------- + /** - * Identical to above only it uses the re-routed segment array + * Routed URI to assoc * - * @access public - * @param integer the starting segment number - * @param array an array of default values + * 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 - * */ - function ruri_to_assoc($n = 3, $default = array()) + public function ruri_to_assoc($n = 3, $default = array()) { return $this->_uri_to_assoc($n, $default, 'rsegment'); } @@ -406,57 +414,43 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Generate a key value pair from the URI string or Re-routed URI string + * Internal URI-to-assoc * - * @access private - * @param integer the starting segment number - * @param array an array of default values - * @param string which array we should use + * 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 */ - function _uri_to_assoc($n = 3, $default = array(), $which = 'segment') + protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment') { - if ($which == 'segment') - { - $total_segments = 'total_segments'; - $segment_array = 'segment_array'; - } - else - { - $total_segments = 'total_rsegments'; - $segment_array = 'rsegment_array'; - } - if ( ! is_numeric($n)) { return $default; } - if (isset($this->keyval[$n])) + if (isset($this->keyval[$which], $this->keyval[$which][$n])) { - return $this->keyval[$n]; + return $this->keyval[$which][$n]; } + $total_segments = "total_{$which}s"; + $segment_array = "{$which}_array"; + if ($this->$total_segments() < $n) { - if (count($default) == 0) - { - return array(); - } - - $retval = array(); - foreach ($default as $val) - { - $retval[$val] = FALSE; - } - return $retval; + return (count($default) === 0) + ? array() + : array_fill_keys($default, NULL); } $segments = array_slice($this->$segment_array(), ($n - 1)); - $i = 0; $lastval = ''; - $retval = array(); + $retval = array(); foreach ($segments as $seg) { if ($i % 2) @@ -465,7 +459,7 @@ class CI_URI { } else { - $retval[$seg] = FALSE; + $retval[$seg] = NULL; $lastval = $seg; } @@ -478,30 +472,31 @@ class CI_URI { { if ( ! array_key_exists($val, $retval)) { - $retval[$val] = FALSE; + $retval[$val] = NULL; } } } // Cache the array for reuse - $this->keyval[$n] = $retval; + isset($this->keyval[$which]) OR $this->keyval[$which] = array(); + $this->keyval[$which][$n] = $retval; return $retval; } // -------------------------------------------------------------------- /** - * Generate a URI string from an associative array + * Assoc to URI * + * Generates a URI string from an associative array. * - * @access public - * @param array an associative array of key/values - * @return array + * @param array $array Input array of key/value pairs + * @return string URI string */ - function assoc_to_uri($array) + public function assoc_to_uri($array) { $temp = array(); - foreach ((array)$array as $key => $val) + foreach ((array) $array as $key => $val) { $temp[] = $key; $temp[] = $val; @@ -513,14 +508,15 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment and add a trailing slash + * Slash segment * - * @access public - * @param integer - * @param string + * Fetches an URI segment with a slash. + * + * @param int $n Index + * @param string $where Where to add the slash ('trailing' or 'leading') * @return string */ - function slash_segment($n, $where = 'trailing') + public function slash_segment($n, $where = 'trailing') { return $this->_slash_segment($n, $where, 'segment'); } @@ -528,14 +524,15 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment and add a trailing slash + * Slash routed segment * - * @access public - * @param integer - * @param string + * 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 */ - function slash_rsegment($n, $where = 'trailing') + public function slash_rsegment($n, $where = 'trailing') { return $this->_slash_segment($n, $where, 'rsegment'); } @@ -543,24 +540,27 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment and add a trailing slash - helper function + * Internal Slash segment * - * @access private - * @param integer - * @param string - * @param string + * 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 */ - function _slash_segment($n, $where = 'trailing', $which = 'segment') + protected function _slash_segment($n, $where = 'trailing', $which = 'segment') { - $leading = '/'; - $trailing = '/'; + $leading = $trailing = '/'; - if ($where == 'trailing') + if ($where === 'trailing') { $leading = ''; } - elseif ($where == 'leading') + elseif ($where === 'leading') { $trailing = ''; } @@ -573,10 +573,9 @@ class CI_URI { /** * Segment Array * - * @access public - * @return array + * @return array CI_URI::$segments */ - function segment_array() + public function segment_array() { return $this->segments; } @@ -586,10 +585,9 @@ class CI_URI { /** * Routed Segment Array * - * @access public - * @return array + * @return array CI_URI::$rsegments */ - function rsegment_array() + public function rsegment_array() { return $this->rsegments; } @@ -599,10 +597,9 @@ class CI_URI { /** * Total number of segments * - * @access public - * @return integer + * @return int */ - function total_segments() + public function total_segments() { return count($this->segments); } @@ -612,10 +609,9 @@ class CI_URI { /** * Total number of routed segments * - * @access public - * @return integer + * @return int */ - function total_rsegments() + public function total_rsegments() { return count($this->rsegments); } @@ -623,32 +619,25 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch the entire URI string + * Fetch URI string * - * @access public - * @return string + * @return string CI_URI::$uri_string */ - function uri_string() + public function uri_string() { return $this->uri_string; } - // -------------------------------------------------------------------- /** - * Fetch the entire Re-routed URI string + * Fetch Re-routed URI string * - * @access public * @return string */ - function ruri_string() + public function ruri_string() { - return '/'.implode('/', $this->rsegment_array()); + return ltrim(load_class('Router', 'core')->directory, '/').implode('/', $this->rsegments); } } -// END URI Class - -/* End of file URI.php */ -/* Location: ./system/core/URI.php */ \ No newline at end of file diff --git a/system/core/Utf8.php b/system/core/Utf8.php old mode 100755 new mode 100644 index 1a5bee1..9ee63e9 --- a/system/core/Utf8.php +++ b/system/core/Utf8.php @@ -1,19 +1,41 @@ -item('charset') == 'UTF-8' // Application charset must be UTF-8 + defined('PREG_BAD_UTF8_ERROR') // PCRE must support UTF-8 + && (ICONV_ENABLED === TRUE OR MB_ENABLED === TRUE) // iconv or mbstring must be installed + && strtoupper(config_item('charset')) === 'UTF-8' // Application charset must be UTF-8 ) { - log_message('debug', "UTF-8 Support Enabled"); - define('UTF8_ENABLED', TRUE); - - // set internal encoding for multibyte string functions if necessary - // and set a flag so we don't have to repeatedly use extension_loaded() - // or function_exists() - if (extension_loaded('mbstring')) - { - define('MB_ENABLED', TRUE); - mb_internal_encoding('UTF-8'); - } - else - { - define('MB_ENABLED', FALSE); - } + log_message('debug', 'UTF-8 Support Enabled'); } else { - log_message('debug', "UTF-8 Support Disabled"); define('UTF8_ENABLED', FALSE); + log_message('debug', 'UTF-8 Support Disabled'); } + + log_message('info', 'Utf8 Class Initialized'); } // -------------------------------------------------------------------- @@ -76,17 +82,23 @@ class CI_Utf8 { /** * Clean UTF-8 strings * - * Ensures strings are UTF-8 + * Ensures strings contain only valid UTF-8 characters. * - * @access public - * @param string + * @param string $str String to clean * @return string */ - function clean_string($str) + public function clean_string($str) { - if ($this->_is_ascii($str) === FALSE) + if ($this->is_ascii($str) === FALSE) { - $str = @iconv('UTF-8', 'UTF-8//IGNORE', $str); + 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; @@ -99,13 +111,12 @@ class CI_Utf8 { * * Removes all ASCII control characters except horizontal tabs, * line feeds, and carriage returns, as all others can cause - * problems in XML + * problems in XML. * - * @access public - * @param string + * @param string $str String to clean * @return string */ - function safe_ascii_for_xml($str) + public function safe_ascii_for_xml($str) { return remove_invisible_characters($str, FALSE); } @@ -115,29 +126,24 @@ class CI_Utf8 { /** * Convert to UTF-8 * - * Attempts to convert a string to UTF-8 + * Attempts to convert a string to UTF-8. * - * @access public - * @param string - * @param string - input encoding - * @return string + * @param string $str Input string + * @param string $encoding Input encoding + * @return string $str encoded in UTF-8 or FALSE on failure */ - function convert_to_utf8($str, $encoding) + public function convert_to_utf8($str, $encoding) { - if (function_exists('iconv')) + if (MB_ENABLED) { - $str = @iconv($encoding, 'UTF-8', $str); + return mb_convert_encoding($str, 'UTF-8', $encoding); } - elseif (function_exists('mb_convert_encoding')) + elseif (ICONV_ENABLED) { - $str = @mb_convert_encoding($str, 'UTF-8', $encoding); - } - else - { - return FALSE; + return @iconv($encoding, 'UTF-8', $str); } - return $str; + return FALSE; } // -------------------------------------------------------------------- @@ -145,21 +151,14 @@ class CI_Utf8 { /** * Is ASCII? * - * Tests if a string is standard 7-bit ASCII or not + * Tests if a string is standard 7-bit ASCII or not. * - * @access public - * @param string + * @param string $str String to check * @return bool */ - function _is_ascii($str) + public function is_ascii($str) { - return (preg_match('/[^\x00-\x7F]/S', $str) == 0); + return (preg_match('/[^\x00-\x7F]/S', $str) === 0); } - // -------------------------------------------------------------------- - } -// End Utf8 Class - -/* End of file Utf8.php */ -/* Location: ./system/core/Utf8.php */ \ No newline at end of file diff --git a/system/core/compat/hash.php b/system/core/compat/hash.php new file mode 100644 index 0000000..8f5510c --- /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/libraries/javascript/index.html b/system/core/compat/index.html old mode 100755 new mode 100644 similarity index 81% rename from system/libraries/javascript/index.html rename to system/core/compat/index.html index c942a79..b702fbc --- a/system/libraries/javascript/index.html +++ b/system/core/compat/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/core/compat/mbstring.php b/system/core/compat/mbstring.php new file mode 100644 index 0000000..552e727 --- /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 0000000..2c528fd --- /dev/null +++ b/system/core/compat/standard.php @@ -0,0 +1,182 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/DB.php b/system/database/DB.php old mode 100755 new mode 100644 index f8d0204..02e0e1d --- a/system/database/DB.php +++ b/system/database/DB.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ * * @param string|string[] $params * @param bool $query_builder_override @@ -50,18 +61,23 @@ function &DB($params = '', $query_builder_override = NULL) } include($file_path); - // Make packages contain database config files - foreach (get_instance()->load->get_package_paths() as $path) + + // Make packages contain database config files, + // given that the controller instance already exists + if (class_exists('CI_Controller', FALSE)) { - if ($path !== APPPATH) + foreach (get_instance()->load->get_package_paths() as $path) { - if (file_exists($file_path = $path.'config/'.ENVIRONMENT.'/database.php')) + if ($path !== APPPATH) { - include($file_path); - } - elseif (file_exists($file_path = $path.'config/database.php')) - { - include($file_path); + 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); + } } } } @@ -119,7 +135,7 @@ function &DB($params = '', $query_builder_override = NULL) { if (is_string($val) && in_array(strtoupper($val), array('TRUE', 'FALSE', 'NULL'))) { - $val = var_export($val); + $val = var_export($val, TRUE); } $params[$key] = $val; @@ -197,13 +213,6 @@ function &DB($params = '', $query_builder_override = NULL) } } - if ($DB->autoinit === TRUE) - { - $DB->initialize(); - } - + $DB->initialize(); return $DB; } - -/* End of file DB.php */ -/* Location: ./system/database/DB.php */ \ No newline at end of file diff --git a/system/database/DB_cache.php b/system/database/DB_cache.php old mode 100755 new mode 100644 index b855ff2..afcfc4c --- a/system/database/DB_cache.php +++ b/system/database/DB_cache.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_Cache { @@ -132,7 +143,7 @@ class CI_DB_Cache { $segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2); $filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql); - if (FALSE === ($cachedata = @file_get_contents($filepath))) + if ( ! is_file($filepath) OR FALSE === ($cachedata = file_get_contents($filepath))) { return FALSE; } @@ -156,14 +167,9 @@ class CI_DB_Cache { $dir_path = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'; $filename = md5($sql); - if ( ! is_dir($dir_path)) + if ( ! is_dir($dir_path) && ! @mkdir($dir_path, 0750)) { - if ( ! @mkdir($dir_path, 0777)) - { - return FALSE; - } - - @chmod($dir_path, 0777); + return FALSE; } if (write_file($dir_path.$filename, serialize($object)) === FALSE) @@ -171,7 +177,7 @@ class CI_DB_Cache { return FALSE; } - @chmod($dir_path.$filename, 0666); + chmod($dir_path.$filename, 0640); return TRUE; } @@ -213,6 +219,3 @@ class CI_DB_Cache { } } - -/* End of file DB_cache.php */ -/* Location: ./system/database/DB_cache.php */ \ No newline at end of file diff --git a/system/database/DB_driver.php b/system/database/DB_driver.php old mode 100755 new mode 100644 index 12ab5bb..5ae0442 --- a/system/database/DB_driver.php +++ b/system/database/DB_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ abstract class CI_DB_driver { @@ -112,15 +123,6 @@ abstract class CI_DB_driver { */ public $dbcollat = 'utf8_general_ci'; - /** - * Auto-init flag - * - * Whether to automatically initialize the DB connection. - * - * @var bool - */ - public $autoinit = TRUE; - /** * Encryption flag/data * @@ -140,7 +142,7 @@ abstract class CI_DB_driver { * * @var int */ - public $port = ''; + public $port = NULL; /** * Persistent connection flag @@ -370,7 +372,7 @@ abstract class CI_DB_driver { } } - log_message('debug', 'Database Driver Class Initialized'); + log_message('info', 'Database Driver Class Initialized'); } // -------------------------------------------------------------------- @@ -444,10 +446,24 @@ abstract class CI_DB_driver { // -------------------------------------------------------------------- + /** + * 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 resource + * @return mixed */ public function db_pconnect() { @@ -465,7 +481,7 @@ abstract class CI_DB_driver { * This is just a dummy method to allow drivers without such * functionality to not declare it, while others will override it. * - * @return void + * @return void */ public function reconnect() { @@ -479,7 +495,7 @@ abstract class CI_DB_driver { * This is just a dummy method to allow drivers without such * functionality to not declare it, while others will override it. * - * @return bool + * @return bool */ public function db_select() { @@ -488,6 +504,18 @@ abstract class CI_DB_driver { // -------------------------------------------------------------------- + /** + * Last error + * + * @return array + */ + public function error() + { + return array('code' => NULL, 'message' => NULL); + } + + // -------------------------------------------------------------------- + /** * Set client character set * @@ -631,7 +659,10 @@ abstract class CI_DB_driver { } // This will trigger a rollback if transactions are being used - $this->_trans_status = FALSE; + 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(); @@ -645,13 +676,15 @@ abstract class CI_DB_driver { // 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. - if ($this->_trans_depth !== 0) + while ($this->_trans_depth !== 0) { - do + $trans_depth = $this->_trans_depth; + $this->trans_complete(); + if ($trans_depth === $this->_trans_depth) { - $this->trans_complete(); + log_message('error', 'Database: Failure during an automated transaction commit/rollback!'); + break; } - while ($this->_trans_depth !== 0); } // Display errors @@ -749,7 +782,10 @@ abstract class CI_DB_driver { { if ( ! $this->conn_id) { - $this->initialize(); + if ( ! $this->initialize()) + { + return FALSE; + } } return $this->_execute($sql); @@ -772,10 +808,13 @@ abstract class CI_DB_driver { /** * Enable/disable Transaction Strict Mode + * * When strict mode is enabled, if you are running multiple groups of - * transactions, if one group fails all groups will be rolled back. - * If strict mode is disabled, each group is treated autonomously, meaning - * a failure of one group will not affect any others + * 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 @@ -791,7 +830,7 @@ abstract class CI_DB_driver { * Start Transaction * * @param bool $test_mode = FALSE - * @return void + * @return bool */ public function trans_start($test_mode = FALSE) { @@ -800,15 +839,7 @@ abstract class CI_DB_driver { return FALSE; } - // When transactions are nested we only begin/commit/rollback the outermost ones - if ($this->_trans_depth > 0) - { - $this->_trans_depth += 1; - return; - } - - $this->trans_begin($test_mode); - $this->_trans_depth += 1; + return $this->trans_begin($test_mode); } // -------------------------------------------------------------------- @@ -825,25 +856,14 @@ abstract class CI_DB_driver { return FALSE; } - // When transactions are nested we only begin/commit/rollback the outermost ones - if ($this->_trans_depth > 1) - { - $this->_trans_depth -= 1; - return TRUE; - } - else - { - $this->_trans_depth = 0; - } - // 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. + // the _trans_status flag so that subsequent groups of + // transactions will be permitted. if ($this->trans_strict === FALSE) { $this->_trans_status = TRUE; @@ -853,8 +873,7 @@ abstract class CI_DB_driver { return FALSE; } - $this->trans_commit(); - return TRUE; + return $this->trans_commit(); } // -------------------------------------------------------------------- @@ -871,6 +890,88 @@ abstract class CI_DB_driver { // -------------------------------------------------------------------- + /** + * 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 * @@ -880,7 +981,7 @@ abstract class CI_DB_driver { */ public function compile_binds($sql, $binds) { - if (empty($binds) OR empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE) + if (empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE) { return $sql; } @@ -900,7 +1001,7 @@ abstract class CI_DB_driver { $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)) + if ($c = preg_match_all("/'[^']*'|\"[^\"]*\"/i", $sql, $matches)) { $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', str_replace($matches[0], @@ -922,7 +1023,12 @@ abstract class CI_DB_driver { do { $c--; - $sql = substr_replace($sql, $this->escape($binds[$c]), $matches[0][$c][1], $ml); + $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); @@ -939,7 +1045,7 @@ abstract class CI_DB_driver { */ 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)\s/i', $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); } // -------------------------------------------------------------------- @@ -948,7 +1054,7 @@ abstract class CI_DB_driver { * Calculate the aggregate query elapsed time * * @param int The number of decimal places - * @return int + * @return string */ public function elapsed_time($decimals = 6) { @@ -992,7 +1098,12 @@ abstract class CI_DB_driver { */ public function escape($str) { - if (is_string($str) OR (is_object($str) && method_exists($str, '__toString'))) + 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)."'"; } @@ -1013,7 +1124,7 @@ abstract class CI_DB_driver { /** * Escape String * - * @param string $str + * @param string|string[] $str Input string * @param bool $like Whether or not the string will be used in a LIKE condition * @return string */ @@ -1063,14 +1174,14 @@ abstract class CI_DB_driver { // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { - return str_replace("'", "''", remove_invisible_characters($str)); + return str_replace("'", "''", remove_invisible_characters($str, FALSE)); } // -------------------------------------------------------------------- @@ -1081,10 +1192,10 @@ abstract class CI_DB_driver { * Retrieves the primary key. It assumes that the row in the first * position is the primary key * - * @param string the table name + * @param string $table Table name * @return string */ - public function primary($table = '') + public function primary($table) { $fields = $this->list_fields($table); return is_array($fields) ? current($fields) : FALSE; @@ -1192,29 +1303,18 @@ abstract class CI_DB_driver { /** * Fetch Field Names * - * @param string the table name + * @param string $table Table name * @return array */ - public function list_fields($table = '') + public function list_fields($table) { - // Is there a cached result? - if (isset($this->data_cache['field_names'][$table])) - { - return $this->data_cache['field_names'][$table]; - } - - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (FALSE === ($sql = $this->_list_columns($table))) { return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $query = $this->query($sql); - $this->data_cache['field_names'][$table] = array(); + $fields = array(); foreach ($query->result_array() as $row) { @@ -1236,10 +1336,10 @@ abstract class CI_DB_driver { } } - $this->data_cache['field_names'][$table][] = $row[$key]; + $fields[] = $row[$key]; } - return $this->data_cache['field_names'][$table]; + return $fields; } // -------------------------------------------------------------------- @@ -1261,18 +1361,13 @@ abstract class CI_DB_driver { /** * Returns an object with field data * - * @param string the table name - * @return object + * @param string $table the table name + * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE))); - return $query->field_data(); + return ($query) ? $query->field_data() : FALSE; } // -------------------------------------------------------------------- @@ -1427,7 +1522,7 @@ abstract class CI_DB_driver { return 'UPDATE '.$table.' SET '.implode(', ', $valstr) .$this->_compile_wh('qb_where') .$this->_compile_order_by() - .($this->qb_limit ? ' LIMIT '.$this->qb_limit : ''); + .($this->qb_limit !== FALSE ? ' LIMIT '.$this->qb_limit : ''); } // -------------------------------------------------------------------- @@ -1461,18 +1556,18 @@ abstract class CI_DB_driver { ? '\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+\S+\s+AND\s+\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'] + '\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'] ); } @@ -1618,7 +1713,7 @@ abstract class CI_DB_driver { /** * Close DB Connection * - * This method would be overriden by most of the drivers. + * This method would be overridden by most of the drivers. * * @return void */ @@ -1693,7 +1788,7 @@ abstract class CI_DB_driver { * the table prefix onto it. Some logic is necessary in order to deal with * column names that include the path. Consider a query like this: * - * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table + * SELECT hostname.database.table.column AS c FROM hostname.database.table * * Or a query with aliasing: * @@ -1735,13 +1830,13 @@ abstract class CI_DB_driver { // // Added exception for single quotes as well, we don't want to alter // literal strings. -- Narf - if (strpos($item, '(') !== FALSE OR strpos($item, "'") !== FALSE) + if (strcspn($item, "()'") !== strlen($item)) { return $item; } // Convert tabs or multiple spaces into single spaces - $item = preg_replace('/\s+/', ' ', $item); + $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 @@ -1769,12 +1864,15 @@ abstract class CI_DB_driver { // with an alias. While we're at it, we will escape the components if (strpos($item, '.') !== FALSE) { - $parts = explode('.', $item); + $parts = explode('.', $item); // Does the first segment of the exploded item match // one of the aliases previously identified? If so, // we have nothing more to do other than escape the item - if (in_array($parts[0], $this->qb_aliased_tables)) + // + // 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) { @@ -1822,15 +1920,19 @@ abstract class CI_DB_driver { $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 !== '' && strpos($parts[$i], $this->swap_pre) === 0) + if ($this->swap_pre !== '' && preg_match('#^'.$ec.preg_quote($this->swap_pre).'#', $parts[$i])) { - $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $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 - elseif (strpos($parts[$i], $this->dbprefix) !== 0) + else { - $parts[$i] = $this->dbprefix.$parts[$i]; + preg_match('#^'.$ec.preg_quote($this->dbprefix).'#', $parts[$i]) OR $parts[$i] = $this->dbprefix.$parts[$i]; } // Put the parts back together @@ -1881,6 +1983,3 @@ abstract class CI_DB_driver { } } - -/* End of file DB_driver.php */ -/* Location: ./system/database/DB_driver.php */ \ No newline at end of file diff --git a/system/database/DB_forge.php b/system/database/DB_forge.php old mode 100755 new mode 100644 index 111546e..85b58fd --- a/system/database/DB_forge.php +++ b/system/database/DB_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ abstract class CI_DB_forge { @@ -132,7 +143,7 @@ abstract class CI_DB_forge { protected $_unsigned = TRUE; /** - * NULL value representatin in CREATE/ALTER TABLE statements + * NULL value representation in CREATE/ALTER TABLE statements * * @var string */ @@ -156,7 +167,7 @@ abstract class CI_DB_forge { public function __construct(&$db) { $this->db =& $db; - log_message('debug', 'Database Forge Class Initialized'); + log_message('info', 'Database Forge Class Initialized'); } // -------------------------------------------------------------------- @@ -173,7 +184,7 @@ abstract class CI_DB_forge { { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } - elseif ( ! $this->db->query(sprintf($this->_create_database, $db_name, $this->db->char_set, $this->db->dbcollat))) + 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; } @@ -196,16 +207,11 @@ abstract class CI_DB_forge { */ public function drop_database($db_name) { - if ($db_name === '') - { - show_error('A table name is required for that operation.'); - return FALSE; - } - elseif ($this->_drop_database === FALSE) + 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, $db_name))) + 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; } @@ -231,13 +237,14 @@ abstract class CI_DB_forge { * @param bool $primary * @return CI_DB_forge */ - public function add_key($key = '', $primary = FALSE) + public function add_key($key, $primary = FALSE) { - if (empty($key)) - { - show_error('Key information is required for that operation.'); - } - + // 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) @@ -268,13 +275,8 @@ abstract class CI_DB_forge { * @param array $field * @return CI_DB_forge */ - public function add_field($field = '') + public function add_field($field) { - if (empty($field)) - { - show_error('Field information is required.'); - } - if (is_string($field)) { if ($field === 'id') @@ -317,7 +319,7 @@ abstract class CI_DB_forge { * @param array $attributes Associative array of table attributes * @return bool */ - public function create_table($table = '', $if_not_exists = FALSE, array $attributes = array()) + public function create_table($table, $if_not_exists = FALSE, array $attributes = array()) { if ($table === '') { @@ -346,7 +348,10 @@ abstract class CI_DB_forge { if (($result = $this->db->query($sql)) !== FALSE) { - empty($this->db->data_cache['table_names']) OR $this->db->data_cache['table_names'][] = $table; + 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)) @@ -380,10 +385,8 @@ abstract class CI_DB_forge { { return TRUE; } - else - { - $if_not_exists = FALSE; - } + + $if_not_exists = FALSE; } $sql = ($if_not_exists) @@ -457,12 +460,7 @@ abstract class CI_DB_forge { return ($this->db->db_debug) ? $this->db->display_error('db_table_name_required') : FALSE; } - $query = $this->_drop_table($this->db->dbprefix.$table_name, $if_exists); - if ($query === FALSE) - { - return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; - } - elseif ($query === TRUE) + if (($query = $this->_drop_table($this->db->dbprefix.$table_name, $if_exists)) === TRUE) { return TRUE; } @@ -491,7 +489,7 @@ abstract class CI_DB_forge { * * @param string $table Table name * @param bool $if_exists Whether to add an IF EXISTS condition - * @return string + * @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) { @@ -564,18 +562,10 @@ abstract class CI_DB_forge { * @param string $_after Column for AFTER clause (deprecated) * @return bool */ - public function add_column($table = '', $field = array(), $_after = NULL) + public function add_column($table, $field, $_after = NULL) { - if ($table === '') - { - show_error('A table name is required for that operation.'); - } - // Work-around for literal column definitions - if ( ! is_array($field)) - { - $field = array($field); - } + is_array($field) OR $field = array($field); foreach (array_keys($field) as $k) { @@ -615,18 +605,8 @@ abstract class CI_DB_forge { * @param string $column_name Column name * @return bool */ - public function drop_column($table = '', $column_name = '') + public function drop_column($table, $column_name) { - if ($table === '') - { - show_error('A table name is required for that operation.'); - } - - if ($column_name === '') - { - show_error('A column name is required for that operation.'); - } - $sql = $this->_alter_table('DROP', $this->db->dbprefix.$table, $column_name); if ($sql === FALSE) { @@ -645,18 +625,10 @@ abstract class CI_DB_forge { * @param string $field Column definition * @return bool */ - public function modify_column($table = '', $field = array()) + public function modify_column($table, $field) { - if ($table === '') - { - show_error('A table name is required for that operation.'); - } - // Work-around for literal column definitions - if ( ! is_array($field)) - { - $field = array($field); - } + is_array($field) OR $field = array($field); foreach (array_keys($field) as $k) { @@ -755,7 +727,7 @@ abstract class CI_DB_forge { 'type' => isset($attributes['TYPE']) ? $attributes['TYPE'] : NULL, 'length' => '', 'unsigned' => '', - 'null' => '', + 'null' => NULL, 'unique' => '', 'default' => '', 'auto_increment' => '', @@ -797,6 +769,11 @@ abstract class CI_DB_forge { $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'])) @@ -804,10 +781,6 @@ abstract class CI_DB_forge { case 'ENUM': case 'SET': $attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']); - $field['length'] = is_array($attributes['CONSTRAINT']) - ? "('".implode("','", $attributes['CONSTRAINT'])."')" - : '('.$attributes['CONSTRAINT'].')'; - break; default: $field['length'] = is_array($attributes['CONSTRAINT']) ? '('.implode(',', $attributes['CONSTRAINT']).')' @@ -853,7 +826,7 @@ abstract class CI_DB_forge { */ protected function _attr_type(&$attributes) { - // Usually overriden by drivers + // Usually overridden by drivers } // -------------------------------------------------------------------- @@ -929,7 +902,7 @@ abstract class CI_DB_forge { $field['default'] = empty($this->_null) ? '' : $this->_default.$this->_null; // Override the NULL attribute if that's our default - $attributes['NULL'] = NULL; + $attributes['NULL'] = TRUE; $field['null'] = empty($this->_null) ? '' : ' '.$this->_null; } else @@ -1007,8 +980,8 @@ abstract class CI_DB_forge { /** * Process indexes * - * @param string $table - * @return string + * @param string $table Table name + * @return string[] list of SQL statements */ protected function _process_indexes($table) { @@ -1058,6 +1031,3 @@ abstract class CI_DB_forge { } } - -/* End of file DB_forge.php */ -/* Location: ./system/database/DB_forge.php */ \ No newline at end of file diff --git a/system/database/DB_query_builder.php b/system/database/DB_query_builder.php old mode 100755 new mode 100644 index 085c615..f35b9fd --- a/system/database/DB_query_builder.php +++ b/system/database/DB_query_builder.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -35,7 +46,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ abstract class CI_DB_query_builder extends CI_DB_driver { @@ -138,6 +149,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { */ protected $qb_set = array(); + /** + * QB data set for update_batch() + * + * @var array + */ + protected $qb_set_ub = array(); + /** * QB aliased tables list * @@ -196,6 +214,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { */ protected $qb_cache_join = array(); + /** + * QB Cache aliased tables list + * + * @var array + */ + protected $qb_cache_aliased_tables = array(); + /** * QB Cache WHERE data * @@ -520,40 +545,47 @@ abstract class CI_DB_query_builder extends CI_DB_driver { is_bool($escape) OR $escape = $this->_protect_identifiers; - // Split multiple conditions - if ($escape === TRUE && preg_match_all('/\sAND\s|\sOR\s/i', $cond, $m, PREG_OFFSET_CAPTURE)) - { - $newcond = ''; - $m[0][] = array('', strlen($cond)); - - for ($i = 0, $c = count($m[0]), $s = 0; - $i < $c; - $s = $m[0][$i][1] + strlen($m[0][$i][0]), $i++) - { - $temp = substr($cond, $s, ($m[0][$i][1] - $s)); - - $newcond .= preg_match("/([\[\]\w\.'-]+)(\s*[^\"\[`'\w]+\s*)(.+)/i", $temp, $match) - ? $this->protect_identifiers($match[1]).$match[2].$this->protect_identifiers($match[3]) - : $temp; - - $newcond .= $m[0][$i][0]; - } - - $cond = ' ON '.$newcond; - } - // Split apart the condition and protect the identifiers - elseif ($escape === TRUE && preg_match("/([\[\]\w\.'-]+)(\s*[^\"\[`'\w]+\s*)(.+)/i", $cond, $match)) - { - $cond = ' ON '.$this->protect_identifiers($match[1]).$match[2].$this->protect_identifiers($match[3]); - } - elseif ( ! $this->_has_operator($cond)) + if ( ! $this->_has_operator($cond)) { $cond = ' USING ('.($escape ? $this->escape_identifiers($cond) : $cond).')'; } - else + 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) @@ -635,7 +667,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $key = array($key => $value); } - // If the escape value was not set will will base it on the global setting + // 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) @@ -648,7 +680,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { { if ($escape === TRUE) { - $v = ' '.$this->escape($v); + $v = $this->escape($v); } if ( ! $this->_has_operator($k)) @@ -661,11 +693,16 @@ abstract class CI_DB_query_builder extends CI_DB_driver { // 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'); + } - $this->{$qb_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape); + ${$qb_key} = array('condition' => $prefix.$k, 'value' => $v, 'escape' => $escape); + $this->{$qb_key}[] = ${$qb_key}; if ($this->qb_caching === TRUE) { - $this->{$qb_cache_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape); + $this->{$qb_cache_key}[] = ${$qb_key}; $this->qb_cache_exists[] = substr($qb_key, 3); } @@ -779,15 +816,26 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $not = ($not) ? ' NOT' : ''; - $where_in = array(); - foreach ($values as $value) + if ($escape === TRUE) { - $where_in[] = $this->escape($value); + $where_in = array(); + foreach ($values as $value) + { + $where_in[] = $this->escape($value); + } + } + else + { + $where_in = array_values($values); } - $prefix = (count($this->qb_where) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); + $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 ); @@ -903,41 +951,47 @@ abstract class CI_DB_query_builder extends CI_DB_driver { } 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); - $v = $this->escape_like_str($v); + if ($escape === TRUE) + { + $v = $this->escape_like_str($v); + } - if ($side === 'none') + switch ($side) { - $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}'"; - } - elseif ($side === 'before') - { - $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}'"; - } - elseif ($side === 'after') - { - $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}%'"; - } - else - { - $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}%'"; + 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 ($this->_like_escape_str !== '') + if ($escape === TRUE && $this->_like_escape_str !== '') { - $like_statement .= sprintf($this->_like_escape_str, $this->_like_escape_chr); + $v .= sprintf($this->_like_escape_str, $this->_like_escape_chr); } - $this->qb_where[] = array('condition' => $like_statement, 'escape' => $escape); + $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[] = array('condition' => $like_statement, 'escape' => $escape); + $this->qb_cache_where[] = $qb_where; $this->qb_cache_exists[] = 'where'; } } @@ -962,6 +1016,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $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 ); @@ -1022,6 +1077,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $this->qb_where_group_started = FALSE; $where = array( 'condition' => str_repeat(' ', $this->qb_where_group_count--).')', + 'value' => NULL, 'escape' => FALSE ); @@ -1108,7 +1164,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param string $key * @param string $value * @param bool $escape - * @return object + * @return CI_DB_query_builder */ public function having($key, $value = NULL, $escape = NULL) { @@ -1125,7 +1181,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param string $key * @param string $value * @param bool $escape - * @return object + * @return CI_DB_query_builder */ public function or_having($key, $value = NULL, $escape = NULL) { @@ -1200,7 +1256,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param int $offset OFFSET value * @return CI_DB_query_builder */ - public function limit($value, $offset = FALSE) + public function limit($value, $offset = 0) { is_null($value) OR $this->qb_limit = (int) $value; empty($offset) OR $this->qb_offset = (int) $offset; @@ -1234,7 +1290,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { */ protected function _limit($sql) { - return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').$this->qb_limit; + return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').(int) $this->qb_limit; } // -------------------------------------------------------------------- @@ -1277,7 +1333,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * 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 vaules alone + * @param bool TRUE: resets QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_select($table = '', $reset = TRUE) @@ -1309,7 +1365,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param string the table * @param string the limit clause * @param string the offset clause - * @return object + * @return CI_DB_result */ public function get($table = '', $limit = NULL, $offset = NULL) { @@ -1338,9 +1394,10 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * returned by an Query Builder query. * * @param string + * @param bool the reset clause * @return int */ - public function count_all_results($table = '') + public function count_all_results($table = '', $reset = TRUE) { if ($table !== '') { @@ -1348,10 +1405,26 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $this->from($table); } - $result = ($this->qb_distinct === TRUE) + // 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'))); - $this->_reset_select(); + + if ($reset === TRUE) + { + $this->_reset_select(); + } + else + { + $this->qb_orderby = $qb_orderby; + $this->qb_cache_orderby = $qb_cache_orderby; + } if ($result->num_rows() === 0) { @@ -1365,7 +1438,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { // -------------------------------------------------------------------- /** - * Get_Where + * get_where() * * Allows the where clause, limit and offset to be added directly * @@ -1373,7 +1446,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param string $where * @param int $limit * @param int $offset - * @return object + * @return CI_DB_result */ public function get_where($table = '', $where = NULL, $limit = NULL, $offset = NULL) { @@ -1409,20 +1482,26 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @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) + public function insert_batch($table, $set = NULL, $escape = NULL, $batch_size = 100) { - if ($set !== NULL) + 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 (count($this->qb_set) === 0) - { - // No valid data array. Folds in cases where keys and values did not match up - return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; - } - - if ($table === '') + if (strlen($table) === 0) { if ( ! isset($this->qb_from[0])) { @@ -1434,10 +1513,12 @@ abstract class CI_DB_query_builder extends CI_DB_driver { // Batch this baby $affected_rows = 0; - for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100) + for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size) { - $this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, 100))); - $affected_rows += $this->affected_rows(); + 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(); @@ -1482,7 +1563,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { is_bool($escape) OR $escape = $this->_protect_identifiers; - $keys = array_keys($this->_object_to_array(current($key))); + $keys = array_keys($this->_object_to_array(reset($key))); sort($keys); foreach ($key as $row) @@ -1563,7 +1644,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @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 object + * @return bool TRUE on success, FALSE on failure */ public function insert($table = '', $set = NULL, $escape = NULL) { @@ -1629,7 +1710,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * @param string the table to replace data into * @param array an associative array of insert values - * @return object + * @return bool TRUE on success, FALSE on failure */ public function replace($table = '', $set = NULL) { @@ -1684,7 +1765,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * - * Note: This is only used (and overriden) by MySQL and CUBRID. + * Note: This is only used (and overridden) by MySQL and CUBRID. * * @return string */ @@ -1714,7 +1795,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { return FALSE; } - $sql = $this->_update($this->protect_identifiers($this->qb_from[0], TRUE, NULL, FALSE), $this->qb_set); + $sql = $this->_update($this->qb_from[0], $this->qb_set); if ($reset === TRUE) { @@ -1735,7 +1816,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param array $set An associative array of update values * @param mixed $where * @param int $limit - * @return object + * @return bool TRUE on success, FALSE on failure */ public function update($table = '', $set = NULL, $where = NULL, $limit = NULL) { @@ -1762,7 +1843,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $this->limit($limit); } - $sql = $this->_update($this->protect_identifiers($this->qb_from[0], TRUE, NULL, FALSE), $this->qb_set); + $sql = $this->_update($this->qb_from[0], $this->qb_set); $this->_reset_write(); return $this->query($sql); } @@ -1779,7 +1860,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param string the table to update data on * @return bool */ - protected function _validate_update($table = '') + protected function _validate_update($table) { if (count($this->qb_set) === 0) { @@ -1788,7 +1869,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { if ($table !== '') { - $this->qb_from[0] = $table; + $this->qb_from = array($this->protect_identifiers($table, TRUE, NULL, FALSE)); } elseif ( ! isset($this->qb_from[0])) { @@ -1810,7 +1891,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * @param string the where key * @return int number of rows affected or FALSE on failure */ - public function update_batch($table = '', $set = NULL, $index = NULL) + public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100) { // Combine any cached components with the current statements $this->_merge_cache(); @@ -1820,17 +1901,24 @@ abstract class CI_DB_query_builder extends CI_DB_driver { return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE; } - if ($set !== NULL) + 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 (count($this->qb_set) === 0) - { - return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; - } - - if ($table === '') + if (strlen($table) === 0) { if ( ! isset($this->qb_from[0])) { @@ -1842,10 +1930,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { // Batch this baby $affected_rows = 0; - for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100) + for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size) { - $this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set, $i, 100), $this->protect_identifiers($index))); - $affected_rows += $this->affected_rows(); + 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(); } @@ -1870,13 +1961,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $ids = array(); foreach ($values as $key => $val) { - $ids[] = $val[$index]; + $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { - $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; + $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['field'].' = '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } @@ -1889,7 +1980,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { .'ELSE '.$k.' END, '; } - $this->where($index.' IN('.implode(',', $ids).')', NULL, FALSE); + $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } @@ -1926,7 +2017,10 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $index_set = TRUE; } - $clean[$this->protect_identifiers($k2, FALSE, $escape)] = ($escape === FALSE) ? $v2 : $this->escape($v2); + $clean[$k2] = array( + 'field' => $this->protect_identifiers($k2, FALSE, $escape), + 'value' => ($escape === FALSE ? $v2 : $this->escape($v2)) + ); } if ($index_set === FALSE) @@ -1934,7 +2028,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { return $this->display_error('db_batch_missing_index'); } - $this->qb_set[] = $clean; + $this->qb_set_ub[] = $clean; } return $this; @@ -1948,7 +2042,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * Compiles a delete string and runs "DELETE FROM table" * * @param string the table to empty - * @return object + * @return bool TRUE on success, FALSE on failure */ public function empty_table($table = '') { @@ -1981,7 +2075,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * This function maps to "DELETE FROM table" * * @param string the table to truncate - * @return object + * @return bool TRUE on success, FALSE on failure */ public function truncate($table = '') { @@ -2070,10 +2164,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { } elseif (is_array($table)) { + empty($where) && $reset_data = FALSE; + foreach ($table as $single_table) { $this->delete($single_table, $where, $limit, $reset_data); } + return; } else @@ -2118,7 +2215,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { protected function _delete($table) { return 'DELETE FROM '.$table.$this->_compile_wh('qb_where') - .($this->qb_limit ? ' LIMIT '.$this->qb_limit : ''); + .($this->qb_limit !== FALSE ? ' LIMIT '.$this->qb_limit : ''); } // -------------------------------------------------------------------- @@ -2194,9 +2291,14 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $table = trim(strrchr($table, ' ')); // Store the alias, if it doesn't already exist - if ( ! in_array($table, $this->qb_aliased_tables)) + 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'; + } } } } @@ -2233,7 +2335,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { else { // Cycle through the "select" portion of the query and prep each column name. - // The reason we protect identifiers here rather then in the select() function + // 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) { @@ -2263,7 +2365,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { .$this->_compile_order_by(); // ORDER BY // LIMIT - if ($this->qb_limit) + if ($this->qb_limit !== FALSE OR $this->qb_offset) { return $this->_limit($sql."\n"); } @@ -2278,7 +2380,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Escapes identifiers in WHERE and HAVING statements at execution time. * - * Required so that aliases are tracked properly, regardless of wether + * 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. * @@ -2298,13 +2400,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { } elseif ($this->{$qb_key}[$i]['escape'] === FALSE) { - $this->{$qb_key}[$i] = $this->{$qb_key}[$i]['condition']; + $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', + '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i', $this->{$qb_key}[$i]['condition'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY @@ -2337,7 +2439,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { .' '.trim($matches[3]).$matches[4].$matches[5]; } - $this->{$qb_key}[$i] = implode('', $conditions); + $this->{$qb_key}[$i] = implode('', $conditions).(isset($this->{$qb_key}[$i]['value']) ? ' '.$this->{$qb_key}[$i]['value'] : ''); } return ($qb_key === 'qb_having' ? "\nHAVING " : "\nWHERE ") @@ -2354,7 +2456,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Escapes identifiers in GROUP BY statements at execution time. * - * Required so that aliases are tracked properly, regardless of wether + * 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. * @@ -2390,7 +2492,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Escapes identifiers in ORDER BY statements at execution time. * - * Required so that aliases are tracked properly, regardless of wether + * 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. * @@ -2398,26 +2500,27 @@ abstract class CI_DB_query_builder extends CI_DB_driver { */ protected function _compile_order_by() { - if (is_array($this->qb_orderby) && count($this->qb_orderby) > 0) + if (empty($this->qb_orderby)) { - for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++) - { - 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']); - } + return ''; + } - $this->qb_orderby[$i] = $this->qb_orderby[$i]['field'].$this->qb_orderby[$i]['direction']; + for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++) + { + if (is_string($this->qb_orderby[$i])) + { + continue; } - return $this->qb_orderby = "\nORDER BY ".implode(', ', $this->qb_orderby); - } - elseif (is_string($this->qb_orderby)) - { - return $this->qb_orderby; + 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 ''; + return "\nORDER BY ".implode(', ', $this->qb_orderby); } // -------------------------------------------------------------------- @@ -2494,11 +2597,12 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Starts QB caching * - * @return void + * @return CI_DB_query_builder */ public function start_cache() { $this->qb_caching = TRUE; + return $this; } // -------------------------------------------------------------------- @@ -2508,11 +2612,12 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Stops QB caching * - * @return void + * @return CI_DB_query_builder */ public function stop_cache() { $this->qb_caching = FALSE; + return $this; } // -------------------------------------------------------------------- @@ -2522,7 +2627,7 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Empties the QB cache * - * @return void + * @return CI_DB_query_builder */ public function flush_cache() { @@ -2536,8 +2641,11 @@ abstract class CI_DB_query_builder extends CI_DB_driver { 'qb_cache_orderby' => array(), 'qb_cache_set' => array(), 'qb_cache_exists' => array(), - 'qb_cache_no_escape' => array() + 'qb_cache_no_escape' => array(), + 'qb_cache_aliased_tables' => array() )); + + return $this; } // -------------------------------------------------------------------- @@ -2585,13 +2693,6 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $this->qb_no_escape = $qb_no_escape; } } - - // If we are "protecting identifiers" we need to examine the "from" - // portion of the query to determine if there are any aliases - if ($this->_protect_identifiers === TRUE && count($this->qb_cache_from) > 0) - { - $this->_track_aliases($this->qb_from); - } } // -------------------------------------------------------------------- @@ -2631,12 +2732,13 @@ abstract class CI_DB_query_builder extends CI_DB_driver { * * Publicly-visible method to reset the QB values. * - * @return void + * @return CI_DB_query_builder */ public function reset_query() { $this->_reset_select(); $this->_reset_write(); + return $this; } // -------------------------------------------------------------------- @@ -2665,20 +2767,19 @@ abstract class CI_DB_query_builder extends CI_DB_driver { 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 - ) - ); + '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 + )); } // -------------------------------------------------------------------- @@ -2694,17 +2795,14 @@ abstract class CI_DB_query_builder extends CI_DB_driver { { $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 - ) - ); + )); } } - -/* End of file DB_query_builder.php */ -/* Location: ./system/database/DB_query_builder.php */ \ No newline at end of file diff --git a/system/database/DB_result.php b/system/database/DB_result.php old mode 100755 new mode 100644 index b02d016..0dbac16 --- a/system/database/DB_result.php +++ b/system/database/DB_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -35,7 +46,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_result { @@ -152,10 +163,8 @@ class CI_DB_result { { return $this->result_object(); } - else - { - return $this->custom_result_object($type); - } + + return $this->custom_result_object($type); } // -------------------------------------------------------------------- @@ -325,7 +334,8 @@ class CI_DB_result { if ($type === 'object') return $this->row_object($n); elseif ($type === 'array') return $this->row_array($n); - else return $this->custom_row_object($n, $type); + + return $this->custom_row_object($n, $type); } // -------------------------------------------------------------------- @@ -545,7 +555,7 @@ class CI_DB_result { /** * Number of fields in the result set * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @return int */ @@ -561,7 +571,7 @@ class CI_DB_result { * * Generates an array of column names. * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @return array */ @@ -577,7 +587,7 @@ class CI_DB_result { * * Generates an array of objects containing field meta-data. * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @return array */ @@ -591,7 +601,7 @@ class CI_DB_result { /** * Free the result * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @return void */ @@ -609,7 +619,7 @@ class CI_DB_result { * this internally before fetching results to make sure the * result set starts at zero. * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @param int $n * @return bool @@ -626,7 +636,7 @@ class CI_DB_result { * * Returns the result set as an array. * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @return array */ @@ -642,17 +652,14 @@ class CI_DB_result { * * Returns the result set as an object. * - * Overriden by driver result classes. + * Overridden by driver result classes. * * @param string $class_name * @return object */ protected function _fetch_object($class_name = 'stdClass') { - return array(); + return new $class_name(); } } - -/* End of file DB_result.php */ -/* Location: ./system/database/DB_result.php */ \ No newline at end of file diff --git a/system/database/DB_utility.php b/system/database/DB_utility.php old mode 100755 new mode 100644 index a696112..6642fda --- a/system/database/DB_utility.php +++ b/system/database/DB_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ abstract class CI_DB_utility { @@ -76,7 +87,7 @@ abstract class CI_DB_utility { public function __construct(&$db) { $this->db =& $db; - log_message('debug', 'Database Utility Class Initialized'); + log_message('info', 'Database Utility Class Initialized'); } // -------------------------------------------------------------------- @@ -238,16 +249,17 @@ abstract class CI_DB_utility { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim; } - $out = substr(rtrim($out), 0, -strlen($delim)).$newline; + $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) { - $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim; + $line[] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure; } - $out = substr(rtrim($out), 0, -strlen($delim)).$newline; + $out .= implode($delim, $line).$newline; } return $out; @@ -305,7 +317,7 @@ abstract class CI_DB_utility { * Database Backup * * @param array $params - * @return void + * @return string */ public function backup($params = array()) { @@ -410,6 +422,3 @@ abstract class CI_DB_utility { } } - -/* End of file DB_utility.php */ -/* Location: ./system/database/DB_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/cubrid/cubrid_driver.php b/system/database/drivers/cubrid/cubrid_driver.php old mode 100755 new mode 100644 index 138b0ed..b3b436f --- a/system/database/drivers/cubrid/cubrid_driver.php +++ b/system/database/drivers/cubrid/cubrid_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author Esen Sagynov - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_driver extends CI_DB { @@ -152,10 +163,6 @@ class CI_DB_cubrid_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } return ( ! $this->conn_id OR ($version = cubrid_get_server_info($this->conn_id)) === FALSE) ? FALSE @@ -180,25 +187,17 @@ class CI_DB_cubrid_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if (($autocommit = cubrid_get_autocommit($this->conn_id)) === NULL) { - return TRUE; + return FALSE; } - - // 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 (cubrid_get_autocommit($this->conn_id)) + elseif ($autocommit === TRUE) { - cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_FALSE); + return cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_FALSE); } return TRUE; @@ -211,19 +210,16 @@ class CI_DB_cubrid_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if ( ! cubrid_commit($this->conn_id)) { - return TRUE; + return FALSE; } - cubrid_commit($this->conn_id); - if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) { - cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); + return cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); } return TRUE; @@ -236,16 +232,13 @@ class CI_DB_cubrid_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if ( ! cubrid_rollback($this->conn_id)) { - return TRUE; + return FALSE; } - cubrid_rollback($this->conn_id); - if ($this->auto_commit && ! cubrid_get_autocommit($this->conn_id)) { cubrid_set_autocommit($this->conn_id, CUBRID_AUTOCOMMIT_TRUE); @@ -257,21 +250,14 @@ class CI_DB_cubrid_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { - if (function_exists('cubrid_real_escape_string') && - (is_resource($this->conn_id) - OR (get_resource_type($this->conn_id) === 'Unknown' && preg_match('/Resource id #/', strval($this->conn_id))))) - { - return cubrid_real_escape_string($str, $this->conn_id); - } - - return addslashes($str); + return cubrid_real_escape_string($str, $this->conn_id); } // -------------------------------------------------------------------- @@ -343,13 +329,8 @@ class CI_DB_cubrid_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; @@ -380,7 +361,7 @@ class CI_DB_cubrid_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -422,6 +403,3 @@ class CI_DB_cubrid_driver extends CI_DB { } } - -/* End of file cubrid_driver.php */ -/* Location: ./system/database/drivers/cubrid/cubrid_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/cubrid/cubrid_forge.php b/system/database/drivers/cubrid/cubrid_forge.php old mode 100755 new mode 100644 index 807dd6d..69b53dd --- a/system/database/drivers/cubrid/cubrid_forge.php +++ b/system/database/drivers/cubrid/cubrid_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author Esen Sagynov - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_forge extends CI_DB_forge { @@ -167,6 +178,9 @@ class CI_DB_cubrid_forge extends CI_DB_forge { $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; + case 'LONGTEXT': + $attributes['TYPE'] = 'STRING'; + return; default: return; } } @@ -214,6 +228,3 @@ class CI_DB_cubrid_forge extends CI_DB_forge { } } - -/* End of file cubrid_forge.php */ -/* Location: ./system/database/drivers/cubrid/cubrid_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/cubrid/cubrid_result.php b/system/database/drivers/cubrid/cubrid_result.php old mode 100755 new mode 100644 index d2bdeb0..75d7025 --- a/system/database/drivers/cubrid/cubrid_result.php +++ b/system/database/drivers/cubrid/cubrid_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author Esen Sagynov - * @link http://codeigniter.com/user_guide/database/ - * @since 2.1 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_result extends CI_DB_result { @@ -165,6 +175,3 @@ class CI_DB_cubrid_result extends CI_DB_result { } } - -/* End of file cubrid_result.php */ -/* Location: ./system/database/drivers/cubrid/cubrid_result.php */ \ No newline at end of file diff --git a/system/database/drivers/cubrid/cubrid_utility.php b/system/database/drivers/cubrid/cubrid_utility.php old mode 100755 new mode 100644 index 54e6b4a..ccf794b --- a/system/database/drivers/cubrid/cubrid_utility.php +++ b/system/database/drivers/cubrid/cubrid_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author Esen Sagynov - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_cubrid_utility extends CI_DB_utility { @@ -66,6 +77,3 @@ class CI_DB_cubrid_utility extends CI_DB_utility { return $this->db->display_error('db_unsupported_feature'); } } - -/* End of file cubrid_utility.php */ -/* Location: ./system/database/drivers/cubrid/cubrid_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/cubrid/index.html b/system/database/drivers/cubrid/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/cubrid/index.html +++ b/system/database/drivers/cubrid/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/ibase/ibase_driver.php b/system/database/drivers/ibase/ibase_driver.php old mode 100755 new mode 100644 index b19985c..27e87d4 --- a/system/database/drivers/ibase/ibase_driver.php +++ b/system/database/drivers/ibase/ibase_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_ibase_driver extends CI_DB { @@ -115,7 +126,7 @@ class CI_DB_ibase_driver extends CI_DB { */ protected function _execute($sql) { - return ibase_query($this->conn_id, $sql); + return ibase_query(isset($this->_ibase_trans) ? $this->_ibase_trans : $this->conn_id, $sql); } // -------------------------------------------------------------------- @@ -123,24 +134,16 @@ class CI_DB_ibase_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if (($trans_handle = ibase_trans($this->conn_id)) === FALSE) { - return TRUE; + return FALSE; } - // 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); - - $this->_ibase_trans = ibase_trans($this->conn_id); - + $this->_ibase_trans = $trans_handle; return TRUE; } @@ -151,15 +154,15 @@ class CI_DB_ibase_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans->depth > 0) + if (ibase_commit($this->_ibase_trans)) { + $this->_ibase_trans = NULL; return TRUE; } - return ibase_commit($this->_ibase_trans); + return FALSE; } // -------------------------------------------------------------------- @@ -169,15 +172,15 @@ class CI_DB_ibase_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if (ibase_rollback($this->_ibase_trans)) { + $this->_ibase_trans = NULL; return TRUE; } - return ibase_rollback($this->_ibase_trans); + return FALSE; } // -------------------------------------------------------------------- @@ -219,11 +222,11 @@ class CI_DB_ibase_driver extends CI_DB { */ 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$%\''; + $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 "RDB$RELATION_NAME" LIKE \''.$this->escape_like_str($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); } @@ -242,7 +245,7 @@ class CI_DB_ibase_driver extends CI_DB { */ protected function _list_columns($table = '') { - return 'SELECT "RDB$FIELD_NAME" FROM "RDB$RELATION_FIELDS" WHERE "RDB$RELATION_NAME" = '.$this->escape($table); + return 'SELECT TRIM("RDB$FIELD_NAME") AS COLUMN_NAME FROM "RDB$RELATION_FIELDS" WHERE "RDB$RELATION_NAME" = '.$this->escape($table); } // -------------------------------------------------------------------- @@ -253,13 +256,8 @@ class CI_DB_ibase_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $sql = 'SELECT "rfields"."RDB$FIELD_NAME" AS "name", CASE "fields"."RDB$FIELD_TYPE" WHEN 7 THEN \'SMALLINT\' @@ -296,7 +294,7 @@ class CI_DB_ibase_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -385,6 +383,23 @@ class CI_DB_ibase_driver extends CI_DB { // -------------------------------------------------------------------- + /** + * 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 * @@ -396,6 +411,3 @@ class CI_DB_ibase_driver extends CI_DB { } } - -/* End of file ibase_driver.php */ -/* Location: ./system/database/drivers/ibase/ibase_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/ibase/ibase_forge.php b/system/database/drivers/ibase/ibase_forge.php old mode 100755 new mode 100644 index 19ac86c..29a3acf --- a/system/database/drivers/ibase/ibase_forge.php +++ b/system/database/drivers/ibase/ibase_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_ibase_forge extends CI_DB_forge { @@ -80,7 +91,7 @@ class CI_DB_ibase_forge extends CI_DB_forge { * Create database * * @param string $db_name - * @return string + * @return bool */ public function create_database($db_name) { @@ -100,7 +111,7 @@ class CI_DB_ibase_forge extends CI_DB_forge { * @param string $db_name (ignored) * @return bool */ - public function drop_database($db_name = '') + public function drop_database($db_name) { if ( ! ibase_drop_db($this->conn_id)) { @@ -238,6 +249,3 @@ class CI_DB_ibase_forge extends CI_DB_forge { } } - -/* End of file ibase_forge.php */ -/* Location: ./system/database/drivers/ibase/ibase_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/ibase/ibase_result.php b/system/database/drivers/ibase/ibase_result.php old mode 100755 new mode 100644 index cb2c7f4..8653097 --- a/system/database/drivers/ibase/ibase_result.php +++ b/system/database/drivers/ibase/ibase_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 3.0 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_ibase_result extends CI_DB_result { @@ -149,6 +159,3 @@ class CI_DB_ibase_result extends CI_DB_result { } } - -/* End of file ibase_result.php */ -/* Location: ./system/database/drivers/ibase/ibase_result.php */ \ No newline at end of file diff --git a/system/database/drivers/ibase/ibase_utility.php b/system/database/drivers/ibase/ibase_utility.php old mode 100755 new mode 100644 index a17b19e..a808749 --- a/system/database/drivers/ibase/ibase_utility.php +++ b/system/database/drivers/ibase/ibase_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_ibase_utility extends CI_DB_utility { @@ -56,6 +67,3 @@ class CI_DB_ibase_utility extends CI_DB_utility { } } - -/* End of file ibase_utility.php */ -/* Location: ./system/database/drivers/ibase/ibase_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/ibase/index.html b/system/database/drivers/ibase/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/ibase/index.html +++ b/system/database/drivers/ibase/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/index.html b/system/database/drivers/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/index.html +++ b/system/database/drivers/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/mssql/index.html b/system/database/drivers/mssql/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/mssql/index.html +++ b/system/database/drivers/mssql/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/mssql/mssql_driver.php b/system/database/drivers/mssql/mssql_driver.php old mode 100755 new mode 100644 index f4a1661..e197cfb --- a/system/database/drivers/mssql/mssql_driver.php +++ b/system/database/drivers/mssql/mssql_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_driver extends CI_DB { @@ -143,10 +154,11 @@ class CI_DB_mssql_driver extends CI_DB { } // Note: Escaping is required in the event that the DB name - // contains reserved characters - if (mssql_select_db($this->escape_identifiers($database), $this->conn_id)) + // contains reserved characters. + if (mssql_select_db('['.$database.']', $this->conn_id)) { $this->database = $database; + $this->data_cache = array(); return TRUE; } @@ -171,22 +183,10 @@ class CI_DB_mssql_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - return $this->simple_query('BEGIN TRAN'); } @@ -197,14 +197,8 @@ class CI_DB_mssql_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return $this->simple_query('COMMIT TRAN'); } @@ -215,14 +209,8 @@ class CI_DB_mssql_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return $this->simple_query('ROLLBACK TRAN'); } @@ -280,7 +268,7 @@ class CI_DB_mssql_driver extends CI_DB { */ protected function _version() { - return 'SELECT @@VERSION AS ver'; + return "SELECT SERVERPROPERTY('ProductVersion') AS ver"; } // -------------------------------------------------------------------- @@ -333,13 +321,8 @@ class CI_DB_mssql_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $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)); @@ -369,15 +352,25 @@ class CI_DB_mssql_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ public function error() { - $query = $this->query('SELECT @@ERROR AS code'); - $query = $query->row(); - return array('code' => $query->code, 'message' => mssql_get_last_message()); + // 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; } // -------------------------------------------------------------------- @@ -460,7 +453,7 @@ class CI_DB_mssql_driver extends CI_DB { $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) + if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } @@ -507,7 +500,7 @@ class CI_DB_mssql_driver extends CI_DB { return parent::_insert_batch($table, $keys, $values); } - return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- @@ -523,6 +516,3 @@ class CI_DB_mssql_driver extends CI_DB { } } - -/* End of file mssql_driver.php */ -/* Location: ./system/database/drivers/mssql/mssql_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/mssql/mssql_forge.php b/system/database/drivers/mssql/mssql_forge.php old mode 100755 new mode 100644 index eeb01ba..07b93c2 --- a/system/database/drivers/mssql/mssql_forge.php +++ b/system/database/drivers/mssql/mssql_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * MS SQL Forge Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_forge extends CI_DB_forge { @@ -100,6 +113,11 @@ class CI_DB_mssql_forge extends CI_DB_forge { */ protected function _attr_type(&$attributes) { + if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) + { + unset($attributes['CONSTRAINT']); + } + switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': @@ -131,6 +149,3 @@ class CI_DB_mssql_forge extends CI_DB_forge { } } - -/* End of file mssql_forge.php */ -/* Location: ./system/database/drivers/mssql/mssql_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/mssql/mssql_result.php b/system/database/drivers/mssql/mssql_result.php old mode 100755 new mode 100644 index f3ee987..5d7d3be --- a/system/database/drivers/mssql/mssql_result.php +++ b/system/database/drivers/mssql/mssql_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,10 +42,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * This class extends the parent result class: CI_DB_result * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.3 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_result extends CI_DB_result { @@ -95,7 +107,7 @@ class CI_DB_mssql_result extends CI_DB_result { public function field_data() { $retval = array(); - for ($i = 0, $c = $this->num_field(); $i < $c; $i++) + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field = mssql_fetch_field($this->result_id, $i); @@ -184,6 +196,3 @@ class CI_DB_mssql_result extends CI_DB_result { } } - -/* End of file mssql_result.php */ -/* Location: ./system/database/drivers/mssql/mssql_result.php */ \ No newline at end of file diff --git a/system/database/drivers/mssql/mssql_utility.php b/system/database/drivers/mssql/mssql_utility.php old mode 100755 new mode 100644 index 97212bd..5c9941a --- a/system/database/drivers/mssql/mssql_utility.php +++ b/system/database/drivers/mssql/mssql_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * MS SQL Utility Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mssql_utility extends CI_DB_utility { @@ -62,6 +75,3 @@ class CI_DB_mssql_utility extends CI_DB_utility { } } - -/* End of file mssql_utility.php */ -/* Location: ./system/database/drivers/mssql/mssql_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/mysql/index.html b/system/database/drivers/mysql/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/mysql/index.html +++ b/system/database/drivers/mysql/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/mysql/mysql_driver.php b/system/database/drivers/mysql/mysql_driver.php old mode 100755 new mode 100644 index 7cbcf10..78e77bc --- a/system/database/drivers/mysql/mysql_driver.php +++ b/system/database/drivers/mysql/mysql_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_driver extends CI_DB { @@ -73,7 +84,7 @@ class CI_DB_mysql_driver extends CI_DB { * * @var bool */ - public $stricton = FALSE; + public $stricton; // -------------------------------------------------------------------- @@ -121,8 +132,8 @@ class CI_DB_mysql_driver extends CI_DB { // 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); + ? mysql_pconnect($this->hostname, $this->username, $this->password, $client_flags) + : mysql_connect($this->hostname, $this->username, $this->password, TRUE, $client_flags); // ---------------------------------------------------------------- @@ -136,9 +147,26 @@ class CI_DB_mysql_driver extends CI_DB { : FALSE; } - if ($this->stricton && is_resource($this->conn_id)) + if (isset($this->stricton) && is_resource($this->conn_id)) { - $this->simple_query('SET SESSION sql_mode="STRICT_ALL_TABLES"'); + 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; @@ -180,6 +208,7 @@ class CI_DB_mysql_driver extends CI_DB { if (mysql_select_db($database, $this->conn_id)) { $this->database = $database; + $this->data_cache = array(); return TRUE; } @@ -212,10 +241,6 @@ class CI_DB_mysql_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } if ( ! $this->conn_id OR ($version = mysql_get_server_info($this->conn_id)) === FALSE) { @@ -265,25 +290,12 @@ class CI_DB_mysql_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - $this->simple_query('SET AUTOCOMMIT=0'); - $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK - return TRUE; + return $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK } // -------------------------------------------------------------------- @@ -293,17 +305,15 @@ class CI_DB_mysql_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if ($this->simple_query('COMMIT')) { + $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } - $this->simple_query('COMMIT'); - $this->simple_query('SET AUTOCOMMIT=1'); - return TRUE; + return FALSE; } // -------------------------------------------------------------------- @@ -313,32 +323,28 @@ class CI_DB_mysql_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if ($this->simple_query('ROLLBACK')) { + $this->simple_query('SET AUTOCOMMIT=1'); return TRUE; } - $this->simple_query('ROLLBACK'); - $this->simple_query('SET AUTOCOMMIT=1'); - return TRUE; + return FALSE; } // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { - return is_resource($this->conn_id) - ? mysql_real_escape_string($str, $this->conn_id) - : addslashes($str); + return mysql_real_escape_string($str, $this->conn_id); } // -------------------------------------------------------------------- @@ -410,13 +416,8 @@ class CI_DB_mysql_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; @@ -447,7 +448,7 @@ class CI_DB_mysql_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -491,6 +492,3 @@ class CI_DB_mysql_driver extends CI_DB { } } - -/* End of file mysql_driver.php */ -/* Location: ./system/database/drivers/mysql/mysql_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/mysql/mysql_forge.php b/system/database/drivers/mysql/mysql_forge.php old mode 100755 new mode 100644 index cc886e8..b69aa36 --- a/system/database/drivers/mysql/mysql_forge.php +++ b/system/database/drivers/mysql/mysql_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_forge extends CI_DB_forge { @@ -77,7 +88,7 @@ class CI_DB_mysql_forge extends CI_DB_forge { * * @var string */ - protected $_null = 'NULL'; + protected $_null = 'NULL'; // -------------------------------------------------------------------- @@ -174,6 +185,7 @@ class CI_DB_mysql_forge extends CI_DB_forge { $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'] @@ -182,6 +194,7 @@ class CI_DB_mysql_forge extends CI_DB_forge { .$field['default'] .$field['auto_increment'] .$field['unique'] + .(empty($field['comment']) ? '' : ' COMMENT '.$field['comment']) .$extra_clause; } @@ -228,6 +241,3 @@ class CI_DB_mysql_forge extends CI_DB_forge { } } - -/* End of file mysql_forge.php */ -/* Location: ./system/database/drivers/mysql/mysql_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/mysql/mysql_result.php b/system/database/drivers/mysql/mysql_result.php old mode 100755 new mode 100644 index 68860e6..842d7d3 --- a/system/database/drivers/mysql/mysql_result.php +++ b/system/database/drivers/mysql/mysql_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.0 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_result extends CI_DB_result { @@ -187,6 +197,3 @@ class CI_DB_mysql_result extends CI_DB_result { } } - -/* End of file mysql_result.php */ -/* Location: ./system/database/drivers/mysql/mysql_result.php */ \ No newline at end of file diff --git a/system/database/drivers/mysql/mysql_utility.php b/system/database/drivers/mysql/mysql_utility.php old mode 100755 new mode 100644 index 91de871..a548929 --- a/system/database/drivers/mysql/mysql_utility.php +++ b/system/database/drivers/mysql/mysql_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysql_utility extends CI_DB_utility { @@ -198,6 +209,3 @@ class CI_DB_mysql_utility extends CI_DB_utility { } } - -/* End of file mysql_utility.php */ -/* Location: ./system/database/drivers/mysql/mysql_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/mysqli/index.html b/system/database/drivers/mysqli/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/mysqli/index.html +++ b/system/database/drivers/mysqli/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/mysqli/mysqli_driver.php b/system/database/drivers/mysqli/mysqli_driver.php old mode 100755 new mode 100644 index 09277fc..d374e01 --- a/system/database/drivers/mysqli/mysqli_driver.php +++ b/system/database/drivers/mysqli/mysqli_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_driver extends CI_DB { @@ -73,7 +84,7 @@ class CI_DB_mysqli_driver extends CI_DB { * * @var bool */ - public $stricton = FALSE; + public $stricton; // -------------------------------------------------------------------- @@ -86,29 +97,128 @@ class CI_DB_mysqli_driver extends CI_DB { // -------------------------------------------------------------------- + /** + * MySQLi object + * + * Has to be preserved without being assigned to $conn_id. + * + * @var MySQLi + */ + protected $_mysqli; + + // -------------------------------------------------------------------- + /** * Database connection * * @param bool $persistent * @return object - * @todo SSL support */ public function db_connect($persistent = FALSE) { - // Persistent connection support was added in PHP 5.3.0 - $hostname = ($persistent === TRUE && is_php('5.3')) - ? 'p:'.$this->hostname : $this->hostname; - $port = empty($this->port) ? NULL : $this->port; - $client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0; - $mysqli = mysqli_init(); - - if ($this->stricton) + // Do we have a socket path? + if ($this->hostname[0] === '/') { - $mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode="STRICT_ALL_TABLES"'); + $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; } - return $mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, NULL, $client_flags) - ? $mysqli : FALSE; + $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; } // -------------------------------------------------------------------- @@ -147,6 +257,7 @@ class CI_DB_mysqli_driver extends CI_DB { if ($this->conn_id->select_db($database)) { $this->database = $database; + $this->data_cache = array(); return TRUE; } @@ -179,10 +290,6 @@ class CI_DB_mysqli_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } return $this->data_cache['version'] = $this->conn_id->server_info; } @@ -227,22 +334,10 @@ class CI_DB_mysqli_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - $this->conn_id->autocommit(FALSE); return is_php('5.5') ? $this->conn_id->begin_transaction() @@ -256,14 +351,8 @@ class CI_DB_mysqli_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - if ($this->conn_id->commit()) { $this->conn_id->autocommit(TRUE); @@ -280,14 +369,8 @@ class CI_DB_mysqli_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - if ($this->conn_id->rollback()) { $this->conn_id->autocommit(TRUE); @@ -300,16 +383,14 @@ class CI_DB_mysqli_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { - return is_object($this->conn_id) - ? $this->conn_id->real_escape_string($str) - : addslashes($str); + return $this->conn_id->real_escape_string($str); } // -------------------------------------------------------------------- @@ -381,13 +462,8 @@ class CI_DB_mysqli_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; @@ -418,17 +494,17 @@ class CI_DB_mysqli_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ public function error() { - if ( ! empty($this->conn_id->connect_errno)) + if ( ! empty($this->_mysqli->connect_errno)) { return array( - 'code' => $this->conn_id->connect_errno, - 'message' => is_php('5.2.9') ? $this->conn_id->connect_error : mysqli_connect_error() + 'code' => $this->_mysqli->connect_errno, + 'message' => $this->_mysqli->connect_error ); } @@ -468,6 +544,3 @@ class CI_DB_mysqli_driver extends CI_DB { } } - -/* End of file mysqli_driver.php */ -/* Location: ./system/database/drivers/mysqli/mysqli_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/mysqli/mysqli_forge.php b/system/database/drivers/mysqli/mysqli_forge.php old mode 100755 new mode 100644 index 3a19405..92b1e94 --- a/system/database/drivers/mysqli/mysqli_forge.php +++ b/system/database/drivers/mysqli/mysqli_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * MySQLi Forge Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_forge extends CI_DB_forge { @@ -77,7 +90,7 @@ class CI_DB_mysqli_forge extends CI_DB_forge { * * @var string */ - protected $_null = 'NULL'; + protected $_null = 'NULL'; // -------------------------------------------------------------------- @@ -182,6 +195,7 @@ class CI_DB_mysqli_forge extends CI_DB_forge { .$field['default'] .$field['auto_increment'] .$field['unique'] + .(empty($field['comment']) ? '' : ' COMMENT '.$field['comment']) .$extra_clause; } @@ -228,6 +242,3 @@ class CI_DB_mysqli_forge extends CI_DB_forge { } } - -/* End of file mysqli_forge.php */ -/* Location: ./system/database/drivers/mysqli/mysqli_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/mysqli/mysqli_result.php b/system/database/drivers/mysqli/mysqli_result.php old mode 100755 new mode 100644 index 7f5792a..0856eca --- a/system/database/drivers/mysqli/mysqli_result.php +++ b/system/database/drivers/mysqli/mysqli_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,10 +42,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * This class extends the parent result class: CI_DB_result * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.3 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_result extends CI_DB_result { @@ -100,9 +112,9 @@ class CI_DB_mysqli_result extends CI_DB_result { { $retval[$i] = new stdClass(); $retval[$i]->name = $field_data[$i]->name; - $retval[$i]->type = $field_data[$i]->type; + $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 & 2); + $retval[$i]->primary_key = (int) ($field_data[$i]->flags & MYSQLI_PRI_KEY_FLAG); $retval[$i]->default = $field_data[$i]->def; } @@ -111,6 +123,52 @@ class CI_DB_mysqli_result extends CI_DB_result { // -------------------------------------------------------------------- + /** + * 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 * @@ -172,6 +230,3 @@ class CI_DB_mysqli_result extends CI_DB_result { } } - -/* End of file mysqli_result.php */ -/* Location: ./system/database/drivers/mysqli/mysqli_result.php */ \ No newline at end of file diff --git a/system/database/drivers/mysqli/mysqli_utility.php b/system/database/drivers/mysqli/mysqli_utility.php old mode 100755 new mode 100644 index 1c94757..6064246 --- a/system/database/drivers/mysqli/mysqli_utility.php +++ b/system/database/drivers/mysqli/mysqli_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * MySQLi Utility Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_mysqli_utility extends CI_DB_utility { @@ -142,9 +155,7 @@ class CI_DB_mysqli_utility extends CI_DB_utility { while ($field = $query->result_id->fetch_field()) { // Most versions of MySQL store timestamp as a string - $is_int[$i] = in_array(strtolower($field->type), - array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'), - TRUE); + $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).', '; @@ -198,6 +209,3 @@ class CI_DB_mysqli_utility extends CI_DB_utility { } } - -/* End of file mysqli_utility.php */ -/* Location: ./system/database/drivers/mysqli/mysqli_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/oci8/index.html b/system/database/drivers/oci8/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/oci8/index.html +++ b/system/database/drivers/oci8/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/oci8/oci8_driver.php b/system/database/drivers/oci8/oci8_driver.php old mode 100755 new mode 100644 index f34c0d1..a825c4a --- a/system/database/drivers/oci8/oci8_driver.php +++ b/system/database/drivers/oci8/oci8_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.4.1 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ /** @@ -86,10 +97,18 @@ class CI_DB_oci8_driver extends CI_DB { * * @var bool */ - public $limit_used; + public $limit_used = FALSE; // -------------------------------------------------------------------- + /** + * Reset $stmt_id flag + * + * Used by stored_procedure() to prevent _execute() from + * re-setting the statement ID. + */ + protected $_reset_stmt_id = TRUE; + /** * List of reserved identifiers * @@ -232,17 +251,17 @@ class CI_DB_oci8_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } - if ( ! $this->conn_id OR ($version = oci_server_version($this->conn_id)) === FALSE) + 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 $this->data_cache['version'] = $version; + return FALSE; } // -------------------------------------------------------------------- @@ -258,26 +277,13 @@ class CI_DB_oci8_driver extends CI_DB { /* 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(). */ - $this->stmt_id = FALSE; - $this->_set_stmt_id($sql); - oci_set_prefetch($this->stmt_id, 1000); - return oci_execute($this->stmt_id, $this->commit_mode); - } - - // -------------------------------------------------------------------- - - /** - * Generate a statement ID - * - * @param string $sql an SQL query - * @return void - */ - protected function _set_stmt_id($sql) - { - if ( ! is_resource($this->stmt_id)) + 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); } // -------------------------------------------------------------------- @@ -304,22 +310,22 @@ class CI_DB_oci8_driver extends CI_DB { * * 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 + * KEY OPTIONAL NOTES + * name no the name of the parameter should be in : format + * value no the value of the parameter. If this is an OUT or IN OUT parameter, + * this should be a reference to a variable + * type yes the type of the parameter + * length yes the max size of the parameter */ - public function stored_procedure($package, $procedure, $params) + public function stored_procedure($package, $procedure, array $params) { - if ($package === '' OR $procedure === '' OR ! is_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 + // Build the query string $sql = 'BEGIN '.$package.'.'.$procedure.'('; $have_cursor = FALSE; @@ -334,10 +340,12 @@ class CI_DB_oci8_driver extends CI_DB { } $sql = trim($sql, ',').'); END;'; - $this->stmt_id = FALSE; - $this->_set_stmt_id($sql); + $this->_reset_stmt_id = FALSE; + $this->stmt_id = oci_parse($this->conn_id, $sql); $this->_bind_params($params); - return $this->query($sql, FALSE, $have_cursor); + $result = $this->query($sql, FALSE, $have_cursor); + $this->_reset_stmt_id = TRUE; + return $result; } // -------------------------------------------------------------------- @@ -374,28 +382,11 @@ class CI_DB_oci8_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - if ( ! $this->trans_enabled) - { - return TRUE; - } - - // When transactions are nested we only begin/commit/rollback the outermost ones - if ($this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - - $this->commit_mode = is_php('5.3.2') ? OCI_NO_AUTO_COMMIT : OCI_DEFAULT; + $this->commit_mode = OCI_NO_AUTO_COMMIT; return TRUE; } @@ -406,20 +397,10 @@ class CI_DB_oci8_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - if ( ! $this->trans_enabled) - { - return TRUE; - } - - // When transactions are nested we only begin/commit/rollback the outermost ones - if ($this->_trans_depth > 0) - { - return TRUE; - } - $this->commit_mode = OCI_COMMIT_ON_SUCCESS; + return oci_commit($this->conn_id); } @@ -430,14 +411,8 @@ class CI_DB_oci8_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - $this->commit_mode = OCI_COMMIT_ON_SUCCESS; return oci_rollback($this->conn_id); } @@ -524,13 +499,9 @@ class CI_DB_oci8_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - elseif (strpos($table, '.') !== FALSE) + if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } @@ -570,7 +541,7 @@ class CI_DB_oci8_driver extends CI_DB { { $default = ''; } - $retval[$i]->default = $query[$i]->COLUMN_DEFAULT; + $retval[$i]->default = $default; } return $retval; @@ -582,29 +553,35 @@ class CI_DB_oci8_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ public function error() { - /* oci_error() returns an array that already contains the - * 'code' and 'message' keys, so we can just return it. - */ + // 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)) { - return oci_error($this->curs_id); + $error = oci_error($this->curs_id); } elseif (is_resource($this->stmt_id)) { - return oci_error($this->stmt_id); + $error = oci_error($this->stmt_id); } elseif (is_resource($this->conn_id)) { - return oci_error($this->conn_id); + $error = oci_error($this->conn_id); + } + else + { + $error = oci_error(); } - return oci_error(); + return is_array($error) + ? $error + : array('code' => '', 'message' => ''); } // -------------------------------------------------------------------- @@ -683,6 +660,14 @@ class CI_DB_oci8_driver extends CI_DB { */ 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) : ''); @@ -700,7 +685,17 @@ class CI_DB_oci8_driver extends CI_DB { oci_close($this->conn_id); } -} + // -------------------------------------------------------------------- -/* End of file oci8_driver.php */ -/* Location: ./system/database/drivers/oci8/oci8_driver.php */ \ No newline at end of file + /** + * 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 old mode 100755 new mode 100644 index d63846f..20217f2 --- a/system/database/drivers/oci8/oci8_forge.php +++ b/system/database/drivers/oci8/oci8_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.4.1 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_forge extends CI_DB_forge { @@ -42,6 +53,13 @@ class CI_DB_oci8_forge extends CI_DB_forge { */ protected $_create_database = FALSE; + /** + * CREATE TABLE IF statement + * + * @var string + */ + protected $_create_table_if = FALSE; + /** * DROP DATABASE statement * @@ -95,11 +113,21 @@ class CI_DB_oci8_forge extends CI_DB_forge { 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']) - .' '.$this->db->escape_identifiers($field[$i]['new_name']); + .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } + + $field[$i] = "\n\t".$field[$i]['_literal']; } } @@ -110,7 +138,7 @@ class CI_DB_oci8_forge extends CI_DB_forge { // RENAME COLUMN must be executed after MODIFY array_unshift($sqls, $sql); - return $sql; + return $sqls; } // -------------------------------------------------------------------- @@ -127,7 +155,33 @@ class CI_DB_oci8_forge extends CI_DB_forge { // Not supported - sequences and triggers must be used instead } -} + // -------------------------------------------------------------------- -/* End of file oci8_forge.php */ -/* Location: ./system/database/drivers/oci8/oci8_forge.php */ \ No newline at end of file + /** + * 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 old mode 100755 new mode 100644 index 50612ca..3da49aa --- a/system/database/drivers/oci8/oci8_result.php +++ b/system/database/drivers/oci8/oci8_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.4.1 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.4.1 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_result extends CI_DB_result { @@ -217,6 +227,3 @@ class CI_DB_oci8_result extends CI_DB_result { } } - -/* End of file oci8_result.php */ -/* Location: ./system/database/drivers/oci8/oci8_result.php */ \ No newline at end of file diff --git a/system/database/drivers/oci8/oci8_utility.php b/system/database/drivers/oci8/oci8_utility.php old mode 100755 new mode 100644 index 856125b..3a7261c --- a/system/database/drivers/oci8/oci8_utility.php +++ b/system/database/drivers/oci8/oci8_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.4.1 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_utility extends CI_DB_utility { @@ -55,6 +66,3 @@ class CI_DB_oci8_utility extends CI_DB_utility { } } - -/* End of file oci8_utility.php */ -/* Location: ./system/database/drivers/oci8/oci8_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/odbc/index.html b/system/database/drivers/odbc/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/odbc/index.html +++ b/system/database/drivers/odbc/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/odbc/odbc_driver.php b/system/database/drivers/odbc/odbc_driver.php old mode 100755 new mode 100644 index 06c24d6..72289bf --- a/system/database/drivers/odbc/odbc_driver.php +++ b/system/database/drivers/odbc/odbc_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,9 +48,9 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ -class CI_DB_odbc_driver extends CI_DB { +class CI_DB_odbc_driver extends CI_DB_driver { /** * Database driver @@ -82,6 +93,22 @@ class CI_DB_odbc_driver extends CI_DB { // -------------------------------------------------------------------- + /** + * ODBC result ID resource returned from odbc_prepare() + * + * @var resource + */ + private $odbc_result; + + /** + * Values to use with odbc_execute() for prepared statements + * + * @var array + */ + private $binds = array(); + + // -------------------------------------------------------------------- + /** * Class constructor * @@ -116,6 +143,74 @@ class CI_DB_odbc_driver extends CI_DB { // -------------------------------------------------------------------- + /** + * 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 * @@ -124,7 +219,25 @@ class CI_DB_odbc_driver extends CI_DB { */ protected function _execute($sql) { - return odbc_exec($this->conn_id, $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; } // -------------------------------------------------------------------- @@ -132,22 +245,10 @@ class CI_DB_odbc_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - return odbc_autocommit($this->conn_id, FALSE); } @@ -158,17 +259,15 @@ class CI_DB_odbc_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if (odbc_commit($this->conn_id)) { + odbc_autocommit($this->conn_id, TRUE); return TRUE; } - $ret = odbc_commit($this->conn_id); - odbc_autocommit($this->conn_id, TRUE); - return $ret; + return FALSE; } // -------------------------------------------------------------------- @@ -178,30 +277,46 @@ class CI_DB_odbc_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + if (odbc_rollback($this->conn_id)) { + odbc_autocommit($this->conn_id, TRUE); return TRUE; } - $ret = odbc_rollback($this->conn_id); - odbc_autocommit($this->conn_id, TRUE); - return $ret; + return FALSE; } // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * 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 remove_invisible_characters($str); + $this->display_error('db_unsupported_feature'); } // -------------------------------------------------------------------- @@ -225,7 +340,7 @@ class CI_DB_odbc_driver extends CI_DB { */ public function insert_id() { - return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- @@ -287,7 +402,7 @@ class CI_DB_odbc_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -298,58 +413,6 @@ class CI_DB_odbc_driver extends CI_DB { // -------------------------------------------------------------------- - /** - * 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 '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); - } - - // -------------------------------------------------------------------- - /** * Close DB Connection * @@ -359,8 +422,4 @@ class CI_DB_odbc_driver extends CI_DB { { odbc_close($this->conn_id); } - } - -/* End of file odbc_driver.php */ -/* Location: ./system/database/drivers/odbc/odbc_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/odbc/odbc_forge.php b/system/database/drivers/odbc/odbc_forge.php old mode 100755 new mode 100644 index dbf9949..05f9c76 --- a/system/database/drivers/odbc/odbc_forge.php +++ b/system/database/drivers/odbc/odbc_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * ODBC Forge Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/database/ + * @link https://codeigniter.com/database/ */ class CI_DB_odbc_forge extends CI_DB_forge { @@ -71,6 +84,3 @@ class CI_DB_odbc_forge extends CI_DB_forge { } } - -/* End of file odbc_forge.php */ -/* Location: ./system/database/drivers/odbc/odbc_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/odbc/odbc_result.php b/system/database/drivers/odbc/odbc_result.php old mode 100755 new mode 100644 index 3a101cd..a06ac4b --- a/system/database/drivers/odbc/odbc_result.php +++ b/system/database/drivers/odbc/odbc_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,10 +42,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * This class extends the parent result class: CI_DB_result * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.3 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_odbc_result extends CI_DB_result { @@ -254,6 +266,3 @@ if ( ! function_exists('odbc_fetch_object')) return $rs_object; } } - -/* End of file odbc_result.php */ -/* Location: ./system/database/drivers/odbc/odbc_result.php */ \ No newline at end of file diff --git a/system/database/drivers/odbc/odbc_utility.php b/system/database/drivers/odbc/odbc_utility.php old mode 100755 new mode 100644 index 00b6186..7872010 --- a/system/database/drivers/odbc/odbc_utility.php +++ b/system/database/drivers/odbc/odbc_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * ODBC Utility Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/database/ + * @link https://codeigniter.com/database/ */ class CI_DB_odbc_utility extends CI_DB_utility { @@ -48,6 +61,3 @@ class CI_DB_odbc_utility extends CI_DB_utility { } } - -/* End of file odbc_utility.php */ -/* Location: ./system/database/drivers/odbc/odbc_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/index.html b/system/database/drivers/pdo/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/pdo/index.html +++ b/system/database/drivers/pdo/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/pdo/pdo_driver.php b/system/database/drivers/pdo/pdo_driver.php old mode 100755 new mode 100644 index 1d4e626..c5d120f --- a/system/database/drivers/pdo/pdo_driver.php +++ b/system/database/drivers/pdo/pdo_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_driver extends CI_DB { @@ -115,7 +126,10 @@ class CI_DB_pdo_driver extends CI_DB { */ public function db_connect($persistent = FALSE) { - $this->options[PDO::ATTR_PERSISTENT] = $persistent; + if ($persistent === TRUE) + { + $this->options[PDO::ATTR_PERSISTENT] = TRUE; + } try { @@ -145,10 +159,6 @@ class CI_DB_pdo_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } // Not all subdrivers support the getAttribute() method try @@ -179,22 +189,10 @@ class CI_DB_pdo_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - return $this->conn_id->beginTransaction(); } @@ -205,14 +203,8 @@ class CI_DB_pdo_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return $this->conn_id->commit(); } @@ -223,21 +215,15 @@ class CI_DB_pdo_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return $this->conn_id->rollBack(); } // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string @@ -299,7 +285,7 @@ class CI_DB_pdo_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -324,52 +310,6 @@ class CI_DB_pdo_driver extends CI_DB { // -------------------------------------------------------------------- - /** - * 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]; - - foreach (array_keys($val) as $field) - { - if ($field !== $index) - { - $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; - } - } - } - - $cases = ''; - foreach ($final as $k => $v) - { - $cases .= $k.' = CASE '."\n"; - - foreach ($v as $row) - { - $cases .= $row."\n"; - } - - $cases .= 'ELSE '.$k.' END, '; - } - - $this->where($index.' IN('.implode(',', $ids).')', NULL, FALSE); - - return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); - } - - // -------------------------------------------------------------------- - /** * Truncate statement * @@ -387,6 +327,3 @@ class CI_DB_pdo_driver extends CI_DB { } } - -/* End of file pdo_driver.php */ -/* Location: ./system/database/drivers/pdo/pdo_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/pdo_forge.php b/system/database/drivers/pdo/pdo_forge.php old mode 100755 new mode 100644 index 4bc8546..e512d3d --- a/system/database/drivers/pdo/pdo_forge.php +++ b/system/database/drivers/pdo/pdo_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * PDO Forge Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/database/ + * @link https://codeigniter.com/database/ */ class CI_DB_pdo_forge extends CI_DB_forge { @@ -50,6 +63,3 @@ class CI_DB_pdo_forge extends CI_DB_forge { protected $_drop_table_if = FALSE; } - -/* End of file pdo_forge.php */ -/* Location: ./system/database/drivers/pdo/pdo_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/pdo_result.php b/system/database/drivers/pdo/pdo_result.php old mode 100755 new mode 100644 index 1b8fbc9..03c0f9f --- a/system/database/drivers/pdo/pdo_result.php +++ b/system/database/drivers/pdo/pdo_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,10 +42,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * This class extends the parent result class: CI_DB_result * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 2.1 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_result extends CI_DB_result { @@ -93,7 +105,7 @@ class CI_DB_pdo_result extends CI_DB_result { { // Might trigger an E_WARNING due to not all subdrivers // supporting getColumnMeta() - $field_names[$i] = @$this->result_id->getColumnMeta(); + $field_names[$i] = @$this->result_id->getColumnMeta($i); $field_names[$i] = $field_names[$i]['name']; } @@ -184,6 +196,3 @@ class CI_DB_pdo_result extends CI_DB_result { } } - -/* End of file pdo_result.php */ -/* Location: ./system/database/drivers/pdo/pdo_result.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/pdo_utility.php b/system/database/drivers/pdo/pdo_utility.php old mode 100755 new mode 100644 index f3c8e2d..6c40cf3 --- a/system/database/drivers/pdo/pdo_utility.php +++ b/system/database/drivers/pdo/pdo_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * PDO Utility Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/database/ + * @link https://codeigniter.com/database/ */ class CI_DB_pdo_utility extends CI_DB_utility { @@ -48,6 +61,3 @@ class CI_DB_pdo_utility extends CI_DB_utility { } } - -/* End of file pdo_utility.php */ -/* Location: ./system/database/drivers/pdo/pdo_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/index.html b/system/database/drivers/pdo/subdrivers/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/pdo/subdrivers/index.html +++ b/system/database/drivers/pdo/subdrivers/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php b/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php old mode 100755 new mode 100644 index 590a332..2e39bb2 --- a/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_4d_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_4d_driver extends CI_DB_pdo_driver { @@ -147,7 +158,7 @@ class CI_DB_pdo_4d_driver extends CI_DB_pdo_driver { * @param string $table * @param array $values * @return string - */ + */ protected function _update($table, $values) { $this->qb_limit = FALSE; @@ -187,6 +198,3 @@ class CI_DB_pdo_4d_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_4d_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_4d_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php b/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php old mode 100755 new mode 100644 index 97255ed..306150b --- a/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_4d_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,9 +42,9 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ -class CI_DB_pdo_4d_forge extends CI_DB_4d_forge { +class CI_DB_pdo_4d_forge extends CI_DB_pdo_forge { /** * CREATE DATABASE statement @@ -153,7 +164,7 @@ class CI_DB_pdo_4d_forge extends CI_DB_4d_forge { $attributes['TYPE'] = 'INT'; return; case 'BIGINT': - $attribites['TYPE'] = 'INT64'; + $attributes['TYPE'] = 'INT64'; return; default: return; } @@ -204,6 +215,3 @@ class CI_DB_pdo_4d_forge extends CI_DB_4d_forge { } } - -/* End of file pdo_4d_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_4d_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php b/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php old mode 100755 new mode 100644 index d2d1fd5..9a6b643 --- a/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_cubrid_driver extends CI_DB_pdo_driver { @@ -131,13 +142,8 @@ class CI_DB_pdo_cubrid_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; @@ -164,47 +170,6 @@ class CI_DB_pdo_cubrid_driver extends CI_DB_pdo_driver { // -------------------------------------------------------------------- - /** - * 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]; - - foreach (array_keys($val) as $field) - { - if ($field !== $index) - { - $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; - } - } - } - - $cases = ''; - foreach ($final as $k => $v) - { - $cases .= $k." = CASE \n" - .implode("\n", $v)."\n" - .'ELSE '.$k.' END), '; - } - - $this->where($index.' IN('.implode(',', $ids).')', NULL, FALSE); - - return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); - } - - // -------------------------------------------------------------------- - /** * Truncate statement * @@ -242,6 +207,3 @@ class CI_DB_pdo_cubrid_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_cubrid_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_cubrid_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php b/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php old mode 100755 new mode 100644 index ed93d24..f2ee3f5 --- a/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_cubrid_forge extends CI_DB_pdo_forge { @@ -167,6 +178,9 @@ class CI_DB_pdo_cubrid_forge extends CI_DB_pdo_forge { $attributes['TYPE'] = 'INTEGER'; $attributes['UNSIGNED'] = FALSE; return; + case 'LONGTEXT': + $attributes['TYPE'] = 'STRING'; + return; default: return; } } @@ -214,6 +228,3 @@ class CI_DB_pdo_cubrid_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_cubrid_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_cubrid_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php b/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php old mode 100755 new mode 100644 index 379fc07..09dbdf0 --- a/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { @@ -115,7 +126,12 @@ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { */ public function db_connect($persistent = FALSE) { - $this->conn_id = parent::db_connect($persistent); + 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)) { @@ -143,7 +159,7 @@ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { */ protected function _list_tables($prefix_limit = FALSE) { - return 'SELECT '.$this->escape_identifiers('name') + $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; @@ -181,13 +197,8 @@ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $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)); @@ -221,7 +232,7 @@ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { * @param string $table * @param array $values * @return string - */ + */ protected function _update($table, $values) { $this->qb_limit = FALSE; @@ -273,7 +284,7 @@ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { $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) + if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } @@ -320,10 +331,23 @@ class CI_DB_pdo_dblib_driver extends CI_DB_pdo_driver { return parent::_insert_batch($table, $keys, $values); } - return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } -} + // -------------------------------------------------------------------- -/* End of file pdo_dblib_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_dblib_driver.php */ \ No newline at end of file + /** + * 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 old mode 100755 new mode 100644 index 271c00d..f38ac99 --- a/system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_dblib_forge extends CI_DB_pdo_forge { @@ -100,6 +111,11 @@ class CI_DB_pdo_dblib_forge extends CI_DB_pdo_forge { */ protected function _attr_type(&$attributes) { + if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) + { + unset($attributes['CONSTRAINT']); + } + switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': @@ -131,6 +147,3 @@ class CI_DB_pdo_dblib_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_dblib_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_dblib_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php b/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php old mode 100755 new mode 100644 index cbee19e..2c49f12 --- a/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_firebird_driver extends CI_DB_pdo_driver { @@ -139,13 +150,8 @@ class CI_DB_pdo_firebird_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $sql = 'SELECT "rfields"."RDB$FIELD_NAME" AS "name", CASE "fields"."RDB$FIELD_TYPE" WHEN 7 THEN \'SMALLINT\' @@ -205,7 +211,7 @@ class CI_DB_pdo_firebird_driver extends CI_DB_pdo_driver { * * @param string $table * @return string - */ + */ protected function _truncate($table) { return 'DELETE FROM '.$table; @@ -254,7 +260,20 @@ class CI_DB_pdo_firebird_driver extends CI_DB_pdo_driver { return preg_replace('`SELECT`i', 'SELECT '.$select, $sql); } -} + // -------------------------------------------------------------------- -/* End of file pdo_firebird_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_firebird_driver.php */ \ No newline at end of file + /** + * 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 old mode 100755 new mode 100644 index d754c27..54752f1 --- a/system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_firebird_forge extends CI_DB_pdo_forge { @@ -86,7 +97,7 @@ class CI_DB_pdo_firebird_forge extends CI_DB_pdo_forge { * @param string $db_name (ignored) * @return bool */ - public function drop_database($db_name = '') + public function drop_database($db_name) { if ( ! ibase_drop_db($this->conn_id)) { @@ -224,6 +235,3 @@ class CI_DB_pdo_firebird_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_firebird_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_firebird_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php b/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php old mode 100755 new mode 100644 index 030fae0..00654d7 --- a/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_ibm_driver extends CI_DB_pdo_driver { @@ -163,7 +174,7 @@ class CI_DB_pdo_ibm_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + 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" @@ -231,6 +242,3 @@ class CI_DB_pdo_ibm_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_ibm_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_ibm_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php b/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php old mode 100755 new mode 100644 index fc3579f..99d75b6 --- a/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_ibm_forge extends CI_DB_pdo_forge { @@ -141,6 +152,3 @@ class CI_DB_pdo_ibm_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_ibm_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_ibm_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php b/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php old mode 100755 new mode 100644 index f28cce1..114eb74 --- a/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_informix_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_informix_driver extends CI_DB_pdo_driver { @@ -176,7 +187,7 @@ class CI_DB_pdo_informix_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { $sql = 'SELECT "syscolumns"."colname" AS "name", CASE "syscolumns"."coltype" @@ -296,6 +307,3 @@ class CI_DB_pdo_informix_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_informix_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_informix_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php b/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php old mode 100755 new mode 100644 index a2d0bdd..1f4bcd1 --- a/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_informix_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_informix_forge extends CI_DB_pdo_forge { @@ -150,6 +161,3 @@ class CI_DB_pdo_informix_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_informix_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_informix_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php b/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php old mode 100755 new mode 100644 index 70c405c..26bc30e --- a/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { @@ -62,7 +73,7 @@ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { * * @var bool */ - public $stricton = FALSE; + public $stricton; // -------------------------------------------------------------------- @@ -95,7 +106,7 @@ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { 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 && is_php('5.3.6')) + elseif ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 6) === FALSE) { $this->dsn .= ';charset='.$this->char_set; } @@ -108,30 +119,37 @@ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { * * @param bool $persistent * @return object - * @todo SSL support */ public function db_connect($persistent = FALSE) { - /* Prior to PHP 5.3.6, even if the charset was supplied in the DSN - * on connect - it was ignored. This is a work-around for the issue. - * - * Reference: http://www.php.net/manual/en/ref.pdo-mysql.connection.php - */ - if ( ! is_php('5.3.6') && ! empty($this->char_set)) + if (isset($this->stricton)) { - $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES '.$this->char_set - .(empty($this->dbcollat) ? '' : ' COLLATE '.$this->dbcollat); - } - - if ($this->stricton) - { - if (empty($this->options[PDO::MYSQL_ATTR_INIT_COMMAND])) + if ($this->stricton) { - $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET SESSION sql_mode="STRICT_ALL_TABLES"'; + $sql = 'CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'; } else { - $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] .= ', @@session.sql_mode = "STRICT_ALL_TABLES"'; + $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; + } } } @@ -140,7 +158,113 @@ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { $this->options[PDO::MYSQL_ATTR_COMPRESS] = TRUE; } - return parent::db_connect($persistent); + 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; } // -------------------------------------------------------------------- @@ -188,13 +312,8 @@ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE) { return FALSE; @@ -258,6 +377,3 @@ class CI_DB_pdo_mysql_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_mysql_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_mysql_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php b/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php old mode 100755 new mode 100644 index d2e1e28..01595a6 --- a/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_mysql_forge extends CI_DB_pdo_forge { @@ -91,7 +102,7 @@ class CI_DB_pdo_mysql_forge extends CI_DB_pdo_forge { * * @var string */ - protected $_null = 'NULL'; + protected $_null = 'NULL'; // -------------------------------------------------------------------- @@ -196,6 +207,7 @@ class CI_DB_pdo_mysql_forge extends CI_DB_pdo_forge { .$field['default'] .$field['auto_increment'] .$field['unique'] + .(empty($field['comment']) ? '' : ' COMMENT '.$field['comment']) .$extra_clause; } @@ -242,6 +254,3 @@ class CI_DB_pdo_mysql_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_mysql_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_mysql_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php b/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php old mode 100755 new mode 100644 index 6fef078..dba4958 --- a/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_oci_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_oci_driver extends CI_DB_pdo_driver { @@ -118,6 +129,29 @@ class CI_DB_pdo_oci_driver extends CI_DB_pdo_driver { // -------------------------------------------------------------------- + /** + * 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 * @@ -173,13 +207,9 @@ class CI_DB_pdo_oci_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - elseif (strpos($table, '.') !== FALSE) + if (strpos($table, '.') !== FALSE) { sscanf($table, '%[^.].%s', $owner, $table); } @@ -281,11 +311,16 @@ class CI_DB_pdo_oci_driver extends CI_DB_pdo_driver { */ 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): ''); } } - -/* End of file pdo_oci_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_oci_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php b/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php old mode 100755 new mode 100644 index dbbff5b..0abda59 --- a/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_oci_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_oci_forge extends CI_DB_pdo_forge { @@ -42,6 +53,13 @@ class CI_DB_pdo_oci_forge extends CI_DB_pdo_forge { */ protected $_create_database = FALSE; + /** + * CREATE TABLE IF statement + * + * @var string + */ + protected $_create_table_if = FALSE; + /** * DROP DATABASE statement * @@ -49,13 +67,6 @@ class CI_DB_pdo_oci_forge extends CI_DB_pdo_forge { */ protected $_drop_database = FALSE; - /** - * CREATE TABLE IF statement - * - * @var string - */ - protected $_create_table_if = 'CREATE TABLE IF NOT EXISTS'; - /** * UNSIGNED support * @@ -95,10 +106,18 @@ class CI_DB_pdo_oci_forge extends CI_DB_pdo_forge { 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']) - .' '.$this->db->escape_identifiers($field[$i]['new_name']); + .' TO '.$this->db->escape_identifiers($field[$i]['new_name']); } } } @@ -127,7 +146,31 @@ class CI_DB_pdo_oci_forge extends CI_DB_pdo_forge { // 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; + } + } } - -/* End of file pdo_oci_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_oci_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php b/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php old mode 100755 new mode 100644 index c95fe18..93a6420 --- a/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_odbc_driver extends CI_DB_pdo_driver { @@ -149,6 +160,37 @@ class CI_DB_pdo_odbc_driver extends CI_DB_pdo_driver { // -------------------------------------------------------------------- + /** + * 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 * @@ -184,75 +226,4 @@ class CI_DB_pdo_odbc_driver extends CI_DB_pdo_driver { { return 'SELECT column_name FROM information_schema.columns WHERE table_name = '.$this->escape($table); } - - // -------------------------------------------------------------------- - - /** - * 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 'DELETE FROM '.$table; - } - - // -------------------------------------------------------------------- - - /** - * Delete statement - * - * Generates a platform-specific delete string from the supplied data - * - * @param string the table name - * @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 preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$this->qb_limit.' ', $sql); - } - } - -/* End of file pdo_odbc_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php b/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php old mode 100755 new mode 100644 index e7feacd..47226d7 --- a/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/database/ + * @link https://codeigniter.com/database/ */ class CI_DB_pdo_odbc_forge extends CI_DB_pdo_forge { @@ -57,6 +68,3 @@ class CI_DB_pdo_odbc_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_odbc_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_odbc_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php b/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php old mode 100755 new mode 100644 index 0e25bc5..b05d473 --- a/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { @@ -143,7 +154,12 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { */ public function is_write_type($sql) { - return (bool) preg_match('/^\s*"?(SET|INSERT(?![^\)]+\)\s+RETURNING)|UPDATE(?!.*\sRETURNING)|DELETE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s/i', str_replace(array("\r\n", "\r", "\n"), ' ', $sql)); + if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql)) + { + return FALSE; + } + + return parent::is_write_type($sql); } // -------------------------------------------------------------------- @@ -250,13 +266,8 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $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)); @@ -315,13 +326,13 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { $ids = array(); foreach ($values as $key => $val) { - $ids[] = $val[$index]; + $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { - $final[$field][] = 'WHEN '.$val[$index].' THEN '.$val[$field]; + $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } @@ -329,12 +340,12 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { $cases = ''; foreach ($final as $k => $v) { - $cases .= $k.' = (CASE '.$index."\n" + $cases .= $k.' = (CASE '.$val[$index]['field']."\n" .implode("\n", $v)."\n" .'ELSE '.$k.' END), '; } - $this->where($index.' IN('.implode(',', $ids).')', NULL, FALSE); + $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } @@ -371,6 +382,3 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_pgsql_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php b/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php old mode 100755 new mode 100644 index cdaa202..ff7a110 --- a/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_pgsql_forge extends CI_DB_pdo_forge { @@ -64,7 +75,7 @@ class CI_DB_pdo_pgsql_forge extends CI_DB_pdo_forge { * * @var string */ - protected $_null = 'NULL'; + protected $_null = 'NULL'; // -------------------------------------------------------------------- @@ -125,7 +136,7 @@ class CI_DB_pdo_pgsql_forge extends CI_DB_pdo_forge { if (isset($field[$i]['null'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) - .($field[$i]['null'] === TRUE ? ' DROP NOT NULL' : ' SET NOT NULL'); + .(trim($field[$i]['null']) === $this->_null ? ' DROP NOT NULL' : ' SET NOT NULL'); } if ( ! empty($field[$i]['new_name'])) @@ -133,6 +144,13 @@ class CI_DB_pdo_pgsql_forge extends CI_DB_pdo_forge { $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; @@ -150,7 +168,7 @@ class CI_DB_pdo_pgsql_forge extends CI_DB_pdo_forge { */ protected function _attr_type(&$attributes) { - // Reset field lenghts for data types that don't support it + // Reset field lengths for data types that don't support it if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== FALSE) { $attributes['CONSTRAINT'] = NULL; @@ -184,12 +202,9 @@ class CI_DB_pdo_pgsql_forge extends CI_DB_pdo_forge { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) { $field['type'] = ($field['type'] === 'NUMERIC') - ? 'BIGSERIAL' - : 'SERIAL'; + ? 'BIGSERIAL' + : 'SERIAL'; } } } - -/* End of file pdo_pgsql_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_pgsql_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php b/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php old mode 100755 new mode 100644 index a91f00b..f55d9a6 --- a/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_sqlite_driver extends CI_DB_pdo_driver { @@ -55,7 +66,7 @@ class CI_DB_pdo_sqlite_driver extends CI_DB_pdo_driver { * * @var array */ - protected $_random_keyword = ' RANDOM()'; + protected $_random_keyword = array('RANDOM()', 'RANDOM()'); // -------------------------------------------------------------------- @@ -110,17 +121,25 @@ class CI_DB_pdo_sqlite_driver extends CI_DB_pdo_driver { // -------------------------------------------------------------------- /** - * Show column query + * Fetch Field Names * - * Generates a platform-specific query string so that the column names can be fetched - * - * @param string $table - * @return string + * @param string $table Table name + * @return array */ - protected function _list_columns($table = '') + public function list_fields($table) { - // Not supported - return FALSE; + 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; } // -------------------------------------------------------------------- @@ -131,13 +150,8 @@ class CI_DB_pdo_sqlite_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; @@ -197,6 +211,3 @@ class CI_DB_pdo_sqlite_driver extends CI_DB_pdo_driver { } } - -/* End of file pdo_sqlite_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_sqlite_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php b/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php old mode 100755 new mode 100644 index 9b0725e..545b2a3 --- a/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_sqlite_forge extends CI_DB_pdo_forge { @@ -78,6 +89,7 @@ class CI_DB_pdo_sqlite_forge extends CI_DB_pdo_forge { if (version_compare($this->db->version(), '3.3', '<')) { $this->_create_table_if = FALSE; + $this->_drop_table_if = FALSE; } } @@ -89,7 +101,7 @@ class CI_DB_pdo_sqlite_forge extends CI_DB_pdo_forge { * @param string $db_name (ignored) * @return bool */ - public function create_database($db_name = '') + 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 @@ -104,7 +116,7 @@ class CI_DB_pdo_sqlite_forge extends CI_DB_pdo_forge { * @param string $db_name (ignored) * @return bool */ - public function drop_database($db_name = '') + public function drop_database($db_name) { // In SQLite, a database is dropped when we delete a file if (file_exists($this->db->database)) @@ -224,6 +236,3 @@ class CI_DB_pdo_sqlite_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_sqlite_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_sqlite_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php old mode 100755 new mode 100644 index ba004d5..84109ae --- a/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 3.0.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_sqlsrv_driver extends CI_DB_pdo_driver { @@ -172,7 +183,7 @@ class CI_DB_pdo_sqlsrv_driver extends CI_DB_pdo_driver { */ protected function _list_tables($prefix_limit = FALSE) { - return 'SELECT '.$this->escape_identifiers('name') + $sql = 'SELECT '.$this->escape_identifiers('name') .' FROM '.$this->escape_identifiers('sysobjects') .' WHERE '.$this->escape_identifiers('type')." = 'U'"; @@ -210,13 +221,8 @@ class CI_DB_pdo_sqlsrv_driver extends CI_DB_pdo_driver { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $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)); @@ -293,6 +299,9 @@ class CI_DB_pdo_sqlsrv_driver extends CI_DB_pdo_driver { // 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'; } @@ -307,7 +316,7 @@ class CI_DB_pdo_sqlsrv_driver extends CI_DB_pdo_driver { $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) + if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } @@ -354,10 +363,7 @@ class CI_DB_pdo_sqlsrv_driver extends CI_DB_pdo_driver { return parent::_insert_batch($table, $keys, $values); } - return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } } - -/* End of file pdo_sqlsrv_driver.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_sqlsrv_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php old mode 100755 new mode 100644 index 3a903c7..b23c6d4 --- a/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php +++ b/system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_sqlsrv_forge extends CI_DB_pdo_forge { @@ -100,6 +111,11 @@ class CI_DB_pdo_sqlsrv_forge extends CI_DB_pdo_forge { */ protected function _attr_type(&$attributes) { + if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) + { + unset($attributes['CONSTRAINT']); + } + switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': @@ -131,6 +147,3 @@ class CI_DB_pdo_sqlsrv_forge extends CI_DB_pdo_forge { } } - -/* End of file pdo_sqlsrv_forge.php */ -/* Location: ./system/database/drivers/pdo/subdrivers/pdo_sqlsrv_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/postgre/index.html b/system/database/drivers/postgre/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/postgre/index.html +++ b/system/database/drivers/postgre/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/postgre/postgre_driver.php b/system/database/drivers/postgre/postgre_driver.php old mode 100755 new mode 100644 index c380a7c..5ce2761 --- a/system/database/drivers/postgre/postgre_driver.php +++ b/system/database/drivers/postgre/postgre_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_driver extends CI_DB { @@ -119,9 +130,9 @@ class CI_DB_postgre_driver extends CI_DB { */ foreach (array('connect_timeout', 'options', 'sslmode', 'service') as $key) { - if (isset($this->$key) && is_string($this->key) && $this->key !== '') + if (isset($this->$key) && is_string($this->$key) && $this->$key !== '') { - $this->dsn .= $key."='".$this->key."' "; + $this->dsn .= $key."='".$this->$key."' "; } } @@ -138,22 +149,21 @@ class CI_DB_postgre_driver extends CI_DB { */ public function db_connect($persistent = FALSE) { - if ($persistent === TRUE - && ($this->conn_id = pg_pconnect($this->dsn)) - && pg_connection_status($this->conn_id) === PGSQL_CONNECTION_BAD - && pg_ping($this->conn_id) === FALSE - ) - { - return FALSE; - } - else - { - $this->conn_id = pg_connect($this->dsn); - } + $this->conn_id = ($persistent === TRUE) + ? pg_pconnect($this->dsn) + : pg_connect($this->dsn); - if ($this->conn_id && ! empty($this->schema)) + if ($this->conn_id !== FALSE) { - $this->simple_query('SET search_path TO '.$this->schema.',public'); + 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; @@ -203,10 +213,6 @@ class CI_DB_postgre_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } if ( ! $this->conn_id OR ($pg_version = pg_version($this->conn_id)) === FALSE) { @@ -218,8 +224,8 @@ class CI_DB_postgre_driver extends CI_DB { * and so we'll have to fall back to running a query in * order to get it. */ - return isset($pg_version['server']) - ? $this->data_cache['version'] = $pg_version['server'] + return (isset($pg_version['server']) && preg_match('#^(\d+\.\d+)#', $pg_version['server'], $match)) + ? $this->data_cache['version'] = $match[1] : parent::version(); } @@ -241,22 +247,10 @@ class CI_DB_postgre_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - return (bool) pg_query($this->conn_id, 'BEGIN'); } @@ -267,14 +261,8 @@ class CI_DB_postgre_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return (bool) pg_query($this->conn_id, 'COMMIT'); } @@ -285,14 +273,8 @@ class CI_DB_postgre_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return (bool) pg_query($this->conn_id, 'ROLLBACK'); } @@ -306,13 +288,18 @@ class CI_DB_postgre_driver extends CI_DB { */ public function is_write_type($sql) { - return (bool) preg_match('/^\s*"?(SET|INSERT(?![^\)]+\)\s+RETURNING)|UPDATE(?!.*\sRETURNING)|DELETE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s/i', str_replace(array("\r\n", "\r", "\n"), ' ', $sql)); + if (preg_match('#^(INSERT|UPDATE).*RETURNING\s.+(\,\s?.+)*$#is', $sql)) + { + return FALSE; + } + + return parent::is_write_type($sql); } // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string @@ -367,8 +354,7 @@ class CI_DB_postgre_driver extends CI_DB { */ public function insert_id() { - $v = pg_version($this->conn_id); - $v = isset($v['server']) ? $v['server'] : 0; // 'server' key is only available since PosgreSQL 7.4 + $v = $this->version(); $table = (func_num_args() > 0) ? func_get_arg(0) : NULL; $column = (func_num_args() > 1) ? func_get_arg(1) : NULL; @@ -453,13 +439,8 @@ class CI_DB_postgre_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $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)); @@ -489,7 +470,7 @@ class CI_DB_postgre_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -568,13 +549,13 @@ class CI_DB_postgre_driver extends CI_DB { $ids = array(); foreach ($values as $key => $val) { - $ids[] = $val[$index]; + $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { - $final[$field][] = 'WHEN '.$val[$index].' THEN '.$val[$field]; + $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } @@ -582,12 +563,12 @@ class CI_DB_postgre_driver extends CI_DB { $cases = ''; foreach ($final as $k => $v) { - $cases .= $k.' = (CASE '.$index."\n" + $cases .= $k.' = (CASE '.$val[$index]['field']."\n" .implode("\n", $v)."\n" .'ELSE '.$k.' END), '; } - $this->where($index.' IN('.implode(',', $ids).')', NULL, FALSE); + $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } @@ -636,6 +617,3 @@ class CI_DB_postgre_driver extends CI_DB { } } - -/* End of file postgre_driver.php */ -/* Location: ./system/database/drivers/postgre/postgre_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/postgre/postgre_forge.php b/system/database/drivers/postgre/postgre_forge.php old mode 100755 new mode 100644 index 8bfb66c..353ddac --- a/system/database/drivers/postgre/postgre_forge.php +++ b/system/database/drivers/postgre/postgre_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Postgre Forge Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_forge extends CI_DB_forge { @@ -57,7 +70,7 @@ class CI_DB_postgre_forge extends CI_DB_forge { * * @var string */ - protected $_null = 'NULL'; + protected $_null = 'NULL'; // -------------------------------------------------------------------- @@ -118,7 +131,7 @@ class CI_DB_postgre_forge extends CI_DB_forge { if (isset($field[$i]['null'])) { $sqls[] = $sql.' ALTER COLUMN '.$this->db->escape_identifiers($field[$i]['name']) - .($field[$i]['null'] === TRUE ? ' DROP NOT NULL' : ' SET NOT NULL'); + .(trim($field[$i]['null']) === $this->_null ? ' DROP NOT NULL' : ' SET NOT NULL'); } if ( ! empty($field[$i]['new_name'])) @@ -126,6 +139,13 @@ class CI_DB_postgre_forge extends CI_DB_forge { $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; @@ -143,7 +163,7 @@ class CI_DB_postgre_forge extends CI_DB_forge { */ protected function _attr_type(&$attributes) { - // Reset field lenghts for data types that don't support it + // Reset field lengths for data types that don't support it if (isset($attributes['CONSTRAINT']) && stripos($attributes['TYPE'], 'int') !== FALSE) { $attributes['CONSTRAINT'] = NULL; @@ -177,12 +197,9 @@ class CI_DB_postgre_forge extends CI_DB_forge { if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) { $field['type'] = ($field['type'] === 'NUMERIC') - ? 'BIGSERIAL' - : 'SERIAL'; + ? 'BIGSERIAL' + : 'SERIAL'; } } } - -/* End of file postgre_forge.php */ -/* Location: ./system/database/drivers/postgre/postgre_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/postgre/postgre_result.php b/system/database/drivers/postgre/postgre_result.php old mode 100755 new mode 100644 index ab04af1..b0054dd --- a/system/database/drivers/postgre/postgre_result.php +++ b/system/database/drivers/postgre/postgre_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,10 +42,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * This class extends the parent result class: CI_DB_result * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.3 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_result extends CI_DB_result { @@ -168,6 +180,3 @@ class CI_DB_postgre_result extends CI_DB_result { } } - -/* End of file postgre_result.php */ -/* Location: ./system/database/drivers/postgre/postgre_result.php */ \ No newline at end of file diff --git a/system/database/drivers/postgre/postgre_utility.php b/system/database/drivers/postgre/postgre_utility.php old mode 100755 new mode 100644 index fe7e3b6..450aa36 --- a/system/database/drivers/postgre/postgre_utility.php +++ b/system/database/drivers/postgre/postgre_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -29,9 +40,11 @@ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Postgre Utility Class * + * @package CodeIgniter + * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_postgre_utility extends CI_DB_utility { @@ -63,6 +76,3 @@ class CI_DB_postgre_utility extends CI_DB_utility { return $this->db->display_error('db_unsupported_feature'); } } - -/* End of file postgre_utility.php */ -/* Location: ./system/database/drivers/postgre/postgre_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite/index.html b/system/database/drivers/sqlite/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/sqlite/index.html +++ b/system/database/drivers/sqlite/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/sqlite/sqlite_driver.php b/system/database/drivers/sqlite/sqlite_driver.php old mode 100755 new mode 100644 index a5dd6e0..aec3d74 --- a/system/database/drivers/sqlite/sqlite_driver.php +++ b/system/database/drivers/sqlite/sqlite_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_driver extends CI_DB { @@ -111,24 +122,11 @@ class CI_DB_sqlite_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - - $this->simple_query('BEGIN TRANSACTION'); - return TRUE; + return $this->simple_query('BEGIN TRANSACTION'); } // -------------------------------------------------------------------- @@ -138,16 +136,9 @@ class CI_DB_sqlite_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - $this->simple_query('COMMIT'); - return TRUE; + return $this->simple_query('COMMIT'); } // -------------------------------------------------------------------- @@ -157,16 +148,9 @@ class CI_DB_sqlite_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - $this->simple_query('ROLLBACK'); - return TRUE; + return $this->simple_query('ROLLBACK'); } // -------------------------------------------------------------------- @@ -252,13 +236,8 @@ class CI_DB_sqlite_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; @@ -349,6 +328,3 @@ class CI_DB_sqlite_driver extends CI_DB { } } - -/* End of file sqlite_driver.php */ -/* Location: ./system/database/drivers/sqlite/sqlite_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite/sqlite_forge.php b/system/database/drivers/sqlite/sqlite_forge.php old mode 100755 new mode 100644 index 5a28c2b..6aa9c61 --- a/system/database/drivers/sqlite/sqlite_forge.php +++ b/system/database/drivers/sqlite/sqlite_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_forge extends CI_DB_forge { @@ -64,7 +75,7 @@ class CI_DB_sqlite_forge extends CI_DB_forge { * @param string $db_name (ignored) * @return bool */ - public function create_database($db_name = '') + 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 @@ -79,7 +90,7 @@ class CI_DB_sqlite_forge extends CI_DB_forge { * @param string $db_name (ignored) * @return bool */ - public function drop_database($db_name = '') + public function drop_database($db_name) { if ( ! file_exists($this->db->database) OR ! @unlink($this->db->database)) { @@ -192,6 +203,3 @@ class CI_DB_sqlite_forge extends CI_DB_forge { } } - -/* End of file sqlite_forge.php */ -/* Location: ./system/database/drivers/sqlite/sqlite_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite/sqlite_result.php b/system/database/drivers/sqlite/sqlite_result.php old mode 100755 new mode 100644 index 8279c31..30c93a2 --- a/system/database/drivers/sqlite/sqlite_result.php +++ b/system/database/drivers/sqlite/sqlite_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 1.3 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_result extends CI_DB_result { @@ -152,6 +162,3 @@ class CI_DB_sqlite_result extends CI_DB_result { } } - -/* End of file sqlite_result.php */ -/* Location: ./system/database/drivers/sqlite/sqlite_result.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite/sqlite_utility.php b/system/database/drivers/sqlite/sqlite_utility.php old mode 100755 new mode 100644 index 7ad040e..2c7f809 --- a/system/database/drivers/sqlite/sqlite_utility.php +++ b/system/database/drivers/sqlite/sqlite_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (http://bcit.ca/) + * @license http://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.3.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite_utility extends CI_DB_utility { @@ -48,6 +59,3 @@ class CI_DB_sqlite_utility extends CI_DB_utility { } } - -/* End of file sqlite_utility.php */ -/* Location: ./system/database/drivers/sqlite/sqlite_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite3/index.html b/system/database/drivers/sqlite3/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/sqlite3/index.html +++ b/system/database/drivers/sqlite3/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/sqlite3/sqlite3_driver.php b/system/database/drivers/sqlite3/sqlite3_driver.php old mode 100755 new mode 100644 index a7d0d08..5d057ba --- a/system/database/drivers/sqlite3/sqlite3_driver.php +++ b/system/database/drivers/sqlite3/sqlite3_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,8 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author Andrey Andreev - * @link http://codeigniter.com/user_guide/database/ - * @since Version 3.0 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite3_driver extends CI_DB { @@ -124,22 +134,10 @@ class CI_DB_sqlite3_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - return $this->conn_id->exec('BEGIN TRANSACTION'); } @@ -150,14 +148,8 @@ class CI_DB_sqlite3_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return $this->conn_id->exec('END TRANSACTION'); } @@ -168,28 +160,22 @@ class CI_DB_sqlite3_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return $this->conn_id->exec('ROLLBACK'); } // -------------------------------------------------------------------- /** - * Platform-dependant string escape + * Platform-dependent string escape * * @param string * @return string */ protected function _escape_str($str) { - return $this->conn_id->escapeString(remove_invisible_characters($str)); + return $this->conn_id->escapeString($str); } // -------------------------------------------------------------------- @@ -237,17 +223,25 @@ class CI_DB_sqlite3_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Show column query + * Fetch Field Names * - * Generates a platform-specific query string so that the column names can be fetched - * - * @param string $table - * @return string + * @param string $table Table name + * @return array */ - protected function _list_columns($table = '') + public function list_fields($table) { - // Not supported - return FALSE; + 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; } // -------------------------------------------------------------------- @@ -258,13 +252,8 @@ class CI_DB_sqlite3_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protect_identifiers($table, TRUE, NULL, FALSE).')')) === FALSE) { return FALSE; @@ -296,7 +285,7 @@ class CI_DB_sqlite3_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -353,6 +342,3 @@ class CI_DB_sqlite3_driver extends CI_DB { } } - -/* End of file sqlite3_driver.php */ -/* Location: ./system/database/drivers/sqlite3/sqlite3_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_forge.php b/system/database/drivers/sqlite3/sqlite3_forge.php old mode 100755 new mode 100644 index d79d15a..4019a95 --- a/system/database/drivers/sqlite3/sqlite3_forge.php +++ b/system/database/drivers/sqlite3/sqlite3_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author Andrey Andreev - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite3_forge extends CI_DB_forge { @@ -63,7 +74,8 @@ class CI_DB_sqlite3_forge extends CI_DB_forge { if (version_compare($this->db->version(), '3.3', '<')) { - $this->create_table_if = FALSE; + $this->_create_table_if = FALSE; + $this->_drop_table_if = FALSE; } } @@ -75,7 +87,7 @@ class CI_DB_sqlite3_forge extends CI_DB_forge { * @param string $db_name * @return bool */ - public function create_database($db_name = '') + 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 @@ -90,7 +102,7 @@ class CI_DB_sqlite3_forge extends CI_DB_forge { * @param string $db_name (ignored) * @return bool */ - public function drop_database($db_name = '') + public function drop_database($db_name) { // In SQLite, a database is dropped when we delete a file if (file_exists($this->db->database)) @@ -211,6 +223,3 @@ class CI_DB_sqlite3_forge extends CI_DB_forge { } } - -/* End of file sqlite3_forge.php */ -/* Location: ./system/database/drivers/sqlite3/sqlite3_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_result.php b/system/database/drivers/sqlite3/sqlite3_result.php old mode 100755 new mode 100644 index fb2fc4e..d656fed --- a/system/database/drivers/sqlite3/sqlite3_result.php +++ b/system/database/drivers/sqlite3/sqlite3_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author Andrey Andreev - * @link http://codeigniter.com/user_guide/database/ - * @since 3.0 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite3_result extends CI_DB_result { @@ -88,7 +98,7 @@ class CI_DB_sqlite3_result extends CI_DB_result { ); $retval = array(); - for ($i = 0, $c = $this->num_fields(); $i < $this->num_fields(); $i++) + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $retval[$i] = new stdClass(); $retval[$i]->name = $this->result_id->columnName($i); @@ -182,6 +192,3 @@ class CI_DB_sqlite3_result extends CI_DB_result { } } - -/* End of file sqlite3_result.php */ -/* Location: ./system/database/drivers/sqlite3/sqlite3_result.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_utility.php b/system/database/drivers/sqlite3/sqlite3_utility.php old mode 100755 new mode 100644 index 49dcf3d..1bdf3ae --- a/system/database/drivers/sqlite3/sqlite3_utility.php +++ b/system/database/drivers/sqlite3/sqlite3_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author Andrey Andreev - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlite3_utility extends CI_DB_utility { @@ -48,6 +59,3 @@ class CI_DB_sqlite3_utility extends CI_DB_utility { } } - -/* End of file sqlite3_utility.php */ -/* Location: ./system/database/drivers/sqlite3/sqlite3_utility.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlsrv/index.html b/system/database/drivers/sqlsrv/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/drivers/sqlsrv/index.html +++ b/system/database/drivers/sqlsrv/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/database/drivers/sqlsrv/sqlsrv_driver.php b/system/database/drivers/sqlsrv/sqlsrv_driver.php old mode 100755 new mode 100644 index ec983d5..a22a8b3 --- a/system/database/drivers/sqlsrv/sqlsrv_driver.php +++ b/system/database/drivers/sqlsrv/sqlsrv_driver.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.0.3 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.0.3 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -37,7 +48,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * @subpackage Drivers * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_driver extends CI_DB { @@ -130,13 +141,14 @@ class CI_DB_sqlsrv_driver extends CI_DB { unset($connection['UID'], $connection['PWD']); } - $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('[', ']'); + 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; } @@ -159,6 +171,7 @@ class CI_DB_sqlsrv_driver extends CI_DB { if ($this->_execute('USE '.$this->escape_identifiers($database))) { $this->database = $database; + $this->data_cache = array(); return TRUE; } @@ -185,22 +198,10 @@ class CI_DB_sqlsrv_driver extends CI_DB { /** * Begin Transaction * - * @param bool $test_mode * @return bool */ - public function trans_begin($test_mode = FALSE) + protected function _trans_begin() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - - // Reset the transaction failure flag. - // If the $test_mode flag is set to TRUE transactions will be rolled back - // even if the queries produce a successful result. - $this->_trans_failure = ($test_mode === TRUE); - return sqlsrv_begin_transaction($this->conn_id); } @@ -211,14 +212,8 @@ class CI_DB_sqlsrv_driver extends CI_DB { * * @return bool */ - public function trans_commit() + protected function _trans_commit() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return sqlsrv_commit($this->conn_id); } @@ -229,14 +224,8 @@ class CI_DB_sqlsrv_driver extends CI_DB { * * @return bool */ - public function trans_rollback() + protected function _trans_rollback() { - // When transactions are nested we only begin/commit/rollback the outermost ones - if ( ! $this->trans_enabled OR $this->_trans_depth > 0) - { - return TRUE; - } - return sqlsrv_rollback($this->conn_id); } @@ -263,9 +252,7 @@ class CI_DB_sqlsrv_driver extends CI_DB { */ public function insert_id() { - $query = $this->query('SELECT @@IDENTITY AS insert_id'); - $query = $query->row(); - return $query->insert_id; + return $this->query('SELECT SCOPE_IDENTITY() AS insert_id')->row()->insert_id; } // -------------------------------------------------------------------- @@ -281,10 +268,6 @@ class CI_DB_sqlsrv_driver extends CI_DB { { return $this->data_cache['version']; } - elseif ( ! $this->conn_id) - { - $this->initialize(); - } if ( ! $this->conn_id OR ($info = sqlsrv_server_info($this->conn_id)) === FALSE) { @@ -344,13 +327,8 @@ class CI_DB_sqlsrv_driver extends CI_DB { * @param string $table * @return array */ - public function field_data($table = '') + public function field_data($table) { - if ($table === '') - { - return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; - } - $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)); @@ -380,7 +358,7 @@ class CI_DB_sqlsrv_driver extends CI_DB { * Error * * Returns an array containing code and message of the last - * database error that has occured. + * database error that has occurred. * * @return array */ @@ -483,6 +461,9 @@ class CI_DB_sqlsrv_driver extends CI_DB { // 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'; } @@ -497,7 +478,7 @@ class CI_DB_sqlsrv_driver extends CI_DB { $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) + if (count($this->qb_select) === 0 OR strpos(implode(',', $this->qb_select), '*') !== FALSE) { $select = '*'; // Inevitable } @@ -544,7 +525,7 @@ class CI_DB_sqlsrv_driver extends CI_DB { return parent::_insert_batch($table, $keys, $values); } - return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE; } // -------------------------------------------------------------------- @@ -560,6 +541,3 @@ class CI_DB_sqlsrv_driver extends CI_DB { } } - -/* End of file sqlsrv_driver.php */ -/* Location: ./system/database/drivers/sqlsrv/sqlsrv_driver.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlsrv/sqlsrv_forge.php b/system/database/drivers/sqlsrv/sqlsrv_forge.php old mode 100755 new mode 100644 index 7938684..90c3120 --- a/system/database/drivers/sqlsrv/sqlsrv_forge.php +++ b/system/database/drivers/sqlsrv/sqlsrv_forge.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.0.3 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.0.3 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_forge extends CI_DB_forge { @@ -100,6 +111,11 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge { */ protected function _attr_type(&$attributes) { + if (isset($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') !== FALSE) + { + unset($attributes['CONSTRAINT']); + } + switch (strtoupper($attributes['TYPE'])) { case 'MEDIUMINT': @@ -131,6 +147,3 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge { } } - -/* End of file sqlsrv_forge.php */ -/* Location: ./system/database/drivers/sqlsrv/sqlsrv_forge.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlsrv/sqlsrv_result.php b/system/database/drivers/sqlsrv/sqlsrv_result.php old mode 100755 new mode 100644 index 71c429e..e2649c6 --- a/system/database/drivers/sqlsrv/sqlsrv_result.php +++ b/system/database/drivers/sqlsrv/sqlsrv_result.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 1.0 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.0.3 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -33,8 +44,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ - * @since 2.0.3 + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_result extends CI_DB_result { @@ -181,6 +191,3 @@ class CI_DB_sqlsrv_result extends CI_DB_result { } } - -/* End of file sqlsrv_result.php */ -/* Location: ./system/database/drivers/sqlsrv/sqlsrv_result.php */ \ No newline at end of file diff --git a/system/database/drivers/sqlsrv/sqlsrv_utility.php b/system/database/drivers/sqlsrv/sqlsrv_utility.php old mode 100755 new mode 100644 index b6a1fe4..6dd01a9 --- a/system/database/drivers/sqlsrv/sqlsrv_utility.php +++ b/system/database/drivers/sqlsrv/sqlsrv_utility.php @@ -2,26 +2,37 @@ /** * CodeIgniter * - * An open source application development framework for PHP 5.2.4 or newer + * An open source application development framework for PHP * - * NOTICE OF LICENSE + * This content is released under the MIT License (MIT) * - * Licensed under the Open Software License version 3.0 + * Copyright (c) 2014 - 2019, British Columbia Institute of Technology * - * This source file is subject to the Open Software License (OSL 3.0) that is - * bundled with this package in the files license.txt / license.rst. It is - * also available through the world wide web at this URL: - * http://opensource.org/licenses/OSL-3.0 - * If you did not receive a copy of the license and are unable to obtain it - * through the world wide web, please send an email to - * licensing@ellislab.com so we can send you a copy immediately. + * 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: * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) - * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) - * @link http://codeigniter.com - * @since Version 2.0.3 + * 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 CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 2.0.3 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); @@ -31,7 +42,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); * * @category Database * @author EllisLab Dev Team - * @link http://codeigniter.com/user_guide/database/ + * @link https://codeigniter.com/user_guide/database/ */ class CI_DB_sqlsrv_utility extends CI_DB_utility { @@ -64,6 +75,3 @@ class CI_DB_sqlsrv_utility extends CI_DB_utility { } } - -/* End of file sqlsrv_utility.php */ -/* Location: ./system/database/drivers/sqlsrv/sqlsrv_utility.php */ \ No newline at end of file diff --git a/system/database/index.html b/system/database/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/database/index.html +++ b/system/database/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/fonts/index.html b/system/fonts/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/fonts/index.html +++ b/system/fonts/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

Directory access is forbidden.

- \ No newline at end of file + diff --git a/system/fonts/texb.ttf b/system/fonts/texb.ttf old mode 100755 new mode 100644 diff --git a/system/helpers/array_helper.php b/system/helpers/array_helper.php old mode 100755 new mode 100644 index 2e620db..cb7eca6 --- a/system/helpers/array_helper.php +++ b/system/helpers/array_helper.php @@ -1,19 +1,41 @@ - '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200); + $defaults = array( + 'word' => '', + '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)) + if ( ! is_array($data) && empty($$key)) { - if ( ! isset($$key) OR $$key == '') - { - $$key = $val; - } + $$key = $val; } else { - $$key = ( ! isset($data[$key])) ? $val : $data[$key]; + $$key = isset($data[$key]) ? $data[$key] : $val; } } - if ($img_path == '' OR $img_url == '') - { - return FALSE; - } - - if ( ! @is_dir($img_path)) - { - return FALSE; - } - - if ( ! is_writable($img_path)) - { - return FALSE; - } - - if ( ! extension_loaded('gd')) + if ($img_path === '' OR $img_url === '' + OR ! is_dir($img_path) OR ! is_really_writable($img_path) + OR ! extension_loaded('gd')) { return FALSE; } @@ -82,21 +105,15 @@ if ( ! function_exists('create_captcha')) // Remove old images // ----------------------------------- - list($usec, $sec) = explode(" ", microtime()); - $now = ((float)$usec + (float)$sec); + $now = microtime(TRUE); $current_dir = @opendir($img_path); - while ($filename = @readdir($current_dir)) { - if ($filename != "." and $filename != ".." and $filename != "index.html") + if (in_array(substr($filename, -4), array('.jpg', '.png')) + && (str_replace(array('.jpg', '.png'), '', $filename) + $expiration) < $now) { - $name = str_replace(".jpg", "", $filename); - - if (($name + $expiration) < $now) - { - @unlink($img_path.$filename); - } + @unlink($img_path.$filename); } } @@ -106,141 +123,219 @@ if ( ! function_exists('create_captcha')) // Do we have a "word" yet? // ----------------------------------- - if ($word == '') - { - $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + if (empty($word)) + { + $word = ''; + $pool_length = strlen($pool); + $rand_max = $pool_length - 1; - $str = ''; - for ($i = 0; $i < 8; $i++) + // PHP7 or a suitable polyfill + if (function_exists('random_int')) { - $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); + 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; } - $word = $str; - } + // 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) ? rand(-($length-6), ($length-6)) : 0; - $x_axis = rand(6, (360/$length)-16); - $y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height); + $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 - if (function_exists('imagecreatetruecolor')) - { - $im = imagecreatetruecolor($img_width, $img_height); - } - else - { - $im = imagecreate($img_width, $img_height); - } + $im = function_exists('imagecreatetruecolor') + ? imagecreatetruecolor($img_width, $img_height) + : imagecreate($img_width, $img_height); // ----------------------------------- // Assign colors - // ----------------------------------- + // ---------------------------------- - $bg_color = imagecolorallocate ($im, 255, 255, 255); - $border_color = imagecolorallocate ($im, 153, 102, 102); - $text_color = imagecolorallocate ($im, 204, 153, 153); - $grid_color = imagecolorallocate($im, 255, 182, 182); - $shadow_color = imagecolorallocate($im, 255, 240, 240); + is_array($colors) OR $colors = $defaults['colors']; - // ----------------------------------- - // Create the rectangle - // ----------------------------------- + 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]); + } - ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color); + // 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; $i < ($circles * $points) - 1; $i++) + for ($i = 0, $cp = ($circles * $points) - 1; $i < $cp; $i++) { - $theta = $theta + $thetac; - $rad = $radius * ($i / $points ); + $theta += $thetac; + $rad = $radius * ($i / $points); $x = ($rad * cos($theta)) + $x_axis; $y = ($rad * sin($theta)) + $y_axis; - $theta = $theta + $thetac; + $theta += $thetac; $rad1 = $radius * (($i + 1) / $points); $x1 = ($rad1 * cos($theta)) + $x_axis; - $y1 = ($rad1 * sin($theta )) + $y_axis; - imageline($im, $x, $y, $x1, $y1, $grid_color); - $theta = $theta - $thetac; + $y1 = ($rad1 * sin($theta)) + $y_axis; + imageline($im, $x, $y, $x1, $y1, $colors['grid']); + $theta -= $thetac; } // ----------------------------------- // Write the text // ----------------------------------- - $use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE; - - if ($use_font == FALSE) + $use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext')); + if ($use_font === FALSE) { - $font_size = 5; - $x = rand(0, $img_width/($length/3)); + ($font_size > 5) && $font_size = 5; + $x = mt_rand(0, $img_width / ($length / 3)); $y = 0; } else { - $font_size = 16; - $x = rand(0, $img_width/($length/1.5)); - $y = $font_size+2; + ($font_size > 30) && $font_size = 30; + $x = mt_rand(0, $img_width / ($length / 1.5)); + $y = $font_size + 2; } - for ($i = 0; $i < strlen($word); $i++) + for ($i = 0; $i < $length; $i++) { - if ($use_font == FALSE) + if ($use_font === FALSE) { - $y = rand(0 , $img_height/2); - imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color); - $x += ($font_size*2); + $y = mt_rand(0 , $img_height / 2); + imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']); + $x += ($font_size * 2); } else { - $y = rand($img_height/2, $img_height-3); - imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1)); + $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, $border_color); + // Create the border + imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $colors['border']); // ----------------------------------- // Generate the image // ----------------------------------- + $img_url = rtrim($img_url, '/').'/'; - $img_name = $now.'.jpg'; - - ImageJPEG($im, $img_path.$img_name); - - $img = "\""; + 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); + return array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename); } } - -// ------------------------------------------------------------------------ - -/* End of file captcha_helper.php */ -/* Location: ./system/heleprs/captcha_helper.php */ \ No newline at end of file diff --git a/system/helpers/cookie_helper.php b/system/helpers/cookie_helper.php old mode 100755 new mode 100644 index 98670c1..b9c2cb6 --- a/system/helpers/cookie_helper.php +++ b/system/helpers/cookie_helper.php @@ -1,19 +1,41 @@ -input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); + get_instance()->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure, $httponly); } } // -------------------------------------------------------------------- -/** - * Fetch an item from the COOKIE array - * - * @access public - * @param string - * @param bool - * @return mixed - */ if ( ! function_exists('get_cookie')) { - function get_cookie($index = '', $xss_clean = FALSE) + /** + * Fetch an item from the COOKIE array + * + * @param string + * @param bool + * @return mixed + */ + function get_cookie($index, $xss_clean = NULL) { - $CI =& get_instance(); - - $prefix = ''; - - if ( ! isset($_COOKIE[$index]) && config_item('cookie_prefix') != '') - { - $prefix = config_item('cookie_prefix'); - } - - return $CI->input->cookie($prefix.$index, $xss_clean); + 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); } } // -------------------------------------------------------------------- -/** - * Delete a COOKIE - * - * @param mixed - * @param string the cookie domain. Usually: .yourdomain.com - * @param string the cookie path - * @param string the cookie prefix - * @return void - */ if ( ! function_exists('delete_cookie')) { - function delete_cookie($name = '', $domain = '', $path = '/', $prefix = '') + /** + * 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); } } - - -/* End of file cookie_helper.php */ -/* Location: ./system/helpers/cookie_helper.php */ \ No newline at end of file diff --git a/system/helpers/date_helper.php b/system/helpers/date_helper.php old mode 100755 new mode 100644 index 27aa482..5c660e2 --- a/system/helpers/date_helper.php +++ b/system/helpers/date_helper.php @@ -1,19 +1,41 @@ -config->item('time_reference')) == 'gmt') + if (empty($timezone)) { - $now = time(); - $system_time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now)); - - if (strlen($system_time) < 10) - { - $system_time = time(); - log_message('error', 'The Date class could not set a proper GMT timestamp so the local time() value was used.'); - } - - return $system_time; + $timezone = config_item('time_reference'); } - else + + if ($timezone === 'local' OR $timezone === date_default_timezone_get()) { return time(); } + + $datetime = new DateTime('now', new DateTimeZone($timezone)); + sscanf($datetime->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); } } // ------------------------------------------------------------------------ -/** - * Convert MySQL Style Datecodes - * - * This function is identical to PHPs date() function, - * except that it allows date codes to be formatted using - * the MySQL style, where each code letter is preceded - * with a percent sign: %Y %m %d etc... - * - * The benefit of doing dates this way is that you don't - * have to worry about escaping your text letters that - * match the date codes. - * - * @access public - * @param string - * @param integer - * @return integer - */ if ( ! function_exists('mdate')) { + /** + * 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 == '') + if ($datestr === '') + { return ''; - - if ($time == '') + } + elseif (empty($time)) + { $time = now(); + } + + $datestr = str_replace( + '%\\', + '', + preg_replace('/([a-z]+?){1}/i', '\\\\\\1', $datestr) + ); - $datestr = str_replace('%\\', '', preg_replace("/([a-z]+?){1}/i", "\\\\\\1", $datestr)); return date($datestr, $time); } } // ------------------------------------------------------------------------ -/** - * Standard Date - * - * Returns a date formatted according to the submitted standard. - * - * @access public - * @param string the chosen format - * @param integer Unix timestamp - * @return string - */ if ( ! function_exists('standard_date')) { - function standard_date($fmt = 'DATE_RFC822', $time = '') + /** + * 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) { - $formats = array( - 'DATE_ATOM' => '%Y-%m-%dT%H:%i:%s%Q', - 'DATE_COOKIE' => '%l, %d-%M-%y %H:%i:%s UTC', - 'DATE_ISO8601' => '%Y-%m-%dT%H:%i:%s%Q', - 'DATE_RFC822' => '%D, %d %M %y %H:%i:%s %O', - 'DATE_RFC850' => '%l, %d-%M-%y %H:%i:%s UTC', - 'DATE_RFC1036' => '%D, %d %M %y %H:%i:%s %O', - 'DATE_RFC1123' => '%D, %d %M %Y %H:%i:%s %O', - 'DATE_RSS' => '%D, %d %M %Y %H:%i:%s %O', - 'DATE_W3C' => '%Y-%m-%dT%H:%i:%s%Q' - ); + if (empty($time)) + { + $time = now(); + } - if ( ! isset($formats[$fmt])) + // Procedural style pre-defined constants from the DateTime extension + if (strpos($fmt, 'DATE_') !== 0 OR defined($fmt) === FALSE) { return FALSE; } - return mdate($formats[$fmt], $time); + return date(constant($fmt), $time); } } // ------------------------------------------------------------------------ -/** - * Timespan - * - * Returns a span of seconds in this format: - * 10 days 14 hours 36 minutes 47 seconds - * - * @access public - * @param integer a number of seconds - * @param integer Unix timestamp - * @return integer - */ if ( ! function_exists('timespan')) { - function timespan($seconds = 1, $time = '') + /** + * 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'); - if ( ! is_numeric($seconds)) - { - $seconds = 1; - } + is_numeric($seconds) OR $seconds = 1; + is_numeric($time) OR $time = time(); + is_numeric($units) OR $units = 7; - if ( ! is_numeric($time)) - { - $time = time(); - } + $seconds = ($time <= $seconds) ? 1 : $time - $seconds; - if ($time <= $seconds) - { - $seconds = 1; - } - else - { - $seconds = $time - $seconds; - } - - $str = ''; - $years = floor($seconds / 31536000); + $str = array(); + $years = floor($seconds / 31557600); if ($years > 0) { - $str .= $years.' '.$CI->lang->line((($years > 1) ? 'date_years' : 'date_year')).', '; + $str[] = $years.' '.$CI->lang->line($years > 1 ? 'date_years' : 'date_year'); } - $seconds -= $years * 31536000; - $months = floor($seconds / 2628000); + $seconds -= $years * 31557600; + $months = floor($seconds / 2629743); - if ($years > 0 OR $months > 0) + if (count($str) < $units && ($years > 0 OR $months > 0)) { if ($months > 0) { - $str .= $months.' '.$CI->lang->line((($months > 1) ? 'date_months' : 'date_month')).', '; + $str[] = $months.' '.$CI->lang->line($months > 1 ? 'date_months' : 'date_month'); } - $seconds -= $months * 2628000; + $seconds -= $months * 2629743; } $weeks = floor($seconds / 604800); - if ($years > 0 OR $months > 0 OR $weeks > 0) + 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')).', '; + $str[] = $weeks.' '.$CI->lang->line($weeks > 1 ? 'date_weeks' : 'date_week'); } $seconds -= $weeks * 604800; @@ -206,11 +221,11 @@ if ( ! function_exists('timespan')) $days = floor($seconds / 86400); - if ($months > 0 OR $weeks > 0 OR $days > 0) + 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')).', '; + $str[] = $days.' '.$CI->lang->line($days > 1 ? 'date_days' : 'date_day'); } $seconds -= $days * 86400; @@ -218,11 +233,11 @@ if ( ! function_exists('timespan')) $hours = floor($seconds / 3600); - if ($days > 0 OR $hours > 0) + if (count($str) < $units && ($days > 0 OR $hours > 0)) { if ($hours > 0) { - $str .= $hours.' '.$CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')).', '; + $str[] = $hours.' '.$CI->lang->line($hours > 1 ? 'date_hours' : 'date_hour'); } $seconds -= $hours * 3600; @@ -230,55 +245,63 @@ if ( ! function_exists('timespan')) $minutes = floor($seconds / 60); - if ($days > 0 OR $hours > 0 OR $minutes > 0) + 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')).', '; + $str[] = $minutes.' '.$CI->lang->line($minutes > 1 ? 'date_minutes' : 'date_minute'); } $seconds -= $minutes * 60; } - if ($str == '') + if (count($str) === 0) { - $str .= $seconds.' '.$CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')).', '; + $str[] = $seconds.' '.$CI->lang->line($seconds > 1 ? 'date_seconds' : 'date_second'); } - return substr(trim($str), 0, -1); + return implode(', ', $str); } } // ------------------------------------------------------------------------ -/** - * Number of days in a month - * - * Takes a month/year as input and returns the number of days - * for the given month/year. Takes leap years into consideration. - * - * @access public - * @param integer a numeric month - * @param integer a numeric year - * @return integer - */ if ( ! function_exists('days_in_month')) { + /** + * 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; } - - if ( ! is_numeric($year) OR strlen($year) != 4) + 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 AND $year % 100 != 0)) + if ($year % 400 === 0 OR ($year % 4 === 0 && $year % 100 !== 0)) { return 29; } @@ -291,112 +314,110 @@ if ( ! function_exists('days_in_month')) // ------------------------------------------------------------------------ -/** - * Converts a local Unix timestamp to GMT - * - * @access public - * @param integer Unix timestamp - * @return integer - */ 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 == '') + if ($time === '') + { $time = time(); + } - return mktime( gmdate("H", $time), gmdate("i", $time), gmdate("s", $time), gmdate("m", $time), gmdate("d", $time), gmdate("Y", $time)); + return mktime( + gmdate('G', $time), + gmdate('i', $time), + gmdate('s', $time), + gmdate('n', $time), + gmdate('j', $time), + gmdate('Y', $time) + ); } } // ------------------------------------------------------------------------ -/** - * Converts GMT time to a localized value - * - * Takes a Unix timestamp (in GMT) as input, and returns - * at the local value based on the timezone and DST setting - * submitted - * - * @access public - * @param integer Unix timestamp - * @param string timezone - * @param bool whether DST is active - * @return integer - */ if ( ! function_exists('gmt_to_local')) { + /** + * 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 == '') + if ($time === '') { return now(); } $time += timezones($timezone) * 3600; - if ($dst == TRUE) - { - $time += 3600; - } - - return $time; + return ($dst === TRUE) ? $time + 3600 : $time; } } // ------------------------------------------------------------------------ -/** - * Converts a MySQL Timestamp to Unix - * - * @access public - * @param integer Unix timestamp - * @return integer - */ 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('-', '', $time); - $time = str_replace(':', '', $time); - $time = str_replace(' ', '', $time); + $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) - ); + return mktime( + substr($time, 8, 2), + substr($time, 10, 2), + substr($time, 12, 2), + substr($time, 4, 2), + substr($time, 6, 2), + substr($time, 0, 4) + ); } } // ------------------------------------------------------------------------ -/** - * Unix to "Human" - * - * Formats Unix timestamp to the following prototype: 2006-08-21 11:35 PM - * - * @access public - * @param integer Unix timestamp - * @param bool whether to show seconds - * @param string format: us or euro - * @return string - */ if ( ! function_exists('unix_to_human')) { + /** + * 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).' '; + $r = date('Y', $time).'-'.date('m', $time).'-'.date('d', $time).' '; - if ($fmt == 'us') + if ($fmt === 'us') { $r .= date('h', $time).':'.date('i', $time); } @@ -410,9 +431,9 @@ if ( ! function_exists('unix_to_human')) $r .= ':'.date('s', $time); } - if ($fmt == 'us') + if ($fmt === 'us') { - $r .= ' '.date('A', $time); + return $r.' '.date('A', $time); } return $r; @@ -421,67 +442,46 @@ if ( ! function_exists('unix_to_human')) // ------------------------------------------------------------------------ -/** - * Convert "human" date to GMT - * - * Reverses the above process - * - * @access public - * @param string format: us or euro - * @return integer - */ if ( ! function_exists('human_to_unix')) { + /** + * Convert "human" date to GMT + * + * Reverses the above process + * + * @param string format: us or euro + * @return int + */ function human_to_unix($datestr = '') { - if ($datestr == '') + if ($datestr === '') { return FALSE; } - $datestr = trim($datestr); - $datestr = preg_replace("/\040+/", ' ', $datestr); + $datestr = preg_replace('/\040+/', ' ', trim($datestr)); - if ( ! preg_match('/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}(?::[0-9]{1,2})?(?:\s[AP]M)?$/i', $datestr)) + 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; } - $split = explode(' ', $datestr); + 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; - $ex = explode("-", $split['0']); - - $year = (strlen($ex['0']) == 2) ? '20'.$ex['0'] : $ex['0']; - $month = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1']; - $day = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2']; - - $ex = explode(":", $split['1']); - - $hour = (strlen($ex['0']) == 1) ? '0'.$ex['0'] : $ex['0']; - $min = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1']; - - if (isset($ex['2']) && preg_match('/[0-9]{1,2}/', $ex['2'])) + if (isset($ampm)) { - $sec = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2']; - } - else - { - // Unless specified, seconds get set to zero. - $sec = '00'; - } + $ampm = strtolower($ampm); - if (isset($split['2'])) - { - $ampm = strtolower($split['2']); - - if (substr($ampm, 0, 1) == 'p' AND $hour < 12) - $hour = $hour + 12; - - if (substr($ampm, 0, 1) == 'a' AND $hour == 12) - $hour = '00'; - - if (strlen($hour) == 1) - $hour = '0'.$hour; + if ($ampm[0] === 'p' && $hour < 12) + { + $hour += 12; + } + elseif ($ampm[0] === 'a' && $hour === 12) + { + $hour = 0; + } } return mktime($hour, $min, $sec, $month, $day, $year); @@ -490,122 +490,253 @@ if ( ! function_exists('human_to_unix')) // ------------------------------------------------------------------------ -/** - * Timezone Menu - * - * Generates a drop-down menu of timezones. - * - * @access public - * @param string timezone - * @param string classname - * @param string menu name - * @return string - */ -if ( ! function_exists('timezone_menu')) +if ( ! function_exists('nice_date')) { - function timezone_menu($default = 'UTC', $class = "", $name = 'timezones') + /** + * 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) { - $CI =& get_instance(); - $CI->lang->load('date'); - - if ($default == 'GMT') - $default = 'UTC'; - - $menu = '"; + // Date Like: YYYYMMDD + if (preg_match('/^\d{8}$/i', $bad_date, $matches)) + { + return DateTime::createFromFormat('Ymd', $bad_date)->format($format); + } - return $menu; + // 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 = ''; } } // ------------------------------------------------------------------------ -/** - * Timezones - * - * Returns an array of timezones. This is a helper function - * for various other ones in this library - * - * @access public - * @param string timezone - * @return string - */ if ( ! function_exists('timezones')) { + /** + * 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 - ); + '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 == '') + if ($tz === '') { return $zones; } - if ($tz == 'GMT') - $tz = 'UTC'; - - return ( ! isset($zones[$tz])) ? 0 : $zones[$tz]; + return isset($zones[$tz]) ? $zones[$tz] : 0; } } +// ------------------------------------------------------------------------ -/* End of file date_helper.php */ -/* Location: ./system/helpers/date_helper.php */ \ No newline at end of file +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 old mode 100755 new mode 100644 index 0c0c39c..73777bf --- a/system/helpers/directory_helper.php +++ b/system/helpers/directory_helper.php @@ -1,19 +1,41 @@ - 0) && @is_dir($source_dir.$file)) + is_dir($source_dir.$file) && $file .= DIRECTORY_SEPARATOR; + + if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir.$file)) { - $filedata[$file] = directory_map($source_dir.$file.DIRECTORY_SEPARATOR, $new_depth, $hidden); + $filedata[$file] = directory_map($source_dir.$file, $new_depth, $hidden); } else { @@ -74,7 +99,3 @@ if ( ! function_exists('directory_map')) return FALSE; } } - - -/* End of file directory_helper.php */ -/* Location: ./system/helpers/directory_helper.php */ \ No newline at end of file diff --git a/system/helpers/download_helper.php b/system/helpers/download_helper.php old mode 100755 new mode 100644 index 34e2944..d8e30ae --- a/system/helpers/download_helper.php +++ b/system/helpers/download_helper.php @@ -1,19 +1,41 @@ - 0) - { - $data =& fread($fp, filesize($file)); - } - - flock($fp, LOCK_UN); - fclose($fp); - - return $data; + return @file_get_contents($file); } } // ------------------------------------------------------------------------ -/** - * Write File - * - * Writes data to the file specified in the path. - * Creates a new file if non-existent. - * - * @access public - * @param string path to file - * @param string file data - * @return bool - */ if ( ! function_exists('write_file')) { - function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE) + /** + * Write File + * + * Writes data to the file specified in the path. + * Creates a new file if non-existent. + * + * @param string $path File path + * @param string $data Data to write + * @param string $mode fopen() mode (default: 'wb') + * @return bool + */ + function write_file($path, $data, $mode = 'wb') { if ( ! $fp = @fopen($path, $mode)) { @@ -93,35 +90,44 @@ if ( ! function_exists('write_file')) } flock($fp, LOCK_EX); - fwrite($fp, $data); + + for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result) + { + if (($result = fwrite($fp, substr($data, $written))) === FALSE) + { + break; + } + } + flock($fp, LOCK_UN); fclose($fp); - return TRUE; + return is_int($result); } } // ------------------------------------------------------------------------ -/** - * Delete Files - * - * Deletes all files contained in the supplied directory path. - * Files must be writable or owned by the system in order to be deleted. - * If the second parameter is set to TRUE, any directories contained - * within the supplied base directory will be nuked as well. - * - * @access public - * @param string path to file - * @param bool whether to delete any directories found in the path - * @return bool - */ if ( ! function_exists('delete_files')) { - function delete_files($path, $del_dir = FALSE, $level = 0) + /** + * Delete Files + * + * Deletes all files contained in the supplied directory path. + * Files must be writable or owned by the system in order to be deleted. + * If the second parameter is set to TRUE, any directories contained + * within the supplied base directory will be nuked as well. + * + * @param string $path File path + * @param bool $del_dir Whether to delete any directories found in the path + * @param bool $htdocs Whether to skip deleting .htaccess and index page files + * @param int $_level Current directory depth level (default: 0; internal use only) + * @return bool + */ + function delete_files($path, $del_dir = FALSE, $htdocs = FALSE, $_level = 0) { // Trim the trailing slash - $path = rtrim($path, DIRECTORY_SEPARATOR); + $path = rtrim($path, '/\\'); if ( ! $current_dir = @opendir($path)) { @@ -130,49 +136,44 @@ if ( ! function_exists('delete_files')) while (FALSE !== ($filename = @readdir($current_dir))) { - if ($filename != "." and $filename != "..") + if ($filename !== '.' && $filename !== '..') { - if (is_dir($path.DIRECTORY_SEPARATOR.$filename)) + $filepath = $path.DIRECTORY_SEPARATOR.$filename; + + if (is_dir($filepath) && $filename[0] !== '.' && ! is_link($filepath)) { - // Ignore empty folders - if (substr($filename, 0, 1) != '.') - { - delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1); - } + delete_files($filepath, $del_dir, $htdocs, $_level + 1); } - else + elseif ($htdocs !== TRUE OR ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) { - unlink($path.DIRECTORY_SEPARATOR.$filename); + @unlink($filepath); } } } - @closedir($current_dir); - if ($del_dir == TRUE AND $level > 0) - { - return @rmdir($path); - } + closedir($current_dir); - return TRUE; + return ($del_dir === TRUE && $_level > 0) + ? @rmdir($path) + : TRUE; } } // ------------------------------------------------------------------------ -/** - * Get Filenames - * - * Reads the specified directory and builds an array containing the filenames. - * Any sub-folders contained within the specified path are read as well. - * - * @access public - * @param string path to source - * @param bool whether to include the path as part of the filename - * @param bool internal variable to determine recursion status - do not use in calls - * @return array - */ if ( ! function_exists('get_filenames')) { + /** + * 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(); @@ -188,42 +189,41 @@ if ( ! function_exists('get_filenames')) while (FALSE !== ($file = readdir($fp))) { - if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0) + if (is_dir($source_dir.$file) && $file[0] !== '.') { get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE); } - elseif (strncmp($file, '.', 1) !== 0) + elseif ($file[0] !== '.') { - $_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file; + $_filedata[] = ($include_path === TRUE) ? $source_dir.$file : $file; } } + + closedir($fp); return $_filedata; } - else - { - return FALSE; - } + + return FALSE; } } // -------------------------------------------------------------------- -/** - * Get Directory File Information - * - * Reads the specified directory and builds an array containing the filenames, - * filesize, dates, and permissions - * - * Any sub-folders contained within the specified path are read as well. - * - * @access public - * @param string path to source - * @param bool Look only at the top level directory specified? - * @param bool internal variable to determine recursion status - do not use in calls - * @return array - */ if ( ! function_exists('get_dir_file_info')) { + /** + * 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(); @@ -238,49 +238,46 @@ if ( ! function_exists('get_dir_file_info')) $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; } - // foreach (scandir($source_dir, 1) as $file) // In addition to being PHP5+, scandir() is simply not as fast + // 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) AND strncmp($file, '.', 1) !== 0 AND $top_level_only === FALSE) + 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 (strncmp($file, '.', 1) !== 0) + elseif ($file[0] !== '.') { $_filedata[$file] = get_file_info($source_dir.$file); $_filedata[$file]['relative_path'] = $relative_path; } } + closedir($fp); return $_filedata; } - else - { - return FALSE; - } + + return FALSE; } } // -------------------------------------------------------------------- -/** -* Get File Info -* -* Given a file and path, returns the name, path, size, date modified -* Second parameter allows you to explicitly declare what information you want returned -* Options are: name, server_path, size, date, readable, writable, executable, fileperms -* Returns FALSE if the file cannot be found. -* -* @access public -* @param string path to file -* @param mixed array or comma separated string of information returned -* @return array -*/ if ( ! function_exists('get_file_info')) { + /** + * 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; @@ -296,7 +293,7 @@ if ( ! function_exists('get_file_info')) switch ($key) { case 'name': - $fileinfo['name'] = substr(strrchr($file, DIRECTORY_SEPARATOR), 1); + $fileinfo['name'] = basename($file); break; case 'server_path': $fileinfo['server_path'] = $file; @@ -311,8 +308,7 @@ if ( ! function_exists('get_file_info')) $fileinfo['readable'] = is_readable($file); break; case 'writable': - // There are known problems using is_weritable on IIS. It may not be reliable - consider fileperms() - $fileinfo['writable'] = is_writable($file); + $fileinfo['writable'] = is_really_writable($file); break; case 'executable': $fileinfo['executable'] = is_executable($file); @@ -329,104 +325,87 @@ if ( ! function_exists('get_file_info')) // -------------------------------------------------------------------- -/** - * Get Mime by Extension - * - * Translates a file extension into a mime type based on config/mimes.php. - * Returns FALSE if it can't determine the type, or open the mime config file - * - * Note: this is NOT an accurate way of determining file mime types, and is here strictly as a convenience - * It should NOT be trusted, and should certainly NOT be used for security - * - * @access public - * @param string path to file - * @return mixed - */ if ( ! function_exists('get_mime_by_extension')) { - function get_mime_by_extension($file) + /** + * 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) { - $extension = strtolower(substr(strrchr($file, '.'), 1)); - - global $mimes; + static $mimes; if ( ! is_array($mimes)) { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); - } - elseif (is_file(APPPATH.'config/mimes.php')) - { - include(APPPATH.'config/mimes.php'); - } + $mimes = get_mimes(); - if ( ! is_array($mimes)) + if (empty($mimes)) { return FALSE; } } - if (array_key_exists($extension, $mimes)) + $extension = strtolower(substr(strrchr($filename, '.'), 1)); + + if (isset($mimes[$extension])) { - if (is_array($mimes[$extension])) - { - // Multiple mime types, just give the first one - return current($mimes[$extension]); - } - else - { - return $mimes[$extension]; - } - } - else - { - return FALSE; + return is_array($mimes[$extension]) + ? current($mimes[$extension]) // Multiple mime types, just give the first one + : $mimes[$extension]; } + + return FALSE; } } // -------------------------------------------------------------------- -/** - * Symbolic Permissions - * - * Takes a numeric value representing a file's permissions and returns - * standard symbolic notation representing that value - * - * @access public - * @param int - * @return string - */ if ( ! function_exists('symbolic_permissions')) { + /** + * 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) + if (($perms & 0xC000) === 0xC000) { $symbolic = 's'; // Socket } - elseif (($perms & 0xA000) == 0xA000) + elseif (($perms & 0xA000) === 0xA000) { $symbolic = 'l'; // Symbolic Link } - elseif (($perms & 0x8000) == 0x8000) + elseif (($perms & 0x8000) === 0x8000) { $symbolic = '-'; // Regular } - elseif (($perms & 0x6000) == 0x6000) + elseif (($perms & 0x6000) === 0x6000) { $symbolic = 'b'; // Block special } - elseif (($perms & 0x4000) == 0x4000) + elseif (($perms & 0x4000) === 0x4000) { $symbolic = 'd'; // Directory } - elseif (($perms & 0x2000) == 0x2000) + elseif (($perms & 0x2000) === 0x2000) { $symbolic = 'c'; // Character special } - elseif (($perms & 0x1000) == 0x1000) + elseif (($perms & 0x1000) === 0x1000) { $symbolic = 'p'; // FIFO pipe } @@ -436,19 +415,19 @@ if ( ! function_exists('symbolic_permissions')) } // Owner - $symbolic .= (($perms & 0x0100) ? 'r' : '-'); - $symbolic .= (($perms & 0x0080) ? 'w' : '-'); - $symbolic .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); + $symbolic .= (($perms & 0x0100) ? 'r' : '-') + .(($perms & 0x0080) ? 'w' : '-') + .(($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); // Group - $symbolic .= (($perms & 0x0020) ? 'r' : '-'); - $symbolic .= (($perms & 0x0010) ? 'w' : '-'); - $symbolic .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); + $symbolic .= (($perms & 0x0020) ? 'r' : '-') + .(($perms & 0x0010) ? 'w' : '-') + .(($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); // World - $symbolic .= (($perms & 0x0004) ? 'r' : '-'); - $symbolic .= (($perms & 0x0002) ? 'w' : '-'); - $symbolic .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); + $symbolic .= (($perms & 0x0004) ? 'r' : '-') + .(($perms & 0x0002) ? 'w' : '-') + .(($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $symbolic; } @@ -456,24 +435,19 @@ if ( ! function_exists('symbolic_permissions')) // -------------------------------------------------------------------- -/** - * Octal Permissions - * - * Takes a numeric value representing a file's permissions and returns - * a three character string representing the file's octal permissions - * - * @access public - * @param int - * @return string - */ if ( ! function_exists('octal_permissions')) { + /** + * 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); } } - - -/* End of file file_helper.php */ -/* Location: ./system/helpers/file_helper.php */ \ No newline at end of file diff --git a/system/helpers/form_helper.php b/system/helpers/form_helper.php old mode 100755 new mode 100644 index 7e2c3a0..5910d8e --- a/system/helpers/form_helper.php +++ b/system/helpers/form_helper.php @@ -1,19 +1,41 @@ -config->site_url($CI->uri->uri_string()); } - // If an action is not a full URL then turn it into one - if ($action && strpos($action, '://') === FALSE) + elseif (strpos($action, '://') === FALSE) { $action = $CI->config->site_url($action); } - // If no action is provided then set to the current url - $action OR $action = $CI->config->site_url($CI->uri->uri_string()); + $attributes = _attributes_to_string($attributes); - $form = '
config->item('csrf_protection') === TRUE AND ! (strpos($action, $CI->config->base_url()) === FALSE OR strpos($form, 'method="get"'))) + if (stripos($attributes, 'method=') === FALSE) { - $hidden[$CI->security->get_csrf_token_name()] = $CI->security->get_csrf_hash(); + $attributes .= ' method="post"'; } - if (is_array($hidden) AND count($hidden) > 0) + if (stripos($attributes, 'accept-charset=') === FALSE) { - $form .= sprintf("
%s
", form_hidden($hidden)); + $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; @@ -81,19 +139,18 @@ if ( ! function_exists('form_open')) // ------------------------------------------------------------------------ -/** - * Form Declaration - Multipart type - * - * Creates the opening portion of the form, but with "multipart/form-data". - * - * @access public - * @param string the URI segments of the form destination - * @param array a key/value pair of attributes - * @param array a key/value pair hidden data - * @return string - */ if ( ! function_exists('form_open_multipart')) { + /** + * 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)) @@ -111,19 +168,19 @@ if ( ! function_exists('form_open_multipart')) // ------------------------------------------------------------------------ -/** - * Hidden Input Field - * - * Generates hidden fields. You can pass a simple key/value string or an associative - * array with multiple values. - * - * @access public - * @param mixed - * @param string - * @return string - */ if ( ! function_exists('form_hidden')) { + /** + * 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; @@ -139,18 +196,19 @@ if ( ! function_exists('form_hidden')) { form_hidden($key, $val, TRUE); } + return $form; } if ( ! is_array($value)) { - $form .= ''."\n"; + $form .= '\n"; } else { foreach ($value as $k => $v) { - $k = (is_int($k)) ? '' : $k; + $k = is_int($k) ? '' : $k; form_hidden($name.'['.$k.']', $v, TRUE); } } @@ -161,47 +219,45 @@ if ( ! function_exists('form_hidden')) // ------------------------------------------------------------------------ -/** - * Text Input Field - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ 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); + $defaults = array( + 'type' => 'text', + 'name' => is_array($data) ? '' : $data, + 'value' => $value + ); - return ""; + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Password Field - * - * Identical to the input function but adds the "password" type - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ if ( ! function_exists('form_password')) { + /** + * 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 = '') { - if ( ! is_array($data)) - { - $data = array('name' => $data); - } - + is_array($data) OR $data = array('name' => $data); $data['type'] = 'password'; return form_input($data, $value, $extra); } @@ -209,47 +265,47 @@ if ( ! function_exists('form_password')) // ------------------------------------------------------------------------ -/** - * Upload Field - * - * Identical to the input function but adds the "file" type - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ if ( ! function_exists('form_upload')) { + /** + * 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 = '') { - if ( ! is_array($data)) - { - $data = array('name' => $data); - } - + $defaults = array('type' => 'file', 'name' => ''); + is_array($data) OR $data = array('name' => $data); $data['type'] = 'file'; - return form_input($data, $value, $extra); + + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Textarea field - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ 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'); + $defaults = array( + 'name' => is_array($data) ? '' : $data, + 'cols' => '40', + 'rows' => '10' + ); if ( ! is_array($data) OR ! isset($data['value'])) { @@ -261,28 +317,29 @@ if ( ! function_exists('form_textarea')) unset($data['value']); // textareas don't use the value attribute } - $name = (is_array($data)) ? $data['name'] : $data; - return ""; + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Multi-select menu - * - * @access public - * @param string - * @param array - * @param mixed - * @param string - * @return type - */ 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 = '') { - if ( ! strpos($extra, 'multiple')) + $extra = _attributes_to_string($extra); + if (stripos($extra, 'multiple') === FALSE) { $extra .= ' multiple="multiple"'; } @@ -293,91 +350,117 @@ if ( ! function_exists('form_multiselect')) // -------------------------------------------------------------------- -/** - * Drop-down Menu - * - * @access public - * @param string - * @param array - * @param string - * @param string - * @return string - */ if ( ! function_exists('form_dropdown')) { - function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '') + /** + * 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 = '') { - if ( ! is_array($selected)) + $defaults = array(); + + if (is_array($data)) { - $selected = array($selected); + 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 (count($selected) === 0) + if (empty($selected)) { - // If the form name appears in the $_POST array we have a winner! - if (isset($_POST[$name])) + if (is_array($data)) { - $selected = array($_POST[$name]); + if (isset($data['name'], $_POST[$data['name']])) + { + $selected = array($_POST[$data['name']]); + } + } + elseif (isset($_POST[$data])) + { + $selected = array($_POST[$data]); } } - if ($extra != '') $extra = ' '.$extra; + $extra = _attributes_to_string($extra); - $multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : ''; + $multiple = (count($selected) > 1 && stripos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : ''; - $form = '\n"; foreach ($options as $key => $val) { $key = (string) $key; - if (is_array($val) && ! empty($val)) + if (is_array($val)) { - $form .= ''."\n"; + if (empty($val)) + { + continue; + } + + $form .= '\n"; foreach ($val as $optgroup_key => $optgroup_val) { - $sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : ''; - - $form .= '\n"; + $sel = in_array($optgroup_key, $selected) ? ' selected="selected"' : ''; + $form .= '\n"; } - $form .= ''."\n"; + $form .= "\n"; } else { - $sel = (in_array($key, $selected)) ? ' selected="selected"' : ''; - - $form .= '\n"; + $form .= '\n"; } } - $form .= ''; - - return $form; + return $form."\n"; } } // ------------------------------------------------------------------------ -/** - * Checkbox Field - * - * @access public - * @param mixed - * @param string - * @param bool - * @param string - * @return string - */ 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); + $defaults = array('type' => 'checkbox', 'name' => ( ! is_array($data) ? $data : ''), 'value' => $value); - if (is_array($data) AND array_key_exists('checked', $data)) + if (is_array($data) && array_key_exists('checked', $data)) { $checked = $data['checked']; @@ -400,167 +483,159 @@ if ( ! function_exists('form_checkbox')) unset($defaults['checked']); } - return ""; + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Radio Button - * - * @access public - * @param mixed - * @param string - * @param bool - * @param string - * @return string - */ 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 = '') { - if ( ! is_array($data)) - { - $data = array('name' => $data); - } - + is_array($data) OR $data = array('name' => $data); $data['type'] = 'radio'; + return form_checkbox($data, $value, $checked, $extra); } } // ------------------------------------------------------------------------ -/** - * Submit Button - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ if ( ! function_exists('form_submit')) { + /** + * 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); + $defaults = array( + 'type' => 'submit', + 'name' => is_array($data) ? '' : $data, + 'value' => $value + ); - return ""; + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Reset Button - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ 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); + $defaults = array( + 'type' => 'reset', + 'name' => is_array($data) ? '' : $data, + 'value' => $value + ); - return ""; + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Form Button - * - * @access public - * @param mixed - * @param string - * @param string - * @return string - */ 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'); + $defaults = array( + 'name' => is_array($data) ? '' : $data, + 'type' => 'button' + ); - if ( is_array($data) AND isset($data['content'])) + if (is_array($data) && isset($data['content'])) { $content = $data['content']; unset($data['content']); // content is not an attribute } - return ""; + return '\n"; } } // ------------------------------------------------------------------------ -/** - * Form Label Tag - * - * @access public - * @param string The text to appear onscreen - * @param string The id the label applies to - * @param string Additional attributes - * @return string - */ if ( ! function_exists('form_label')) { + /** + * 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 = ' 0) - { - foreach ($attributes as $key => $val) - { - $label .= ' '.$key.'="'.$val.'"'; - } - } + $label .= _attributes_to_string($attributes); - $label .= ">$label_text"; - - return $label; + return $label.'>'.$label_text.''; } } // ------------------------------------------------------------------------ -/** - * Fieldset Tag - * - * Used to produce
text. To close fieldset - * use form_fieldset_close() - * - * @access public - * @param string The legend text - * @param string Additional attributes - * @return string - */ + if ( ! function_exists('form_fieldset')) { + /** + * 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 !== '') { - $fieldset .= "$legend_text\n"; + return $fieldset.''.$legend_text."\n"; } return $fieldset; @@ -569,306 +644,250 @@ if ( ! function_exists('form_fieldset')) // ------------------------------------------------------------------------ -/** - * Fieldset Close Tag - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('form_fieldset_close')) { + /** + * Fieldset Close Tag + * + * @param string + * @return string + */ function form_fieldset_close($extra = '') { - return "
".$extra; + return '
'.$extra; } } // ------------------------------------------------------------------------ -/** - * Form Close Tag - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('form_close')) { + /** + * Form Close Tag + * + * @param string + * @return string + */ function form_close($extra = '') { - return "".$extra; + return ''.$extra; } } // ------------------------------------------------------------------------ -/** - * Form Prep - * - * Formats text so that it can be safely placed in a form field in the event it has HTML tags. - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('form_prep')) { - function form_prep($str = '', $field_name = '') + /** + * 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) { - static $prepped_fields = array(); - - // if the field name is an array we do this recursively - if (is_array($str)) - { - foreach ($str as $key => $val) - { - $str[$key] = form_prep($val); - } - - return $str; - } - - if ($str === '') - { - return ''; - } - - // we've already prepped a field with this name - // @todo need to figure out a way to namespace this so - // that we know the *exact* field and not just one with - // the same name - if (isset($prepped_fields[$field_name])) - { - return $str; - } - - $str = htmlspecialchars($str); - - // In case htmlspecialchars misses these. - $str = str_replace(array("'", '"'), array("'", """), $str); - - if ($field_name != '') - { - $prepped_fields[$field_name] = $field_name; - } - - return $str; + return html_escape($str, TRUE); } } // ------------------------------------------------------------------------ -/** - * Form Value - * - * Grabs a value from the POST array for the specified field so you can - * re-populate an input field or textarea. If Form Validation - * is active it retrieves the info from the validation class - * - * @access public - * @param string - * @return mixed - */ if ( ! function_exists('set_value')) { - function set_value($field = '', $default = '') + /** + * 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) { - if (FALSE === ($OBJ =& _get_validation_object())) - { - if ( ! isset($_POST[$field])) - { - return $default; - } + $CI =& get_instance(); - return form_prep($_POST[$field], $field); - } + $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); - return form_prep($OBJ->set_value($field, $default), $field); + isset($value) OR $value = $default; + return ($html_escape) ? html_escape($value) : $value; } } // ------------------------------------------------------------------------ -/** - * Set Select - * - * Let's you set the selected value of a menu via data in the POST array. + * If Form Validation is active it retrieves the info from the validation class + * + * @param string + * @param string + * @param bool + * @return string + */ + function set_select($field, $value = '', $default = FALSE) { - $OBJ =& _get_validation_object(); + $CI =& get_instance(); - if ($OBJ === FALSE) + if (isset($CI->form_validation) && is_object($CI->form_validation) && $CI->form_validation->has_rule($field)) { - if ( ! isset($_POST[$field])) + return $CI->form_validation->set_select($field, $value, $default); + } + elseif (($input = $CI->input->post($field, FALSE)) === NULL) + { + return ($default === TRUE) ? ' selected="selected"' : ''; + } + + $value = (string) $value; + if (is_array($input)) + { + // Note: in_array('', array(0)) returns TRUE, do not use it + foreach ($input as &$v) { - if (count($_POST) === 0 AND $default == TRUE) + if ($value === $v) { return ' selected="selected"'; } - return ''; } - $field = $_POST[$field]; - - if (is_array($field)) - { - if ( ! in_array($value, $field)) - { - return ''; - } - } - else - { - if (($field == '' OR $value == '') OR ($field != $value)) - { - return ''; - } - } - - return ' selected="selected"'; + return ''; } - return $OBJ->set_select($field, $value, $default); + return ($input === $value) ? ' selected="selected"' : ''; } } // ------------------------------------------------------------------------ -/** - * Set Checkbox - * - * Let's you set the selected value of a checkbox via the value in the POST array. - * If Form Validation is active it retrieves the info from the validation class - * - * @access public - * @param string - * @param string - * @param bool - * @return string - */ if ( ! function_exists('set_checkbox')) { - function set_checkbox($field = '', $value = '', $default = FALSE) + /** + * Set Checkbox + * + * Let's you set the selected value of a checkbox via the value in the POST array. + * If Form Validation is active it retrieves the info from the validation class + * + * @param string + * @param string + * @param bool + * @return string + */ + function set_checkbox($field, $value = '', $default = FALSE) { - $OBJ =& _get_validation_object(); + $CI =& get_instance(); - if ($OBJ === FALSE) + if (isset($CI->form_validation) && is_object($CI->form_validation) && $CI->form_validation->has_rule($field)) { - if ( ! isset($_POST[$field])) + return $CI->form_validation->set_checkbox($field, $value, $default); + } + + // Form inputs are always strings ... + $value = (string) $value; + $input = $CI->input->post($field, FALSE); + + if (is_array($input)) + { + // Note: in_array('', array(0)) returns TRUE, do not use it + foreach ($input as &$v) { - if (count($_POST) === 0 AND $default == TRUE) + if ($value === $v) { return ' checked="checked"'; } - return ''; } - $field = $_POST[$field]; - - if (is_array($field)) - { - if ( ! in_array($value, $field)) - { - return ''; - } - } - else - { - if (($field == '' OR $value == '') OR ($field != $value)) - { - return ''; - } - } - - return ' checked="checked"'; + return ''; } - return $OBJ->set_checkbox($field, $value, $default); + // Unchecked checkbox and radio inputs are not even submitted by browsers ... + if ($CI->input->method() === 'post') + { + return ($input === $value) ? ' checked="checked"' : ''; + } + + return ($default === TRUE) ? ' checked="checked"' : ''; } } // ------------------------------------------------------------------------ -/** - * Set Radio - * - * Let's you set the selected value of a radio field via info in the POST array. - * If Form Validation is active it retrieves the info from the validation class - * - * @access public - * @param string - * @param string - * @param bool - * @return string - */ if ( ! function_exists('set_radio')) { - function set_radio($field = '', $value = '', $default = FALSE) + /** + * Set Radio + * + * Let's you set the selected value of a radio field via info in the POST array. + * If Form Validation is active it retrieves the info from the validation class + * + * @param string $field + * @param string $value + * @param bool $default + * @return string + */ + function set_radio($field, $value = '', $default = FALSE) { - $OBJ =& _get_validation_object(); + $CI =& get_instance(); - if ($OBJ === FALSE) + if (isset($CI->form_validation) && is_object($CI->form_validation) && $CI->form_validation->has_rule($field)) { - if ( ! isset($_POST[$field])) + return $CI->form_validation->set_radio($field, $value, $default); + } + + // Form inputs are always strings ... + $value = (string) $value; + $input = $CI->input->post($field, FALSE); + + if (is_array($input)) + { + // Note: in_array('', array(0)) returns TRUE, do not use it + foreach ($input as &$v) { - if (count($_POST) === 0 AND $default == TRUE) + if ($value === $v) { return ' checked="checked"'; } - return ''; } - $field = $_POST[$field]; - - if (is_array($field)) - { - if ( ! in_array($value, $field)) - { - return ''; - } - } - else - { - if (($field == '' OR $value == '') OR ($field != $value)) - { - return ''; - } - } - - return ' checked="checked"'; + return ''; } - return $OBJ->set_radio($field, $value, $default); + // Unchecked checkbox and radio inputs are not even submitted by browsers ... + if ($CI->input->method() === 'post') + { + return ($input === $value) ? ' checked="checked"' : ''; + } + + return ($default === TRUE) ? ' checked="checked"' : ''; } } // ------------------------------------------------------------------------ -/** - * Form Error - * - * Returns the error for a specific form field. This is a helper for the - * form validation class. - * - * @access public - * @param string - * @param string - * @param string - * @return string - */ if ( ! function_exists('form_error')) { + /** + * Form Error + * + * Returns the error for a specific form field. This is a helper for the + * form validation class. + * + * @param string + * @param string + * @param string + * @return string + */ function form_error($field = '', $prefix = '', $suffix = '') { if (FALSE === ($OBJ =& _get_validation_object())) @@ -882,19 +901,18 @@ if ( ! function_exists('form_error')) // ------------------------------------------------------------------------ -/** - * Validation Error String - * - * Returns all the errors associated with a form submission. This is a helper - * function for the form validation class. - * - * @access public - * @param string - * @param string - * @return string - */ if ( ! function_exists('validation_errors')) { + /** + * Validation Error String + * + * Returns all the errors associated with a form submission. This is a helper + * function for the form validation class. + * + * @param string + * @param string + * @return string + */ function validation_errors($prefix = '', $suffix = '') { if (FALSE === ($OBJ =& _get_validation_object())) @@ -908,18 +926,17 @@ if ( ! function_exists('validation_errors')) // ------------------------------------------------------------------------ -/** - * Parse the form attributes - * - * Helper function used by some of the form helpers - * - * @access private - * @param array - * @param array - * @return string - */ if ( ! function_exists('_parse_form_attributes')) { + /** + * Parse the form attributes + * + * Helper function used by some of the form helpers + * + * @param array $attributes List of attributes + * @param array $default Default values + * @return string + */ function _parse_form_attributes($attributes, $default) { if (is_array($attributes)) @@ -943,12 +960,16 @@ if ( ! function_exists('_parse_form_attributes')) foreach ($default as $key => $val) { - if ($key == 'value') + if ($key === 'value') { - $val = form_prep($val, $default['name']); + $val = html_escape($val); + } + elseif ($key === 'name' && ! strlen($default['name'])) + { + continue; } - $att .= $key . '="' . $val . '" '; + $att .= $key.'="'.$val.'" '; } return $att; @@ -957,54 +978,32 @@ if ( ! function_exists('_parse_form_attributes')) // ------------------------------------------------------------------------ -/** - * Attributes To String - * - * Helper function used by some of the form helpers - * - * @access private - * @param mixed - * @param bool - * @return string - */ if ( ! function_exists('_attributes_to_string')) { - function _attributes_to_string($attributes, $formtag = FALSE) + /** + * Attributes To String + * + * Helper function used by some of the form helpers + * + * @param mixed + * @return string + */ + function _attributes_to_string($attributes) { - if (is_string($attributes) AND strlen($attributes) > 0) + if (empty($attributes)) { - if ($formtag == TRUE AND strpos($attributes, 'method=') === FALSE) - { - $attributes .= ' method="post"'; - } - - if ($formtag == TRUE AND strpos($attributes, 'accept-charset=') === FALSE) - { - $attributes .= ' accept-charset="'.strtolower(config_item('charset')).'"'; - } - - return ' '.$attributes; + return ''; } - if (is_object($attributes) AND count($attributes) > 0) + if (is_object($attributes)) { - $attributes = (array)$attributes; + $attributes = (array) $attributes; } - if (is_array($attributes) AND count($attributes) > 0) + if (is_array($attributes)) { $atts = ''; - if ( ! isset($attributes['method']) AND $formtag === TRUE) - { - $atts .= ' method="post"'; - } - - if ( ! isset($attributes['accept-charset']) AND $formtag === TRUE) - { - $atts .= ' accept-charset="'.strtolower(config_item('charset')).'"'; - } - foreach ($attributes as $key => $val) { $atts .= ' '.$key.'="'.$val.'"'; @@ -1012,43 +1011,45 @@ if ( ! function_exists('_attributes_to_string')) return $atts; } + + if (is_string($attributes)) + { + return ' '.$attributes; + } + + return FALSE; } } // ------------------------------------------------------------------------ -/** - * Validation Object - * - * Determines what the form validation class was instantiated as, fetches - * the object and returns it. - * - * @access private - * @return mixed - */ if ( ! function_exists('_get_validation_object')) { + /** + * Validation Object + * + * Determines what the form validation class was instantiated as, fetches + * the object and returns it. + * + * @return mixed + */ function &_get_validation_object() { $CI =& get_instance(); // We set this as a variable since we're returning by reference. $return = FALSE; - - if (FALSE !== ($object = $CI->load->is_loaded('form_validation'))) + + if (FALSE !== ($object = $CI->load->is_loaded('Form_validation'))) { if ( ! isset($CI->$object) OR ! is_object($CI->$object)) { return $return; } - + return $CI->$object; } - + return $return; } } - - -/* End of file form_helper.php */ -/* Location: ./system/helpers/form_helper.php */ diff --git a/system/helpers/html_helper.php b/system/helpers/html_helper.php old mode 100755 new mode 100644 index 8e6d393..76adcb2 --- a/system/helpers/html_helper.php +++ b/system/helpers/html_helper.php @@ -1,19 +1,41 @@ -".$data.""; + return ''.$data.''; } } // ------------------------------------------------------------------------ -/** - * Unordered List - * - * Generates an HTML unordered list from an single or multi-dimensional array. - * - * @access public - * @param array - * @param mixed - * @return string - */ if ( ! function_exists('ul')) { + /** + * Unordered List + * + * Generates an HTML unordered list from an single or multi-dimensional array. + * + * @param array + * @param mixed + * @return string + */ function ul($list, $attributes = '') { return _list('ul', $list, $attributes); @@ -69,18 +88,17 @@ if ( ! function_exists('ul')) // ------------------------------------------------------------------------ -/** - * Ordered List - * - * Generates an HTML ordered list from an single or multi-dimensional array. - * - * @access public - * @param array - * @param mixed - * @return string - */ if ( ! function_exists('ol')) { + /** + * Ordered List + * + * Generates an HTML ordered list from an single or multi-dimensional array. + * + * @param array + * @param mixed + * @return string + */ function ol($list, $attributes = '') { return _list('ol', $list, $attributes); @@ -89,21 +107,20 @@ if ( ! function_exists('ol')) // ------------------------------------------------------------------------ -/** - * Generates the list - * - * Generates an HTML ordered list from an single or multi-dimensional array. - * - * @access private - * @param string - * @param mixed - * @param mixed - * @param integer - * @return string - */ if ( ! function_exists('_list')) { - function _list($type = 'ul', $list, $attributes = '', $depth = 0) + /** + * Generates the list + * + * Generates an HTML ordered list from an single or multi-dimensional array. + * + * @param string + * @param mixed + * @param mixed + * @param int + * @return string + */ + function _list($type = 'ul', $list = array(), $attributes = '', $depth = 0) { // If an array wasn't submitted there's nothing to do... if ( ! is_array($list)) @@ -112,25 +129,10 @@ if ( ! function_exists('_list')) } // Set the indentation based on the depth - $out = str_repeat(" ", $depth); + $out = str_repeat(' ', $depth) + // Write the opening list tag + .'<'.$type._stringify_attributes($attributes).">\n"; - // Were any attributes submitted? If so generate a string - if (is_array($attributes)) - { - $atts = ''; - foreach ($attributes as $key => $val) - { - $atts .= ' ' . $key . '="' . $val . '"'; - } - $attributes = $atts; - } - elseif (is_string($attributes) AND strlen($attributes) > 0) - { - $attributes = ' '. $attributes; - } - - // Write the opening list tag - $out .= "<".$type.$attributes.">\n"; // Cycle through the list elements. If an array is // encountered we will recursively call _list() @@ -140,8 +142,7 @@ if ( ! function_exists('_list')) { $_last_list_item = $key; - $out .= str_repeat(" ", $depth + 2); - $out .= "
  • "; + $out .= str_repeat(' ', $depth + 2).'
  • '; if ( ! is_array($val)) { @@ -149,55 +150,32 @@ if ( ! function_exists('_list')) } else { - $out .= $_last_list_item."\n"; - $out .= _list($type, $val, '', $depth + 4); - $out .= str_repeat(" ", $depth + 2); + $out .= $_last_list_item."\n"._list($type, $val, '', $depth + 4).str_repeat(' ', $depth + 2); } $out .= "
  • \n"; } - // Set the indentation for the closing tag - $out .= str_repeat(" ", $depth); - - // Write the closing list tag - $out .= "\n"; - - return $out; + // Set the indentation for the closing tag and apply it + return $out.str_repeat(' ', $depth).'\n"; } } // ------------------------------------------------------------------------ -/** - * Generates HTML BR tags based on number supplied - * - * @access public - * @param integer - * @return string - */ -if ( ! function_exists('br')) -{ - function br($num = 1) - { - return str_repeat("
    ", $num); - } -} - -// ------------------------------------------------------------------------ - -/** - * Image - * - * Generates an element - * - * @access public - * @param mixed - * @return string - */ if ( ! function_exists('img')) { - function img($src = '', $index_page = FALSE) + /** + * Image + * + * Generates an element + * + * @param mixed + * @param bool + * @param mixed + * @return string + */ + function img($src = '', $index_page = FALSE, $attributes = '') { if ( ! is_array($src) ) { @@ -212,112 +190,101 @@ if ( ! function_exists('img')) $img = '$v) + foreach ($src as $k => $v) { - - if ($k == 'src' AND strpos($v, '://') === FALSE) + if ($k === 'src' && ! preg_match('#^(data:[a-z,;])|(([a-z]+:)?(?config->site_url($v).'"'; + $img .= ' src="'.get_instance()->config->site_url($v).'"'; } else { - $img .= ' src="'.$CI->config->slash_item('base_url').$v.'"'; + $img .= ' src="'.get_instance()->config->base_url($v).'"'; } } else { - $img .= " $k=\"$v\""; + $img .= ' '.$k.'="'.$v.'"'; } } - $img .= '/>'; - - return $img; + return $img._stringify_attributes($attributes).' />'; } } // ------------------------------------------------------------------------ -/** - * Doctype - * - * Generates a page document type declaration - * - * Valid options are xhtml-11, xhtml-strict, xhtml-trans, xhtml-frame, - * html4-strict, html4-trans, and html4-frame. Values are saved in the - * doctypes config file. - * - * @access public - * @param string type The doctype to be generated - * @return string - */ if ( ! function_exists('doctype')) { + /** + * Doctype + * + * Generates a page document type declaration + * + * Examples of valid options: html5, xhtml-11, xhtml-strict, xhtml-trans, + * xhtml-frame, html4-strict, html4-trans, and html4-frame. + * All values are saved in the doctypes config file. + * + * @param string type The doctype to be generated + * @return string + */ function doctype($type = 'xhtml1-strict') { - global $_doctypes; + static $doctypes; - if ( ! is_array($_doctypes)) + if ( ! is_array($doctypes)) { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php'); - } - elseif (is_file(APPPATH.'config/doctypes.php')) + if (file_exists(APPPATH.'config/doctypes.php')) { include(APPPATH.'config/doctypes.php'); } - if ( ! is_array($_doctypes)) + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php')) { + include(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php'); + } + + if (empty($_doctypes) OR ! is_array($_doctypes)) + { + $doctypes = array(); return FALSE; } + + $doctypes = $_doctypes; } - if (isset($_doctypes[$type])) - { - return $_doctypes[$type]; - } - else - { - return FALSE; - } + return isset($doctypes[$type]) ? $doctypes[$type] : FALSE; } } // ------------------------------------------------------------------------ -/** - * Link - * - * Generates link to a CSS file - * - * @access public - * @param mixed stylesheet hrefs or an array - * @param string rel - * @param string type - * @param string title - * @param string media - * @param boolean should index_page be added to the css path - * @return string - */ if ( ! function_exists('link_tag')) { + /** + * Link + * + * Generates link to a CSS file + * + * @param mixed stylesheet hrefs or an array + * @param string rel + * @param string type + * @param string title + * @param string media + * @param bool should index_page be added to the css path + * @return string + */ function link_tag($href = '', $rel = 'stylesheet', $type = 'text/css', $title = '', $media = '', $index_page = FALSE) { $CI =& get_instance(); - $link = '$v) + foreach ($href as $k => $v) { - if ($k == 'href' AND strpos($v, '://') === FALSE) + if ($k === 'href' && ! preg_match('#^([a-z]+:)?//#i', $v)) { if ($index_page === TRUE) { @@ -325,20 +292,18 @@ if ( ! function_exists('link_tag')) } else { - $link .= 'href="'.$CI->config->slash_item('base_url').$v.'" '; + $link .= 'href="'.$CI->config->base_url($v).'" '; } } else { - $link .= "$k=\"$v\" "; + $link .= $k.'="'.$v.'" '; } } - - $link .= "/>"; } else { - if ( strpos($href, '://') !== FALSE) + if (preg_match('#^([a-z]+:)?//#i', $href)) { $link .= 'href="'.$href.'" '; } @@ -348,40 +313,39 @@ if ( ! function_exists('link_tag')) } else { - $link .= 'href="'.$CI->config->slash_item('base_url').$href.'" '; + $link .= 'href="'.$CI->config->base_url($href).'" '; } $link .= 'rel="'.$rel.'" type="'.$type.'" '; - if ($media != '') + if ($media !== '') { $link .= 'media="'.$media.'" '; } - if ($title != '') + if ($title !== '') { $link .= 'title="'.$title.'" '; } - - $link .= '/>'; } - - return $link; + return $link."/>\n"; } } // ------------------------------------------------------------------------ -/** - * Generates meta tags from an array of key/values - * - * @access public - * @param array - * @return string - */ if ( ! function_exists('meta')) { + /** + * Generates meta tags from an array of key/values + * + * @param array + * @param string + * @param string + * @param string + * @return string + */ function meta($name = '', $content = '', $type = 'name', $newline = "\n") { // Since we allow the data to be passes as a string, a simple array @@ -390,22 +354,19 @@ if ( ! function_exists('meta')) { $name = array(array('name' => $name, 'content' => $content, 'type' => $type, 'newline' => $newline)); } - else + elseif (isset($name['name'])) { // Turn single array into multidimensional - if (isset($name['name'])) - { - $name = array($name); - } + $name = array($name); } $str = ''; foreach ($name as $meta) { - $type = ( ! isset($meta['type']) OR $meta['type'] == 'name') ? 'name' : 'http-equiv'; - $name = ( ! isset($meta['name'])) ? '' : $meta['name']; - $content = ( ! isset($meta['content'])) ? '' : $meta['content']; - $newline = ( ! isset($meta['newline'])) ? "\n" : $meta['newline']; + $type = (isset($meta['type']) && $meta['type'] !== 'name') ? 'http-equiv' : 'name'; + $name = isset($meta['name']) ? $meta['name'] : ''; + $content = isset($meta['content']) ? $meta['content'] : ''; + $newline = isset($meta['newline']) ? $meta['newline'] : "\n"; $str .= ''.$newline; } @@ -416,21 +377,34 @@ if ( ! function_exists('meta')) // ------------------------------------------------------------------------ -/** - * Generates non-breaking space entities based on number supplied - * - * @access public - * @param integer - * @return string - */ -if ( ! function_exists('nbs')) +if ( ! function_exists('br')) { - function nbs($num = 1) + /** + * Generates HTML BR tags based on number supplied + * + * @deprecated 3.0.0 Use str_repeat() instead + * @param int $count Number of times to repeat the tag + * @return string + */ + function br($count = 1) { - return str_repeat(" ", $num); + return str_repeat('
    ', $count); } } +// ------------------------------------------------------------------------ -/* End of file html_helper.php */ -/* Location: ./system/helpers/html_helper.php */ \ No newline at end of file +if ( ! function_exists('nbs')) +{ + /** + * Generates non-breaking space entities based on number supplied + * + * @deprecated 3.0.0 Use str_repeat() instead + * @param int + * @return string + */ + function nbs($num = 1) + { + return str_repeat(' ', $num); + } +} diff --git a/system/helpers/index.html b/system/helpers/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/helpers/index.html +++ b/system/helpers/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file + diff --git a/system/helpers/inflector_helper.php b/system/helpers/inflector_helper.php old mode 100755 new mode 100644 index e93ada0..1c14f4a --- a/system/helpers/inflector_helper.php +++ b/system/helpers/inflector_helper.php @@ -1,19 +1,41 @@ - '\1ix', - '/(vert|ind)ices$/' => '\1ex', - '/^(ox)en/' => '\1', - '/(alias)es$/' => '\1', - '/([octop|vir])i$/' => '\1us', - '/(cris|ax|test)es$/' => '\1is', - '/(shoe)s$/' => '\1', - '/(o)es$/' => '\1', - '/(bus|campus)es$/' => '\1', - '/([m|l])ice$/' => '\1ouse', - '/(x|ch|ss|sh)es$/' => '\1', - '/(m)ovies$/' => '\1\2ovie', - '/(s)eries$/' => '\1\2eries', - '/([^aeiouy]|qu)ies$/' => '\1y', - '/([lr])ves$/' => '\1f', - '/(tive)s$/' => '\1', - '/(hive)s$/' => '\1', - '/([^f])ves$/' => '\1fe', - '/(^analy)ses$/' => '\1sis', + '/(matr)ices$/' => '\1ix', + '/(vert|ind)ices$/' => '\1ex', + '/^(ox)en/' => '\1', + '/(alias)es$/' => '\1', + '/([octop|vir])i$/' => '\1us', + '/(cris|ax|test)es$/' => '\1is', + '/(shoe)s$/' => '\1', + '/(o)es$/' => '\1', + '/(bus|campus)es$/' => '\1', + '/([m|l])ice$/' => '\1ouse', + '/(x|ch|ss|sh)es$/' => '\1', + '/(m)ovies$/' => '\1\2ovie', + '/(s)eries$/' => '\1\2eries', + '/([^aeiouy]|qu)ies$/' => '\1y', + '/([lr])ves$/' => '\1f', + '/(tive)s$/' => '\1', + '/(hive)s$/' => '\1', + '/([^f])ves$/' => '\1fe', + '/(^analy)ses$/' => '\1sis', '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis', - '/([ti])a$/' => '\1um', - '/(p)eople$/' => '\1\2erson', - '/(m)en$/' => '\1an', - '/(s)tatuses$/' => '\1\2tatus', - '/(c)hildren$/' => '\1\2hild', - '/(n)ews$/' => '\1\2ews', - '/([^u])s$/' => '\1', + '/([ti])a$/' => '\1um', + '/(p)eople$/' => '\1\2erson', + '/(m)en$/' => '\1an', + '/(s)tatuses$/' => '\1\2tatus', + '/(c)hildren$/' => '\1\2hild', + '/(n)ews$/' => '\1\2ews', + '/(quiz)zes$/' => '\1', + '/([^us])s$/' => '\1' ); - + foreach ($singular_rules as $rule => $replacement) { if (preg_match($rule, $result)) @@ -88,23 +114,27 @@ if ( ! function_exists('singular')) // -------------------------------------------------------------------- -/** - * Plural - * - * Takes a singular word and makes it plural - * - * @access public - * @param string - * @param bool - * @return str - */ if ( ! function_exists('plural')) { - function plural($str, $force = FALSE) + /** + * Plural + * + * Takes a singular word and makes it plural + * + * @param string $str Input string + * @return string + */ + function plural($str) { $result = strval($str); - + + if ( ! word_is_countable($result)) + { + return $result; + } + $plural_rules = array( + '/(quiz)$/' => '\1zes', // quizzes '/^(ox)$/' => '\1\2en', // ox '/([m|l])ouse$/' => '\1ice', // mouse, louse '/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index @@ -119,7 +149,7 @@ if ( ! function_exists('plural')) '/(c)hild$/' => '\1hildren', // child '/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato '/(bu|campu)s$/' => '\1\2ses', // bus, campus - '/(alias|status|virus)/' => '\1es', // alias + '/(alias|status|virus)$/' => '\1es', // alias '/(octop)us$/' => '\1i', // octopus '/(ax|cris|test)is$/' => '\1es', // axis, crisis '/s$/' => 's', // no change (compatibility) @@ -141,63 +171,117 @@ if ( ! function_exists('plural')) // -------------------------------------------------------------------- -/** - * Camelize - * - * Takes multiple words separated by spaces or underscores and camelizes them - * - * @access public - * @param string - * @return str - */ if ( ! function_exists('camelize')) { + /** + * Camelize + * + * Takes multiple words separated by spaces or underscores and camelizes them + * + * @param string $str Input string + * @return string + */ function camelize($str) { - $str = 'x'.strtolower(trim($str)); - $str = ucwords(preg_replace('/[\s_]+/', ' ', $str)); - return substr(str_replace(' ', '', $str), 1); + return strtolower($str[0]).substr(str_replace(' ', '', ucwords(preg_replace('/[\s_]+/', ' ', $str))), 1); } } // -------------------------------------------------------------------- -/** - * Underscore - * - * Takes multiple words separated by spaces and underscores them - * - * @access public - * @param string - * @return str - */ if ( ! function_exists('underscore')) { + /** + * Underscore + * + * Takes multiple words separated by spaces and underscores them + * + * @param string $str Input string + * @return string + */ function underscore($str) { - return preg_replace('/[\s]+/', '_', strtolower(trim($str))); + return preg_replace('/[\s]+/', '_', trim(MB_ENABLED ? mb_strtolower($str) : strtolower($str))); } } // -------------------------------------------------------------------- -/** - * Humanize - * - * Takes multiple words separated by underscores and changes them to spaces - * - * @access public - * @param string - * @return str - */ if ( ! function_exists('humanize')) { - function humanize($str) + /** + * Humanize + * + * Takes multiple words separated by the separator and changes them to spaces + * + * @param string $str Input string + * @param string $separator Input separator + * @return string + */ + function humanize($str, $separator = '_') { - return ucwords(preg_replace('/[_]+/', ' ', strtolower(trim($str)))); + return ucwords(preg_replace('/['.preg_quote($separator).']+/', ' ', trim(MB_ENABLED ? mb_strtolower($str) : strtolower($str)))); } } +// -------------------------------------------------------------------- -/* End of file inflector_helper.php */ -/* Location: ./system/helpers/inflector_helper.php */ \ No newline at end of file +if ( ! function_exists('word_is_countable')) +{ + /** + * Checks if the given word has a plural version. + * + * @param string $word Word to check + * @return bool + */ + function word_is_countable($word) + { + return ! in_array( + strtolower($word), + array( + 'audio', + 'bison', + 'chassis', + 'compensation', + 'coreopsis', + 'data', + 'deer', + 'education', + 'emoji', + 'equipment', + 'fish', + 'furniture', + 'gold', + 'information', + 'knowledge', + 'love', + 'rain', + 'money', + 'moose', + 'nutrition', + 'offspring', + 'plankton', + 'pokemon', + 'police', + 'rice', + 'series', + 'sheep', + 'species', + 'swine', + 'traffic', + 'wheat' + ) + ); + } +} + +// -------------------------------------------------------------------- + +if ( ! function_exists('is_countable')) +{ + function is_countable($word) + { + trigger_error('is_countable() is a native PHP function since version 7.3.0; use word_is_countable() instead', E_USER_WARNING); + return word_is_countable($word); + } +} diff --git a/system/helpers/language_helper.php b/system/helpers/language_helper.php old mode 100755 new mode 100644 index e8a2885..2cefcc2 --- a/system/helpers/language_helper.php +++ b/system/helpers/language_helper.php @@ -1,19 +1,41 @@ -lang->line($line); + $line = get_instance()->lang->line($line); - if ($id != '') + if ($for !== '') { - $line = '"; + $line = ''; } return $line; } } - -// ------------------------------------------------------------------------ -/* End of file language_helper.php */ -/* Location: ./system/helpers/language_helper.php */ \ No newline at end of file diff --git a/system/helpers/number_helper.php b/system/helpers/number_helper.php old mode 100755 new mode 100644 index f18fee8..15a53ff --- a/system/helpers/number_helper.php +++ b/system/helpers/number_helper.php @@ -1,19 +1,41 @@ -security->xss_clean($str, $is_image); + return get_instance()->security->xss_clean($str, $is_image); } } // ------------------------------------------------------------------------ -/** - * Sanitize Filename - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('sanitize_filename')) { + /** + * Sanitize Filename + * + * @param string + * @return string + */ function sanitize_filename($filename) { - $CI =& get_instance(); - return $CI->security->sanitize_filename($filename); + return get_instance()->security->sanitize_filename($filename); } } // -------------------------------------------------------------------- -/** - * Hash encode a string - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('do_hash')) { + /** + * Hash encode a string + * + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 Use PHP's native hash() instead. + * @param string $str + * @param string $type = 'sha1' + * @return string + */ function do_hash($str, $type = 'sha1') { - if ($type == 'sha1') + if ( ! in_array(strtolower($type), hash_algos())) { - return sha1($str); - } - else - { - return md5($str); + $type = 'md5'; } + + return hash($type, $str); } } // ------------------------------------------------------------------------ -/** - * Strip Image Tags - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('strip_image_tags')) { + /** + * Strip Image Tags + * + * @param string + * @return string + */ function strip_image_tags($str) { - $str = preg_replace("##", "\\1", $str); - $str = preg_replace("##", "\\1", $str); - - return $str; + return get_instance()->security->strip_image_tags($str); } } // ------------------------------------------------------------------------ -/** - * Convert PHP tags to entities - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('encode_php_tags')) { + /** + * Convert PHP tags to entities + * + * @param string + * @return string + */ function encode_php_tags($str) { - return str_replace(array(''), array('<?php', '<?PHP', '<?', '?>'), $str); + return str_replace(array(''), array('<?', '?>'), $str); } } - - -/* End of file security_helper.php */ -/* Location: ./system/helpers/security_helper.php */ \ No newline at end of file diff --git a/system/helpers/smiley_helper.php b/system/helpers/smiley_helper.php old mode 100755 new mode 100644 index eb325c5..321e59c --- a/system/helpers/smiley_helper.php +++ b/system/helpers/smiley_helper.php @@ -1,19 +1,41 @@ -field_id pairs - * @param string field_id if alias name was passed in - * @return array - */ if ( ! function_exists('smiley_js')) { + /** + * Smiley Javascript + * + * Returns the javascript required for the smiley insertion. Optionally takes + * an array of aliases to loosely couple the smiley array to the view. + * + * @param mixed alias name or array of alias->field_id pairs + * @param string field_id if alias name was passed in + * @param bool + * @return array + */ function smiley_js($alias = '', $field_id = '', $inline = TRUE) { static $do_setup = TRUE; - $r = ''; - if ($alias != '' && ! is_array($alias)) + if ($alias !== '' && ! is_array($alias)) { $alias = array($alias => $field_id); } if ($do_setup === TRUE) { - $do_setup = FALSE; + $do_setup = FALSE; + $m = array(); - $m = array(); - - if (is_array($alias)) - { - foreach ($alias as $name => $id) - { - $m[] = '"'.$name.'" : "'.$id.'"'; - } - } - - $m = '{'.implode(',', $m).'}'; - - $r .= << $id) { - $r .= 'smiley_map["'.$name.'"] = "'.$id.'";'."\n"; + $m[] = '"'.$name.'" : "'.$id.'"'; } } + + $m = '{'.implode(',', $m).'}'; + + $r .= << $id) + { + $r .= 'smiley_map["'.$name.'"] = "'.$id."\";\n"; + } } - if ($inline) - { - return ''; - } - else - { - return $r; - } + return ($inline) + ? '' + : $r; } } // ------------------------------------------------------------------------ -/** - * Get Clickable Smileys - * - * Returns an array of image tag links that can be clicked to be inserted - * into a form field. - * - * @access public - * @param string the URL to the folder containing the smiley images - * @return array - */ if ( ! function_exists('get_clickable_smileys')) { - function get_clickable_smileys($image_url, $alias = '', $smileys = NULL) + /** + * Get Clickable Smileys + * + * Returns an array of image tag links that can be clicked to be inserted + * into a form field. + * + * @param string the URL to the folder containing the smiley images + * @param array + * @return array + */ + function get_clickable_smileys($image_url, $alias = '') { // For backward compatibility with js_insert_smiley - if (is_array($alias)) { $smileys = $alias; } - - if ( ! is_array($smileys)) + elseif (FALSE === ($smileys = _get_smiley_array())) { - if (FALSE === ($smileys = _get_smiley_array())) - { - return $smileys; - } + return FALSE; } // Add a trailing slash to the file path if needed @@ -157,7 +165,7 @@ if ( ! function_exists('get_clickable_smileys')) foreach ($smileys as $key => $val) { // Keep duplicates from being used, which can happen if the - // mapping array contains multiple identical replacements. For example: + // mapping array contains multiple identical replacements. For example: // :-) and :) might be replaced with the same image so both smileys // will be in the array. if (isset($used[$smileys[$key][0]])) @@ -165,8 +173,7 @@ if ( ! function_exists('get_clickable_smileys')) continue; } - $link[] = "
    \"".$smileys[$key][3]."\""; - + $link[] = ''.$smileys[$key][3].''; $used[$smileys[$key][0]] = TRUE; } @@ -176,39 +183,31 @@ if ( ! function_exists('get_clickable_smileys')) // ------------------------------------------------------------------------ -/** - * Parse Smileys - * - * Takes a string as input and swaps any contained smileys for the actual image - * - * @access public - * @param string the text to be parsed - * @param string the URL to the folder containing the smiley images - * @return string - */ if ( ! function_exists('parse_smileys')) { + /** + * Parse Smileys + * + * Takes a string as input and swaps any contained smileys for the actual image + * + * @param string the text to be parsed + * @param string the URL to the folder containing the smiley images + * @param array + * @return string + */ function parse_smileys($str = '', $image_url = '', $smileys = NULL) { - if ($image_url == '') + if ($image_url === '' OR ( ! is_array($smileys) && FALSE === ($smileys = _get_smiley_array()))) { return $str; } - if ( ! is_array($smileys)) - { - if (FALSE === ($smileys = _get_smiley_array())) - { - return $str; - } - } - // Add a trailing slash to the file path if needed - $image_url = preg_replace("/(.+?)\/*$/", "\\1/", $image_url); + $image_url = rtrim($image_url, '/').'/'; foreach ($smileys as $key => $val) { - $str = str_replace($key, "\"".$smileys[$key][3]."\"", $str); + $str = str_replace($key, ''.$smileys[$key][3].'', $str); } return $str; @@ -217,65 +216,40 @@ if ( ! function_exists('parse_smileys')) // ------------------------------------------------------------------------ -/** - * Get Smiley Array - * - * Fetches the config/smiley.php file - * - * @access private - * @return mixed - */ if ( ! function_exists('_get_smiley_array')) { + /** + * Get Smiley Array + * + * Fetches the config/smiley.php file + * + * @return mixed + */ function _get_smiley_array() { - if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/smileys.php')) + static $_smileys; + + if ( ! is_array($_smileys)) { - include(APPPATH.'config/'.ENVIRONMENT.'/smileys.php'); - } - elseif (file_exists(APPPATH.'config/smileys.php')) - { - include(APPPATH.'config/smileys.php'); - } - - if (isset($smileys) AND is_array($smileys)) - { - return $smileys; + if (file_exists(APPPATH.'config/smileys.php')) + { + include(APPPATH.'config/smileys.php'); + } + + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/smileys.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/smileys.php'); + } + + if (empty($smileys) OR ! is_array($smileys)) + { + $_smileys = array(); + return FALSE; + } + + $_smileys = $smileys; } - return FALSE; + return $_smileys; } } - -// ------------------------------------------------------------------------ - -/** - * JS Insert Smiley - * - * Generates the javascript function needed to insert smileys into a form field - * - * DEPRECATED as of version 1.7.2, use smiley_js instead - * - * @access public - * @param string form name - * @param string field name - * @return string - */ -if ( ! function_exists('js_insert_smiley')) -{ - function js_insert_smiley($form_name = '', $form_field = '') - { - return << - function insert_smiley(smiley) - { - document.{$form_name}.{$form_field}.value += " " + smiley; - } - -EOF; - } -} - - -/* End of file smiley_helper.php */ -/* Location: ./system/helpers/smiley_helper.php */ \ No newline at end of file diff --git a/system/helpers/string_helper.php b/system/helpers/string_helper.php old mode 100755 new mode 100644 index 9a2f2be..c7dd969 --- a/system/helpers/string_helper.php +++ b/system/helpers/string_helper.php @@ -1,19 +1,41 @@ - $val) - { - $str[$key] = strip_slashes($val); - } + return stripslashes($str); } - else + + foreach ($str as $key => $val) { - $str = stripslashes($str); + $str[$key] = strip_slashes($val); } return $str; @@ -83,17 +104,16 @@ if ( ! function_exists('strip_slashes')) // ------------------------------------------------------------------------ -/** - * Strip Quotes - * - * Removes single and double quotes from a string - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('strip_quotes')) { + /** + * Strip Quotes + * + * Removes single and double quotes from a string + * + * @param string + * @return string + */ function strip_quotes($str) { return str_replace(array('"', "'"), '', $str); @@ -102,17 +122,16 @@ if ( ! function_exists('strip_quotes')) // ------------------------------------------------------------------------ -/** - * Quotes to Entities - * - * Converts single and double quotes to entities - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('quotes_to_entities')) { + /** + * Quotes to Entities + * + * Converts single and double quotes to entities + * + * @param string + * @return string + */ function quotes_to_entities($str) { return str_replace(array("\'","\"","'",'"'), array("'",""","'","""), $str); @@ -121,164 +140,144 @@ if ( ! function_exists('quotes_to_entities')) // ------------------------------------------------------------------------ -/** - * Reduce Double Slashes - * - * Converts double slashes in a string to a single slash, - * except those found in http:// - * - * http://www.some-site.com//index.php - * - * becomes: - * - * http://www.some-site.com/index.php - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('reduce_double_slashes')) { + /** + * Reduce Double Slashes + * + * Converts double slashes in a string to a single slash, + * except those found in http:// + * + * http://www.some-site.com//index.php + * + * becomes: + * + * http://www.some-site.com/index.php + * + * @param string + * @return string + */ function reduce_double_slashes($str) { - return preg_replace("#(^|[^:])//+#", "\\1/", $str); + return preg_replace('#(^|[^:])//+#', '\\1/', $str); } } // ------------------------------------------------------------------------ -/** - * Reduce Multiples - * - * Reduces multiple instances of a particular character. Example: - * - * Fred, Bill,, Joe, Jimmy - * - * becomes: - * - * Fred, Bill, Joe, Jimmy - * - * @access public - * @param string - * @param string the character you wish to reduce - * @param bool TRUE/FALSE - whether to trim the character from the beginning/end - * @return string - */ if ( ! function_exists('reduce_multiples')) { + /** + * Reduce Multiples + * + * Reduces multiple instances of a particular character. Example: + * + * Fred, Bill,, Joe, Jimmy + * + * becomes: + * + * Fred, Bill, Joe, Jimmy + * + * @param string + * @param string the character you wish to reduce + * @param bool TRUE/FALSE - whether to trim the character from the beginning/end + * @return string + */ function reduce_multiples($str, $character = ',', $trim = FALSE) { $str = preg_replace('#'.preg_quote($character, '#').'{2,}#', $character, $str); - - if ($trim === TRUE) - { - $str = trim($str, $character); - } - - return $str; + return ($trim === TRUE) ? trim($str, $character) : $str; } } // ------------------------------------------------------------------------ -/** - * Create a Random String - * - * Useful for generating passwords or hashes. - * - * @access public - * @param string type of random string. basic, alpha, alunum, numeric, nozero, unique, md5, encrypt and sha1 - * @param integer number of characters - * @return string - */ if ( ! function_exists('random_string')) { + /** + * Create a "Random" String + * + * @param string type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1 + * @param int number of characters + * @return string + */ function random_string($type = 'alnum', $len = 8) { - switch($type) + switch ($type) { - case 'basic' : return mt_rand(); - break; - case 'alnum' : - case 'numeric' : - case 'nozero' : - case 'alpha' : - - switch ($type) - { - case 'alpha' : $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - break; - case 'alnum' : $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - break; - case 'numeric' : $pool = '0123456789'; - break; - case 'nozero' : $pool = '123456789'; - break; - } - - $str = ''; - for ($i=0; $i < $len; $i++) - { - $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); - } - return $str; - break; - case 'unique' : - case 'md5' : - - return md5(uniqid(mt_rand())); - break; - case 'encrypt' : - case 'sha1' : - - $CI =& get_instance(); - $CI->load->helper('security'); - - return do_hash(uniqid(mt_rand(), TRUE), 'sha1'); - break; + case 'basic': + return mt_rand(); + case 'alnum': + case 'numeric': + case 'nozero': + case 'alpha': + switch ($type) + { + case 'alpha': + $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + case 'alnum': + $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + case 'numeric': + $pool = '0123456789'; + break; + case 'nozero': + $pool = '123456789'; + break; + } + return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len); + case 'unique': // todo: remove in 3.1+ + case 'md5': + return md5(uniqid(mt_rand())); + case 'encrypt': // todo: remove in 3.1+ + case 'sha1': + return sha1(uniqid(mt_rand(), TRUE)); } } } // ------------------------------------------------------------------------ -/** - * Add's _1 to a string or increment the ending number to allow _2, _3, etc - * - * @param string $str required - * @param string $separator What should the duplicate number be appended with - * @param string $first Which number should be used for the first dupe increment - * @return string - */ -function increment_string($str, $separator = '_', $first = 1) +if ( ! function_exists('increment_string')) { - preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match); - - return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first; + /** + * Add's _1 to a string or increment the ending number to allow _2, _3, etc + * + * @param string required + * @param string What should the duplicate number be appended with + * @param string Which number should be used for the first dupe increment + * @return string + */ + function increment_string($str, $separator = '_', $first = 1) + { + preg_match('/(.+)'.preg_quote($separator, '/').'([0-9]+)$/', $str, $match); + return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first; + } } // ------------------------------------------------------------------------ -/** - * Alternator - * - * Allows strings to be alternated. See docs... - * - * @access public - * @param string (as many parameters as needed) - * @return string - */ if ( ! function_exists('alternator')) { + /** + * Alternator + * + * Allows strings to be alternated. See docs... + * + * @param string (as many parameters as needed) + * @return string + */ function alternator() { static $i; - if (func_num_args() == 0) + if (func_num_args() === 0) { $i = 0; return ''; } + $args = func_get_args(); return $args[($i++ % count($args))]; } @@ -286,22 +285,20 @@ if ( ! function_exists('alternator')) // ------------------------------------------------------------------------ -/** - * Repeater function - * - * @access public - * @param string - * @param integer number of repeats - * @return string - */ if ( ! function_exists('repeater')) { + /** + * Repeater function + * + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 This is just an alias for PHP's native str_repeat() + * + * @param string $data String to repeat + * @param int $num Number of repeats + * @return string + */ function repeater($data, $num = 1) { - return (($num > 0) ? str_repeat($data, $num) : ''); + return ($num > 0) ? str_repeat($data, $num) : ''; } } - - -/* End of file string_helper.php */ -/* Location: ./system/helpers/string_helper.php */ \ No newline at end of file diff --git a/system/helpers/text_helper.php b/system/helpers/text_helper.php old mode 100755 new mode 100644 index 8be50d0..e1c5e24 --- a/system/helpers/text_helper.php +++ b/system/helpers/text_helper.php @@ -1,19 +1,41 @@ -= $n) + if (mb_strlen($out) >= $n) { $out = trim($out); - return (strlen($out) == strlen($str)) ? $out : $out.$end_char; + return (mb_strlen($out) === mb_strlen($str)) ? $out : $out.$end_char; } } } @@ -104,24 +125,23 @@ if ( ! function_exists('character_limiter')) // ------------------------------------------------------------------------ -/** - * High ASCII to Entities - * - * Converts High ascii text and MS Word special characters to character entities - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('ascii_to_entities')) { + /** + * High ASCII to Entities + * + * Converts high ASCII text and MS Word special characters to character entities + * + * @param string $str + * @return string + */ function ascii_to_entities($str) { - $count = 1; - $out = ''; - $temp = array(); - - for ($i = 0, $s = strlen($str); $i < $s; $i++) + $out = ''; + $length = defined('MB_OVERLOAD_STRING') + ? mb_strlen($str, '8bit') - 1 + : strlen($str) - 1; + for ($i = 0, $count = 1, $temp = array(); $i <= $length; $i++) { $ordinal = ord($str[$i]); @@ -131,9 +151,9 @@ if ( ! function_exists('ascii_to_entities')) If the $temp array has a value but we have moved on, then it seems only fair that we output that entity and restart $temp before continuing. -Paul */ - if (count($temp) == 1) + if (count($temp) === 1) { - $out .= '&#'.array_shift($temp).';'; + $out .= '&#'.array_shift($temp).';'; $count = 1; } @@ -141,21 +161,28 @@ if ( ! function_exists('ascii_to_entities')) } else { - if (count($temp) == 0) + if (count($temp) === 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; - if (count($temp) == $count) + if (count($temp) === $count) { - $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); + $number = ($count === 3) + ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) + : (($temp[0] % 32) * 64) + ($temp[1] % 64); $out .= '&#'.$number.';'; $count = 1; $temp = array(); } + // If this is the last iteration, just output whatever we have + elseif ($i === $length) + { + $out .= '&#'.implode(';', $temp).';'; + } } } @@ -165,26 +192,24 @@ if ( ! function_exists('ascii_to_entities')) // ------------------------------------------------------------------------ -/** - * Entities to ASCII - * - * Converts character entities back to ASCII - * - * @access public - * @param string - * @param bool - * @return string - */ if ( ! function_exists('entities_to_ascii')) { + /** + * Entities to ASCII + * + * Converts character entities back to ASCII + * + * @param string + * @param bool + * @return string + */ function entities_to_ascii($str, $all = TRUE) { if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) { - for ($i = 0, $s = count($matches['0']); $i < $s; $i++) + for ($i = 0, $s = count($matches[0]); $i < $s; $i++) { - $digits = $matches['1'][$i]; - + $digits = $matches[1][$i]; $out = ''; if ($digits < 128) @@ -194,25 +219,26 @@ if ( ! function_exists('entities_to_ascii')) } elseif ($digits < 2048) { - $out .= chr(192 + (($digits - ($digits % 64)) / 64)); - $out .= chr(128 + ($digits % 64)); + $out .= chr(192 + (($digits - ($digits % 64)) / 64)).chr(128 + ($digits % 64)); } else { - $out .= chr(224 + (($digits - ($digits % 4096)) / 4096)); - $out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64)); - $out .= chr(128 + ($digits % 64)); + $out .= chr(224 + (($digits - ($digits % 4096)) / 4096)) + .chr(128 + ((($digits % 4096) - ($digits % 64)) / 64)) + .chr(128 + ($digits % 64)); } - $str = str_replace($matches['0'][$i], $out, $str); + $str = str_replace($matches[0][$i], $out, $str); } } if ($all) { - $str = str_replace(array("&", "<", ">", """, "'", "-"), - array("&","<",">","\"", "'", "-"), - $str); + return str_replace( + array('&', '<', '>', '"', ''', '-'), + array('&', '<', '>', '"', "'", '-'), + $str + ); } return $str; @@ -221,21 +247,20 @@ if ( ! function_exists('entities_to_ascii')) // ------------------------------------------------------------------------ -/** - * Word Censoring Function - * - * Supply a string and an array of disallowed words and any - * matched words will be converted to #### or to the replacement - * word you've submitted. - * - * @access public - * @param string the text string - * @param string the array of censoered words - * @param string the optional replacement value - * @return string - */ if ( ! function_exists('word_censor')) { + /** + * Word Censoring Function + * + * Supply a string and an array of disallowed words and any + * matched words will be converted to #### or to the replacement + * word you've submitted. + * + * @param string the text string + * @param string the array of censored words + * @param string the optional replacement value + * @return string + */ function word_censor($str, $censored, $replacement = '') { if ( ! is_array($censored)) @@ -253,13 +278,28 @@ if ( ! function_exists('word_censor')) foreach ($censored as $badword) { - if ($replacement != '') + $badword = str_replace('\*', '\w*?', preg_quote($badword, '/')); + if ($replacement !== '') { - $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str); + $str = preg_replace( + "/({$delim})(".$badword.")({$delim})/i", + "\\1{$replacement}\\3", + $str + ); } - else + elseif (preg_match_all("/{$delim}(".$badword."){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) { - $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str); + $matches = $matches[1]; + for ($i = count($matches) - 1; $i >= 0; $i--) + { + $length = strlen($matches[$i][0]); + $str = substr_replace( + $str, + str_repeat('#', $length), + $matches[$i][1], + $length + ); + } } } @@ -269,145 +309,146 @@ if ( ! function_exists('word_censor')) // ------------------------------------------------------------------------ -/** - * Code Highlighter - * - * Colorizes code strings - * - * @access public - * @param string the text string - * @return string - */ if ( ! function_exists('highlight_code')) { + /** + * Code Highlighter + * + * Colorizes code strings + * + * @param string the text string + * @return string + */ function highlight_code($str) { - // The highlight string function encodes and highlights - // brackets so we need them to start raw - $str = str_replace(array('<', '>'), array('<', '>'), $str); - - // Replace any existing PHP tags to temporary markers so they don't accidentally - // break the string out of PHP, and thus, thwart the highlighting. - - $str = str_replace(array('', '<%', '%>', '\\', ''), - array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str); + /* The highlight string function encodes and highlights + * brackets so we need them to start raw. + * + * Also replace any existing PHP tags to temporary markers + * so they don't accidentally break the string out of PHP, + * and thus, thwart the highlighting. + */ + $str = str_replace( + array('<', '>', '', '<%', '%>', '\\', ''), + array('<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), + $str + ); // The highlight_string function requires that the text be surrounded // by PHP tags, which we will remove later - $str = ''; // tags - // so we'll replace them with tags. - - if (abs(PHP_VERSION) < 5) - { - $str = str_replace(array(''), array(''), $str); - $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str); - } + $str = highlight_string('', TRUE); // Remove our artificially added PHP, and the syntax highlighting that came with it - $str = preg_replace('/<\?php( | )/i', '', $str); - $str = preg_replace('/(.*?)\?><\/span>\n<\/span>\n<\/code>/is', "$1\n\n", $str); - $str = preg_replace('/<\/span>/i', '', $str); + $str = preg_replace( + array( + '/<\?php( | )/i', + '/(.*?)\?><\/span>\n<\/span>\n<\/code>/is', + '/<\/span>/i' + ), + array( + '', + "$1\n\n", + '' + ), + $str + ); // Replace our markers back to PHP tags. - $str = str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), - array('<?', '?>', '<%', '%>', '\\', '</script>'), $str); - - return $str; + return str_replace( + array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), + array('<?', '?>', '<%', '%>', '\\', '</script>'), + $str + ); } } // ------------------------------------------------------------------------ -/** - * Phrase Highlighter - * - * Highlights a phrase within a text string - * - * @access public - * @param string the text string - * @param string the phrase you'd like to highlight - * @param string the openging tag to precede the phrase with - * @param string the closing tag to end the phrase with - * @return string - */ if ( ! function_exists('highlight_phrase')) { - function highlight_phrase($str, $phrase, $tag_open = '', $tag_close = '') + /** + * Phrase Highlighter + * + * Highlights a phrase within a text string + * + * @param string $str the text string + * @param string $phrase the phrase you'd like to highlight + * @param string $tag_open the openging tag to precede the phrase with + * @param string $tag_close the closing tag to end the phrase with + * @return string + */ + function highlight_phrase($str, $phrase, $tag_open = '', $tag_close = '') { - if ($str == '') - { - return ''; - } - - if ($phrase != '') - { - return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open."\\1".$tag_close, $str); - } - - return $str; + return ($str !== '' && $phrase !== '') + ? preg_replace('/('.preg_quote($phrase, '/').')/i'.(UTF8_ENABLED ? 'u' : ''), $tag_open.'\\1'.$tag_close, $str) + : $str; } } // ------------------------------------------------------------------------ -/** - * Convert Accented Foreign Characters to ASCII - * - * @access public - * @param string the text string - * @return string - */ if ( ! function_exists('convert_accented_characters')) { + /** + * Convert Accented Foreign Characters to ASCII + * + * @param string $str Input string + * @return string + */ function convert_accented_characters($str) { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php')) + static $array_from, $array_to; + + if ( ! is_array($array_from)) { - include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'); - } - elseif (is_file(APPPATH.'config/foreign_chars.php')) - { - include(APPPATH.'config/foreign_chars.php'); + if (file_exists(APPPATH.'config/foreign_chars.php')) + { + include(APPPATH.'config/foreign_chars.php'); + } + + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'); + } + + if (empty($foreign_characters) OR ! is_array($foreign_characters)) + { + $array_from = array(); + $array_to = array(); + + return $str; + } + + $array_from = array_keys($foreign_characters); + $array_to = array_values($foreign_characters); } - if ( ! isset($foreign_characters)) - { - return $str; - } - - return preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str); + return preg_replace($array_from, $array_to, $str); } } // ------------------------------------------------------------------------ -/** - * Word Wrap - * - * Wraps text at the specified character. Maintains the integrity of words. - * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor - * will URLs. - * - * @access public - * @param string the text string - * @param integer the number of characters to wrap at - * @return string - */ if ( ! function_exists('word_wrap')) { - function word_wrap($str, $charlim = '76') + /** + * Word Wrap + * + * Wraps text at the specified character. Maintains the integrity of words. + * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor + * will URLs. + * + * @param string $str the text string + * @param int $charlim = 76 the number of characters to wrap at + * @return string + */ + function word_wrap($str, $charlim = 76) { - // Se the character limit - if ( ! is_numeric($charlim)) - $charlim = 76; + // Set the character limit + is_numeric($charlim) OR $charlim = 76; // Reduce multiple spaces - $str = preg_replace("| +|", " ", $str); + $str = preg_replace('| +|', ' ', $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) @@ -418,58 +459,56 @@ if ( ! function_exists('word_wrap')) // If the current word is surrounded by {unwrap} tags we'll // strip the entire chunk and replace it with a marker. $unwrap = array(); - if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches)) + if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches)) { - for ($i = 0; $i < count($matches['0']); $i++) + for ($i = 0, $c = count($matches[0]); $i < $c; $i++) { - $unwrap[] = $matches['1'][$i]; - $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str); + $unwrap[] = $matches[1][$i]; + $str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str); } } // Use PHP's native function to do the initial wordwrap. // We set the cut flag to FALSE so that any individual words that are - // too long get left alone. In the next step we'll deal with them. + // too long get left alone. In the next step we'll deal with them. $str = wordwrap($str, $charlim, "\n", FALSE); // Split the string into individual lines of text and cycle through them - $output = ""; + $output = ''; foreach (explode("\n", $str) as $line) { // Is the line within the allowed character count? // If so we'll join it to the output and continue - if (strlen($line) <= $charlim) + if (mb_strlen($line) <= $charlim) { $output .= $line."\n"; continue; } $temp = ''; - while ((strlen($line)) > $charlim) + while (mb_strlen($line) > $charlim) { // If the over-length word is a URL we won't wrap it - if (preg_match("!\[url.+\]|://|wwww.!", $line)) + if (preg_match('!\[url.+\]|://|www\.!', $line)) { break; } // Trim the word down - $temp .= substr($line, 0, $charlim-1); - $line = substr($line, $charlim-1); + $temp .= mb_substr($line, 0, $charlim - 1); + $line = mb_substr($line, $charlim - 1); } // If $temp contains data it means we had to split up an over-length // word into smaller chunks so we'll add it back to our current line - if ($temp != '') + if ($temp !== '') { - $output .= $temp."\n".$line; + $output .= $temp."\n".$line."\n"; } else { - $output .= $line; + $output .= $line."\n"; } - - $output .= "\n"; } // Put our markers back @@ -477,59 +516,52 @@ if ( ! function_exists('word_wrap')) { foreach ($unwrap as $key => $val) { - $output = str_replace("{{unwrapped".$key."}}", $val, $output); + $output = str_replace('{{unwrapped'.$key.'}}', $val, $output); } } - // Remove the unwrap tags - $output = str_replace(array('{unwrap}', '{/unwrap}'), '', $output); - return $output; } } // ------------------------------------------------------------------------ -/** - * Ellipsize String - * - * This function will strip tags from a string, split it at its max_length and ellipsize - * - * @param string string to ellipsize - * @param integer max length of string - * @param mixed int (1|0) or float, .5, .2, etc for position to split - * @param string ellipsis ; Default '...' - * @return string ellipsized string - */ if ( ! function_exists('ellipsize')) { + /** + * Ellipsize String + * + * This function will strip tags from a string, split it at its max_length and ellipsize + * + * @param string string to ellipsize + * @param int max length of string + * @param mixed int (1|0) or float, .5, .2, etc for position to split + * @param string ellipsis ; Default '...' + * @return string ellipsized string + */ function ellipsize($str, $max_length, $position = 1, $ellipsis = '…') { // Strip tags $str = trim(strip_tags($str)); // Is the string long enough to ellipsize? - if (strlen($str) <= $max_length) + if (mb_strlen($str) <= $max_length) { return $str; } - $beg = substr($str, 0, floor($max_length * $position)); - + $beg = mb_substr($str, 0, floor($max_length * $position)); $position = ($position > 1) ? 1 : $position; if ($position === 1) { - $end = substr($str, 0, -($max_length - strlen($beg))); + $end = mb_substr($str, 0, -($max_length - mb_strlen($beg))); } else { - $end = substr($str, -($max_length - strlen($beg))); + $end = mb_substr($str, -($max_length - mb_strlen($beg))); } return $beg.$ellipsis.$end; } } - -/* End of file text_helper.php */ -/* Location: ./system/helpers/text_helper.php */ \ No newline at end of file diff --git a/system/helpers/typography_helper.php b/system/helpers/typography_helper.php old mode 100755 new mode 100644 index 21364fb..d308a57 --- a/system/helpers/typography_helper.php +++ b/system/helpers/typography_helper.php @@ -1,19 +1,41 @@ -load->library('typography'); - return $CI->typography->nl2br_except_pre($str); } } // ------------------------------------------------------------------------ -/** - * Auto Typography Wrapper Function - * - * - * @access public - * @param string - * @param bool whether to allow javascript event handlers - * @param bool whether to reduce multiple instances of double newlines to two - * @return string - */ if ( ! function_exists('auto_typography')) { - function auto_typography($str, $strip_js_event_handlers = TRUE, $reduce_linebreaks = FALSE) + /** + * Auto Typography Wrapper Function + * + * @param string $str + * @param bool $reduce_linebreaks = FALSE whether to reduce multiple instances of double newlines to two + * @return string + */ + function auto_typography($str, $reduce_linebreaks = FALSE) { $CI =& get_instance(); $CI->load->library('typography'); - return $CI->typography->auto_typography($str, $strip_js_event_handlers, $reduce_linebreaks); + return $CI->typography->auto_typography($str, $reduce_linebreaks); } } - // -------------------------------------------------------------------- -/** - * HTML Entities Decode - * - * This function is a replacement for html_entity_decode() - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('entity_decode')) { - function entity_decode($str, $charset='UTF-8') + /** + * HTML Entities Decode + * + * This function is a replacement for html_entity_decode() + * + * @param string + * @param string + * @return string + */ + function entity_decode($str, $charset = NULL) { - global $SEC; - return $SEC->entity_decode($str, $charset); + return get_instance()->security->entity_decode($str, $charset); } } - -/* End of file typography_helper.php */ -/* Location: ./system/helpers/typography_helper.php */ \ No newline at end of file diff --git a/system/helpers/url_helper.php b/system/helpers/url_helper.php old mode 100755 new mode 100644 index 0e410d8..bebfd25 --- a/system/helpers/url_helper.php +++ b/system/helpers/url_helper.php @@ -1,19 +1,41 @@ -config->site_url($uri); + return get_instance()->config->site_url($uri, $protocol); } } // ------------------------------------------------------------------------ -/** - * Base URL - * - * Create a local URL based on your basepath. - * Segments can be passed in as a string or an array, same as site_url - * or a URL to a file can be passed in, e.g. to an image file. - * - * @access public - * @param string - * @return string - */ if ( ! function_exists('base_url')) { - function base_url($uri = '') + /** + * Base URL + * + * Create a local URL based on your basepath. + * Segments can be passed in as a string or an array, same as site_url + * or a URL to a file can be passed in, e.g. to an image file. + * + * @param string $uri + * @param string $protocol + * @return string + */ + function base_url($uri = '', $protocol = NULL) { - $CI =& get_instance(); - return $CI->config->base_url($uri); + return get_instance()->config->base_url($uri, $protocol); } } // ------------------------------------------------------------------------ -/** - * Current URL - * - * Returns the full URL (including segments) of the page where this - * function is placed - * - * @access public - * @return string - */ if ( ! function_exists('current_url')) { + /** + * Current URL + * + * Returns the full URL (including segments) of the page where this + * function is placed + * + * @return string + */ function current_url() { $CI =& get_instance(); @@ -89,78 +108,69 @@ if ( ! function_exists('current_url')) } // ------------------------------------------------------------------------ -/** - * URL String - * - * Returns the URI segments. - * - * @access public - * @return string - */ + if ( ! function_exists('uri_string')) { + /** + * URL String + * + * Returns the URI segments. + * + * @return string + */ function uri_string() { - $CI =& get_instance(); - return $CI->uri->uri_string(); + return get_instance()->uri->uri_string(); } } // ------------------------------------------------------------------------ -/** - * Index page - * - * Returns the "index_page" from your config file - * - * @access public - * @return string - */ if ( ! function_exists('index_page')) { + /** + * Index page + * + * Returns the "index_page" from your config file + * + * @return string + */ function index_page() { - $CI =& get_instance(); - return $CI->config->item('index_page'); + return get_instance()->config->item('index_page'); } } // ------------------------------------------------------------------------ -/** - * Anchor Link - * - * Creates an anchor based on the local URL. - * - * @access public - * @param string the URL - * @param string the link title - * @param mixed any attributes - * @return string - */ if ( ! function_exists('anchor')) { + /** + * Anchor Link + * + * Creates an anchor based on the local URL. + * + * @param string the URL + * @param string the link title + * @param mixed any attributes + * @return string + */ function anchor($uri = '', $title = '', $attributes = '') { $title = (string) $title; - if ( ! is_array($uri)) - { - $site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri; - } - else - { - $site_url = site_url($uri); - } + $site_url = is_array($uri) + ? site_url($uri) + : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri)); - if ($title == '') + if ($title === '') { $title = $site_url; } - if ($attributes != '') + if ($attributes !== '') { - $attributes = _parse_attributes($attributes); + $attributes = _stringify_attributes($attributes); } return ''.$title.''; @@ -169,139 +179,141 @@ if ( ! function_exists('anchor')) // ------------------------------------------------------------------------ -/** - * Anchor Link - Pop-up version - * - * Creates an anchor based on the local URL. The link - * opens a new window based on the attributes specified. - * - * @access public - * @param string the URL - * @param string the link title - * @param mixed any attributes - * @return string - */ if ( ! function_exists('anchor_popup')) { + /** + * Anchor Link - Pop-up version + * + * Creates an anchor based on the local URL. The link + * opens a new window based on the attributes specified. + * + * @param string the URL + * @param string the link title + * @param mixed any attributes + * @return string + */ function anchor_popup($uri = '', $title = '', $attributes = FALSE) { $title = (string) $title; + $site_url = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri); - $site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri; - - if ($title == '') + if ($title === '') { $title = $site_url; } if ($attributes === FALSE) { - return "".$title.""; + return '".$title.''; } if ( ! is_array($attributes)) { - $attributes = array(); + $attributes = array($attributes); + + // Ref: http://www.w3schools.com/jsref/met_win_open.asp + $window_name = '_blank'; + } + elseif ( ! empty($attributes['window_name'])) + { + $window_name = $attributes['window_name']; + unset($attributes['window_name']); + } + else + { + $window_name = '_blank'; } - foreach (array('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0', ) as $key => $val) + foreach (array('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0') as $key => $val) { - $atts[$key] = ( ! isset($attributes[$key])) ? $val : $attributes[$key]; + $atts[$key] = isset($attributes[$key]) ? $attributes[$key] : $val; unset($attributes[$key]); } - if ($attributes != '') - { - $attributes = _parse_attributes($attributes); - } + $attributes = _stringify_attributes($attributes); - return "".$title.""; + return ''.$title.''; } } // ------------------------------------------------------------------------ -/** - * Mailto Link - * - * @access public - * @param string the email address - * @param string the link title - * @param mixed any attributes - * @return string - */ if ( ! function_exists('mailto')) { + /** + * Mailto Link + * + * @param string the email address + * @param string the link title + * @param mixed any attributes + * @return string + */ function mailto($email, $title = '', $attributes = '') { $title = (string) $title; - if ($title == "") + if ($title === '') { $title = $email; } - $attributes = _parse_attributes($attributes); - - return ''.$title.''; + return ''.$title.''; } } // ------------------------------------------------------------------------ -/** - * Encoded Mailto Link - * - * Create a spam-protected mailto link written in Javascript - * - * @access public - * @param string the email address - * @param string the link title - * @param mixed any attributes - * @return string - */ if ( ! function_exists('safe_mailto')) { + /** + * Encoded Mailto Link + * + * Create a spam-protected mailto link written in Javascript + * + * @param string the email address + * @param string the link title + * @param mixed any attributes + * @return string + */ function safe_mailto($email, $title = '', $attributes = '') { $title = (string) $title; - if ($title == "") + if ($title === '') { $title = $email; } - for ($i = 0; $i < 16; $i++) - { - $x[] = substr(' $val) { - $x[] = ' '.$key.'="'; - for ($i = 0; $i < strlen($val); $i++) + $x[] = ' '.$key.'="'; + for ($i = 0, $l = strlen($val); $i < $l; $i++) { - $x[] = "|".ord(substr($val, $i, 1)); + $x[] = '|'.ord($val[$i]); } $x[] = '"'; } } else { - for ($i = 0; $i < strlen($attributes); $i++) + for ($i = 0, $l = strlen($attributes); $i < $l; $i++) { - $x[] = substr($attributes, $i, 1); + $x[] = $attributes[$i]; } } } @@ -309,26 +321,28 @@ if ( ! function_exists('safe_mailto')) $x[] = '>'; $temp = array(); - for ($i = 0; $i < strlen($title); $i++) + for ($i = 0, $l = strlen($title); $i < $l; $i++) { $ordinal = ord($title[$i]); if ($ordinal < 128) { - $x[] = "|".$ordinal; + $x[] = '|'.$ordinal; } else { - if (count($temp) == 0) + if (count($temp) === 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; - if (count($temp) == $count) + if (count($temp) === $count) { - $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); - $x[] = "|".$number; + $number = ($count === 3) + ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) + : (($temp[0] % 32) * 64) + ($temp[1] % 64); + $x[] = '|'.$number; $count = 1; $temp = array(); } @@ -338,89 +352,75 @@ if ( ! function_exists('safe_mailto')) $x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>'; $x = array_reverse($x); - ob_start(); - ?>= 0; i=i-1) {\n" + ."\t\tif (l[i].substring(0, 1) === '|') document.write(\"&#\"+unescape(l[i].substring(1))+\";\");\n" + ."\t\telse document.write(unescape(l[i]));\n" + ."\t}\n" + ."\t//]]>\n" + .''; + + return $output; } } // ------------------------------------------------------------------------ -/** - * Auto-linker - * - * Automatically links URL and Email addresses. - * Note: There's a bit of extra code here to deal with - * URLs or emails that end in a period. We'll strip these - * off and add them after the link. - * - * @access public - * @param string the string - * @param string the type: email, url, or both - * @param bool whether to create pop-up links - * @return string - */ if ( ! function_exists('auto_link')) { + /** + * Auto-linker + * + * Automatically links URL and Email addresses. + * Note: There's a bit of extra code here to deal with + * URLs or emails that end in a period. We'll strip these + * off and add them after the link. + * + * @param string the string + * @param string the type: email, url, or both + * @param bool whether to create pop-up links + * @return string + */ function auto_link($str, $type = 'both', $popup = FALSE) { - if ($type != 'email') + // Find and replace any URLs. + if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[a-z0-9]+(-+[a-z0-9]+)*(\.[a-z0-9]+(-+[a-z0-9]+)*)+(/([^\s()<>;]+\w)?/?)?#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { - if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)) + // Set our target HTML if using popup links. + $target = ($popup) ? ' target="_blank" rel="noopener"' : ''; + + // We process the links in reverse order (last -> first) so that + // the returned string offsets from preg_match_all() are not + // moved as we add more HTML. + foreach (array_reverse($matches) as $match) { - $pop = ($popup == TRUE) ? " target=\"_blank\" " : ""; - - for ($i = 0; $i < count($matches['0']); $i++) - { - $period = ''; - if (preg_match("|\.$|", $matches['6'][$i])) - { - $period = '.'; - $matches['6'][$i] = substr($matches['6'][$i], 0, -1); - } - - $str = str_replace($matches['0'][$i], - $matches['1'][$i].'http'. - $matches['4'][$i].'://'. - $matches['5'][$i]. - $matches['6'][$i].''. - $period, $str); - } + // $match[0] is the matched string/link + // $match[1] is either a protocol prefix or 'www.' + // + // With PREG_OFFSET_CAPTURE, both of the above is an array, + // where the actual value is held in [0] and its offset at the [1] index. + $a = ''.$match[0][0].''; + $str = substr_replace($str, $a, $match[0][1], strlen($match[0][0])); } } - if ($type != 'url') + // Find and replace any emails. + if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) { - if (preg_match_all("/([a-zA-Z0-9_\.\-\+]+)@([a-zA-Z0-9\-]+)\.([a-zA-Z0-9\-\.]*)/i", $str, $matches)) + foreach (array_reverse($matches[0]) as $match) { - for ($i = 0; $i < count($matches['0']); $i++) + if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== FALSE) { - $period = ''; - if (preg_match("|\.$|", $matches['3'][$i])) - { - $period = '.'; - $matches['3'][$i] = substr($matches['3'][$i], 0, -1); - } - - $str = str_replace($matches['0'][$i], safe_mailto($matches['1'][$i].'@'.$matches['2'][$i].'.'.$matches['3'][$i]).$period, $str); + $str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0])); } } } @@ -431,20 +431,19 @@ if ( ! function_exists('auto_link')) // ------------------------------------------------------------------------ -/** - * Prep URL - * - * Simply adds the http:// part if no scheme is included - * - * @access public - * @param string the URL - * @return string - */ if ( ! function_exists('prep_url')) { + /** + * Prep URL + * + * Simply adds the http:// part if no scheme is included + * + * @param string the URL + * @return string + */ function prep_url($str = '') { - if ($str == 'http://' OR $str == '') + if ($str === 'http://' OR $str === '') { return ''; } @@ -453,7 +452,7 @@ if ( ! function_exists('prep_url')) if ( ! $url OR ! isset($url['scheme'])) { - $str = 'http://'.$str; + return 'http://'.$str; } return $str; @@ -462,45 +461,46 @@ if ( ! function_exists('prep_url')) // ------------------------------------------------------------------------ -/** - * Create URL Title - * - * Takes a "title" string as input and creates a - * human-friendly URL string with a "separator" string - * as the word separator. - * - * @access public - * @param string the string - * @param string the separator - * @return string - */ if ( ! function_exists('url_title')) { + /** + * Create URL Title + * + * Takes a "title" string as input and creates a + * human-friendly URL string with a "separator" string + * as the word separator. + * + * @todo Remove old 'dash' and 'underscore' usage in 3.1+. + * @param string $str Input string + * @param string $separator Word separator + * (usually '-' or '_') + * @param bool $lowercase Whether to transform the output string to lowercase + * @return string + */ function url_title($str, $separator = '-', $lowercase = FALSE) { - if ($separator == 'dash') + if ($separator === 'dash') { - $separator = '-'; + $separator = '-'; } - else if ($separator == 'underscore') + elseif ($separator === 'underscore') { - $separator = '_'; + $separator = '_'; } - - $q_separator = preg_quote($separator); + + $q_separator = preg_quote($separator, '#'); $trans = array( - '&.+?;' => '', - '[^a-z0-9 _-]' => '', - '\s+' => $separator, - '('.$q_separator.')+' => $separator + '&.+?;' => '', + '[^\w\d _-]' => '', + '\s+' => $separator, + '('.$q_separator.')+' => $separator ); $str = strip_tags($str); - foreach ($trans as $key => $val) { - $str = preg_replace("#".$key."#i", $val, $str); + $str = preg_replace('#'.$key.'#i'.(UTF8_ENABLED ? 'u' : ''), $val, $str); } if ($lowercase === TRUE) @@ -508,87 +508,62 @@ if ( ! function_exists('url_title')) $str = strtolower($str); } - return trim($str, $separator); + return trim(trim($str, $separator)); } } // ------------------------------------------------------------------------ -/** - * Header Redirect - * - * Header redirect in two flavors - * For very fine grained control over headers, you could use the Output - * Library's set_header() function. - * - * @access public - * @param string the URL - * @param string the method: location or redirect - * @return string - */ if ( ! function_exists('redirect')) { - function redirect($uri = '', $method = 'location', $http_response_code = 302) + /** + * Header Redirect + * + * Header redirect in two flavors + * For very fine grained control over headers, you could use the Output + * Library's set_header() function. + * + * @param string $uri URL + * @param string $method Redirect method + * 'auto', 'location' or 'refresh' + * @param int $code HTTP Response status code + * @return void + */ + function redirect($uri = '', $method = 'auto', $code = NULL) { - if ( ! preg_match('#^https?://#i', $uri)) + if ( ! preg_match('#^(\w+:)?//#i', $uri)) { $uri = site_url($uri); } - switch($method) + // IIS environment likely? Use 'refresh' for better compatibility + if ($method === 'auto' && isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== FALSE) { - case 'refresh' : header("Refresh:0;url=".$uri); + $method = 'refresh'; + } + elseif ($method !== 'refresh' && (empty($code) OR ! is_numeric($code))) + { + if (isset($_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.1') + { + $code = ($_SERVER['REQUEST_METHOD'] !== 'GET') + ? 303 // reference: http://en.wikipedia.org/wiki/Post/Redirect/Get + : 307; + } + else + { + $code = 302; + } + } + + switch ($method) + { + case 'refresh': + header('Refresh:0;url='.$uri); break; - default : header("Location: ".$uri, TRUE, $http_response_code); + default: + header('Location: '.$uri, TRUE, $code); break; } exit; } } - -// ------------------------------------------------------------------------ - -/** - * Parse out the attributes - * - * Some of the functions use this - * - * @access private - * @param array - * @param bool - * @return string - */ -if ( ! function_exists('_parse_attributes')) -{ - function _parse_attributes($attributes, $javascript = FALSE) - { - if (is_string($attributes)) - { - return ($attributes != '') ? ' '.$attributes : ''; - } - - $att = ''; - foreach ($attributes as $key => $val) - { - if ($javascript == TRUE) - { - $att .= $key . '=' . $val . ','; - } - else - { - $att .= ' ' . $key . '="' . $val . '"'; - } - } - - if ($javascript == TRUE AND $att != '') - { - $att = substr($att, 0, -1); - } - - return $att; - } -} - - -/* End of file url_helper.php */ -/* Location: ./system/helpers/url_helper.php */ \ No newline at end of file diff --git a/system/helpers/xml_helper.php b/system/helpers/xml_helper.php old mode 100755 new mode 100644 index 6c36e1c..2639956 --- a/system/helpers/xml_helper.php +++ b/system/helpers/xml_helper.php @@ -1,19 +1,41 @@ -","\"", "'", "-"), - array("&", "<", ">", """, "'", "-"), - $str); + $str = str_replace( + array('&', '<', '>', '"', "'", '-'), + array('&', '<', '>', '"', ''', '-'), + $str + ); // Decode the temp markers back to entities - $str = preg_replace("/$temp(\d+);/","&#\\1;",$str); + $str = preg_replace('/'.$temp.'(\d+);/', '&#\\1;', $str); if ($protect_all === TRUE) { - $str = preg_replace("/$temp(\w+);/","&\\1;", $str); + return preg_replace('/'.$temp.'(\w+);/', '&\\1;', $str); } return $str; } } - -// ------------------------------------------------------------------------ - -/* End of file xml_helper.php */ -/* Location: ./system/helpers/xml_helper.php */ \ No newline at end of file diff --git a/system/index.html b/system/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/index.html +++ b/system/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file + diff --git a/system/language/english/calendar_lang.php b/system/language/english/calendar_lang.php old mode 100755 new mode 100644 index 3e63123..ce83814 --- a/system/language/english/calendar_lang.php +++ b/system/language/english/calendar_lang.php @@ -1,51 +1,84 @@ 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file + diff --git a/system/language/english/migration_lang.php b/system/language/english/migration_lang.php old mode 100755 new mode 100644 index f17530f..967d59c --- a/system/language/english/migration_lang.php +++ b/system/language/english/migration_lang.php @@ -1,13 +1,47 @@ 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file + diff --git a/system/libraries/Cache/Cache.php b/system/libraries/Cache/Cache.php old mode 100755 new mode 100644 index 673e63d..450d57b --- a/system/libraries/Cache/Cache.php +++ b/system/libraries/Cache/Cache.php @@ -1,19 +1,41 @@ -_adapter = $config['adapter']; + isset($config['backup']) && $this->_backup_driver = $config['backup']; + isset($config['key_prefix']) && $this->key_prefix = $config['key_prefix']; + + // If the specified adapter isn't available, check the backup. + if ( ! $this->is_supported($this->_adapter)) { - $this->_initialize($config); + if ( ! $this->is_supported($this->_backup_driver)) + { + // Backup isn't supported either. Default to 'Dummy' driver. + log_message('error', 'Cache adapter "'.$this->_adapter.'" and backup "'.$this->_backup_driver.'" are both unavailable. Cache is now using "Dummy" adapter.'); + $this->_adapter = 'dummy'; + } + else + { + // Backup is supported. Set it to primary. + log_message('debug', 'Cache adapter "'.$this->_adapter.'" is unavailable. Falling back to "'.$this->_backup_driver.'" backup adapter.'); + $this->_adapter = $this->_backup_driver; + } } } @@ -54,15 +127,15 @@ class CI_Cache extends CI_Driver_Library { /** * Get * - * Look for a value in the cache. If it exists, return the data + * Look for a value in the cache. If it exists, return the data * if not, return FALSE * - * @param string - * @return mixed value that is stored/FALSE on failure + * @param string $id + * @return mixed value matching $id or FALSE on failure */ public function get($id) { - return $this->{$this->_adapter}->get($id); + return $this->{$this->_adapter}->get($this->key_prefix.$id); } // ------------------------------------------------------------------------ @@ -70,15 +143,15 @@ class CI_Cache extends CI_Driver_Library { /** * Cache Save * - * @param string Unique Key - * @param mixed Data to store - * @param int Length of time (in seconds) to cache the data - * - * @return boolean true on success/false on failure + * @param string $id Cache ID + * @param mixed $data Data to store + * @param int $ttl Cache TTL (in seconds) + * @param bool $raw Whether to store the raw value + * @return bool TRUE on success, FALSE on failure */ - public function save($id, $data, $ttl = 60) + public function save($id, $data, $ttl = 60, $raw = FALSE) { - return $this->{$this->_adapter}->save($id, $data, $ttl); + return $this->{$this->_adapter}->save($this->key_prefix.$id, $data, $ttl, $raw); } // ------------------------------------------------------------------------ @@ -86,12 +159,40 @@ class CI_Cache extends CI_Driver_Library { /** * Delete from Cache * - * @param mixed unique identifier of the item in the cache - * @return boolean true on success/false on failure + * @param string $id Cache ID + * @return bool TRUE on success, FALSE on failure */ public function delete($id) { - return $this->{$this->_adapter}->delete($id); + return $this->{$this->_adapter}->delete($this->key_prefix.$id); + } + + // ------------------------------------------------------------------------ + + /** + * Increment a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to add + * @return mixed New value on success or FALSE on failure + */ + public function increment($id, $offset = 1) + { + return $this->{$this->_adapter}->increment($this->key_prefix.$id, $offset); + } + + // ------------------------------------------------------------------------ + + /** + * Decrement a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to reduce by + * @return mixed New value on success or FALSE on failure + */ + public function decrement($id, $offset = 1) + { + return $this->{$this->_adapter}->decrement($this->key_prefix.$id, $offset); } // ------------------------------------------------------------------------ @@ -99,7 +200,7 @@ class CI_Cache extends CI_Driver_Library { /** * Clean the cache * - * @return boolean false on failure/true on success + * @return bool TRUE on success, FALSE on failure */ public function clean() { @@ -111,8 +212,8 @@ class CI_Cache extends CI_Driver_Library { /** * Cache Info * - * @param string user/filehits - * @return mixed array on success, false on failure + * @param string $type = 'user' user/filehits + * @return mixed array containing cache info on success OR FALSE on failure */ public function cache_info($type = 'user') { @@ -124,48 +225,12 @@ class CI_Cache extends CI_Driver_Library { /** * Get Cache Metadata * - * @param mixed key to get cache metadata on - * @return mixed return value from child method + * @param string $id key to get cache metadata on + * @return mixed cache item metadata */ public function get_metadata($id) { - return $this->{$this->_adapter}->get_metadata($id); - } - - // ------------------------------------------------------------------------ - - /** - * Initialize - * - * Initialize class properties based on the configuration array. - * - * @param array - * @return void - */ - private function _initialize($config) - { - $default_config = array( - 'adapter', - 'memcached' - ); - - foreach ($default_config as $key) - { - if (isset($config[$key])) - { - $param = '_'.$key; - - $this->{$param} = $config[$key]; - } - } - - if (isset($config['backup'])) - { - if (in_array('cache_'.$config['backup'], $this->valid_drivers)) - { - $this->_backup_driver = $config['backup']; - } - } + return $this->{$this->_adapter}->get_metadata($this->key_prefix.$id); } // ------------------------------------------------------------------------ @@ -173,42 +238,18 @@ class CI_Cache extends CI_Driver_Library { /** * Is the requested driver supported in this environment? * - * @param string The driver to test. - * @return array + * @param string $driver The driver to test + * @return array */ public function is_supported($driver) { - static $support = array(); + static $support; - if ( ! isset($support[$driver])) + if ( ! isset($support, $support[$driver])) { $support[$driver] = $this->{$driver}->is_supported(); } return $support[$driver]; } - - // ------------------------------------------------------------------------ - - /** - * __get() - * - * @param child - * @return object - */ - public function __get($child) - { - $obj = parent::__get($child); - - if ( ! $this->is_supported($child)) - { - $this->_adapter = $this->_backup_driver; - } - - return $obj; - } - } - -/* End of file Cache.php */ -/* Location: ./system/libraries/Cache/Cache.php */ \ No newline at end of file diff --git a/system/libraries/Cache/drivers/Cache_apc.php b/system/libraries/Cache/drivers/Cache_apc.php old mode 100755 new mode 100644 index fdc7401..8da8854 --- a/system/libraries/Cache/drivers/Cache_apc.php +++ b/system/libraries/Cache/drivers/Cache_apc.php @@ -1,19 +1,41 @@ -is_supported()) + { + log_message('error', 'Cache: Failed to initialize APC; extension not loaded/enabled?'); + } + } + + // ------------------------------------------------------------------------ + /** * Get * - * Look for a value in the cache. If it exists, return the data + * Look for a value in the cache. If it exists, return the data * if not, return FALSE * - * @param string - * @return mixed value that is stored/FALSE on failure + * @param string + * @return mixed value that is stored/FALSE on failure */ public function get($id) { - $data = apc_fetch($id); + $success = FALSE; + $data = apc_fetch($id, $success); - return (is_array($data)) ? $data[0] : FALSE; + return ($success === TRUE) ? $data : FALSE; } // ------------------------------------------------------------------------ @@ -48,15 +88,15 @@ class CI_Cache_apc extends CI_Driver { /** * Cache Save * - * @param string Unique Key - * @param mixed Data to store - * @param int Length of time (in seconds) to cache the data - * - * @return boolean true on success/false on failure + * @param string $id Cache ID + * @param mixed $data Data to store + * @param int $ttl Length of time (in seconds) to cache the data + * @param bool $raw Whether to store the raw value (unused) + * @return bool TRUE on success, FALSE on failure */ - public function save($id, $data, $ttl = 60) + public function save($id, $data, $ttl = 60, $raw = FALSE) { - return apc_store($id, array($data, time(), $ttl), $ttl); + return apc_store($id, $data, (int) $ttl); } // ------------------------------------------------------------------------ @@ -64,8 +104,8 @@ class CI_Cache_apc extends CI_Driver { /** * Delete from Cache * - * @param mixed unique identifier of the item in the cache - * @param boolean true on success/false on failure + * @param mixed unique identifier of the item in the cache + * @return bool true on success/false on failure */ public function delete($id) { @@ -74,10 +114,38 @@ class CI_Cache_apc extends CI_Driver { // ------------------------------------------------------------------------ + /** + * Increment a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to add + * @return mixed New value on success or FALSE on failure + */ + public function increment($id, $offset = 1) + { + return apc_inc($id, $offset); + } + + // ------------------------------------------------------------------------ + + /** + * Decrement a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to reduce by + * @return mixed New value on success or FALSE on failure + */ + public function decrement($id, $offset = 1) + { + return apc_dec($id, $offset); + } + + // ------------------------------------------------------------------------ + /** * Clean the cache * - * @return boolean false on failure/true on success + * @return bool false on failure/true on success */ public function clean() { @@ -89,38 +157,48 @@ class CI_Cache_apc extends CI_Driver { /** * Cache Info * - * @param string user/filehits - * @return mixed array on success, false on failure + * @param string user/filehits + * @return mixed array on success, false on failure */ - public function cache_info($type = NULL) - { - return apc_cache_info($type); - } + public function cache_info($type = NULL) + { + return apc_cache_info($type); + } // ------------------------------------------------------------------------ /** * Get Cache Metadata * - * @param mixed key to get cache metadata on - * @return mixed array on success/false on failure + * @param mixed key to get cache metadata on + * @return mixed array on success/false on failure */ public function get_metadata($id) { - $stored = apc_fetch($id); - - if (count($stored) !== 3) + $cache_info = apc_cache_info('user', FALSE); + if (empty($cache_info) OR empty($cache_info['cache_list'])) { return FALSE; } - list($data, $time, $ttl) = $stored; + foreach ($cache_info['cache_list'] as &$entry) + { + if ($entry['info'] !== $id) + { + continue; + } - return array( - 'expire' => $time + $ttl, - 'mtime' => $time, - 'data' => $data - ); + $success = FALSE; + $metadata = array( + 'expire' => ($entry['ttl'] ? $entry['mtime'] + $entry['ttl'] : 0), + 'mtime' => $entry['ttl'], + 'data' => apc_fetch($id, $success) + ); + + return ($success === TRUE) ? $metadata : FALSE; + } + + return FALSE; } // ------------------------------------------------------------------------ @@ -129,19 +207,11 @@ class CI_Cache_apc extends CI_Driver { * is_supported() * * Check to see if APC is available on this system, bail if it isn't. + * + * @return bool */ public function is_supported() { - if ( ! extension_loaded('apc') OR ini_get('apc.enabled') != "1") - { - log_message('error', 'The APC PHP extension must be loaded to use APC Cache.'); - return FALSE; - } - - return TRUE; + return (extension_loaded('apc') && ini_get('apc.enabled')); } - } - -/* End of file Cache_apc.php */ -/* Location: ./system/libraries/Cache/drivers/Cache_apc.php */ \ No newline at end of file diff --git a/system/libraries/Cache/drivers/Cache_dummy.php b/system/libraries/Cache/drivers/Cache_dummy.php old mode 100755 new mode 100644 index 6c38e91..fdb9042 --- a/system/libraries/Cache/drivers/Cache_dummy.php +++ b/system/libraries/Cache/drivers/Cache_dummy.php @@ -1,19 +1,41 @@ -load->helper('file'); - $path = $CI->config->item('cache_path'); - - $this->_cache_path = ($path == '') ? APPPATH.'cache/' : $path; + $this->_cache_path = ($path === '') ? APPPATH.'cache/' : $path; } // ------------------------------------------------------------------------ @@ -47,26 +73,13 @@ class CI_Cache_file extends CI_Driver { /** * Fetch from cache * - * @param mixed unique key id - * @return mixed data on success/false on failure + * @param string $id Cache ID + * @return mixed Data on success, FALSE on failure */ public function get($id) { - if ( ! file_exists($this->_cache_path.$id)) - { - return FALSE; - } - - $data = read_file($this->_cache_path.$id); - $data = unserialize($data); - - if (time() > $data['time'] + $data['ttl']) - { - unlink($this->_cache_path.$id); - return FALSE; - } - - return $data['data']; + $data = $this->_get($id); + return is_array($data) ? $data['data'] : FALSE; } // ------------------------------------------------------------------------ @@ -74,23 +87,23 @@ class CI_Cache_file extends CI_Driver { /** * Save into cache * - * @param string unique key - * @param mixed data to store - * @param int length of time (in seconds) the cache is valid - * - Default is 60 seconds - * @return boolean true on success/false on failure + * @param string $id Cache ID + * @param mixed $data Data to store + * @param int $ttl Time to live in seconds + * @param bool $raw Whether to store the raw value (unused) + * @return bool TRUE on success, FALSE on failure */ - public function save($id, $data, $ttl = 60) + public function save($id, $data, $ttl = 60, $raw = FALSE) { $contents = array( - 'time' => time(), - 'ttl' => $ttl, - 'data' => $data - ); + 'time' => time(), + 'ttl' => $ttl, + 'data' => $data + ); if (write_file($this->_cache_path.$id, serialize($contents))) { - @chmod($this->_cache_path.$id, 0777); + chmod($this->_cache_path.$id, 0640); return TRUE; } @@ -102,12 +115,68 @@ class CI_Cache_file extends CI_Driver { /** * Delete from Cache * - * @param mixed unique identifier of item in cache - * @return boolean true on success/false on failure + * @param mixed unique identifier of item in cache + * @return bool true on success/false on failure */ public function delete($id) { - return unlink($this->_cache_path.$id); + return is_file($this->_cache_path.$id) ? unlink($this->_cache_path.$id) : FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * Increment a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to add + * @return New value on success, FALSE on failure + */ + public function increment($id, $offset = 1) + { + $data = $this->_get($id); + + if ($data === FALSE) + { + $data = array('data' => 0, 'ttl' => 60); + } + elseif ( ! is_int($data['data'])) + { + return FALSE; + } + + $new_value = $data['data'] + $offset; + return $this->save($id, $new_value, $data['ttl']) + ? $new_value + : FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * Decrement a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to reduce by + * @return New value on success, FALSE on failure + */ + public function decrement($id, $offset = 1) + { + $data = $this->_get($id); + + if ($data === FALSE) + { + $data = array('data' => 0, 'ttl' => 60); + } + elseif ( ! is_int($data['data'])) + { + return FALSE; + } + + $new_value = $data['data'] - $offset; + return $this->save($id, $new_value, $data['ttl']) + ? $new_value + : FALSE; } // ------------------------------------------------------------------------ @@ -115,11 +184,11 @@ class CI_Cache_file extends CI_Driver { /** * Clean the Cache * - * @return boolean false on failure/true on success + * @return bool false on failure/true on success */ public function clean() { - return delete_files($this->_cache_path); + return delete_files($this->_cache_path, FALSE, TRUE); } // ------------------------------------------------------------------------ @@ -129,8 +198,8 @@ class CI_Cache_file extends CI_Driver { * * Not supported by file-based caching * - * @param string user/filehits - * @return mixed FALSE + * @param string user/filehits + * @return mixed FALSE */ public function cache_info($type = NULL) { @@ -142,31 +211,30 @@ class CI_Cache_file extends CI_Driver { /** * Get Cache Metadata * - * @param mixed key to get cache metadata on - * @return mixed FALSE on failure, array on success. + * @param mixed key to get cache metadata on + * @return mixed FALSE on failure, array on success. */ public function get_metadata($id) { - if ( ! file_exists($this->_cache_path.$id)) + if ( ! is_file($this->_cache_path.$id)) { return FALSE; } - $data = read_file($this->_cache_path.$id); - $data = unserialize($data); + $data = unserialize(file_get_contents($this->_cache_path.$id)); if (is_array($data)) { $mtime = filemtime($this->_cache_path.$id); - if ( ! isset($data['ttl'])) + if ( ! isset($data['ttl'], $data['time'])) { return FALSE; } return array( - 'expire' => $mtime + $data['ttl'], - 'mtime' => $mtime + 'expire' => $data['time'] + $data['ttl'], + 'mtime' => $mtime ); } @@ -180,14 +248,39 @@ class CI_Cache_file extends CI_Driver { * * In the file driver, check to see that the cache directory is indeed writable * - * @return boolean + * @return bool */ public function is_supported() { return is_really_writable($this->_cache_path); } -} + // ------------------------------------------------------------------------ -/* End of file Cache_file.php */ -/* Location: ./system/libraries/Cache/drivers/Cache_file.php */ \ No newline at end of file + /** + * Get all data + * + * Internal method to get all the relevant data about a cache item + * + * @param string $id Cache ID + * @return mixed Data array on success or FALSE on failure + */ + protected function _get($id) + { + if ( ! is_file($this->_cache_path.$id)) + { + return FALSE; + } + + $data = unserialize(file_get_contents($this->_cache_path.$id)); + + if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl']) + { + file_exists($this->_cache_path.$id) && unlink($this->_cache_path.$id); + return FALSE; + } + + return $data; + } + +} diff --git a/system/libraries/Cache/drivers/Cache_memcached.php b/system/libraries/Cache/drivers/Cache_memcached.php old mode 100755 new mode 100644 index f9d578b..bdc86a5 --- a/system/libraries/Cache/drivers/Cache_memcached.php +++ b/system/libraries/Cache/drivers/Cache_memcached.php @@ -1,19 +1,41 @@ - array( - 'default_host' => '127.0.0.1', - 'default_port' => 11211, - 'default_weight' => 1 - ) + /** + * Memcached configuration + * + * @var array + */ + protected $_config = array( + 'default' => array( + 'host' => '127.0.0.1', + 'port' => 11211, + 'weight' => 1 + ) + ); + + // ------------------------------------------------------------------------ + + /** + * Class constructor + * + * Setup Memcache(d) + * + * @return void + */ + public function __construct() + { + // Try to load memcached server info from the config file. + $CI =& get_instance(); + $defaults = $this->_config['default']; + + if ($CI->config->load('memcached', TRUE, TRUE)) + { + $this->_config = $CI->config->config['memcached']; + } + + if (class_exists('Memcached', FALSE)) + { + $this->_memcached = new Memcached(); + } + elseif (class_exists('Memcache', FALSE)) + { + $this->_memcached = new Memcache(); + } + else + { + log_message('error', 'Cache: Failed to create Memcache(d) object; extension not loaded?'); + return; + } + + foreach ($this->_config as $cache_server) + { + isset($cache_server['hostname']) OR $cache_server['hostname'] = $defaults['host']; + isset($cache_server['port']) OR $cache_server['port'] = $defaults['port']; + isset($cache_server['weight']) OR $cache_server['weight'] = $defaults['weight']; + + if ($this->_memcached instanceof Memcache) + { + // Third parameter is persistence and defaults to TRUE. + $this->_memcached->addServer( + $cache_server['hostname'], + $cache_server['port'], + TRUE, + $cache_server['weight'] ); + } + elseif ($this->_memcached instanceof Memcached) + { + $this->_memcached->addServer( + $cache_server['hostname'], + $cache_server['port'], + $cache_server['weight'] + ); + } + } + } // ------------------------------------------------------------------------ /** * Fetch from cache * - * @param mixed unique key id - * @return mixed data on success/false on failure + * @param string $id Cache ID + * @return mixed Data on success, FALSE on failure */ public function get($id) { $data = $this->_memcached->get($id); - return (is_array($data)) ? $data[0] : FALSE; + return is_array($data) ? $data[0] : $data; } // ------------------------------------------------------------------------ @@ -57,20 +149,26 @@ class CI_Cache_memcached extends CI_Driver { /** * Save * - * @param string unique identifier - * @param mixed data being cached - * @param int time to live - * @return boolean true on success, false on failure + * @param string $id Cache ID + * @param mixed $data Data being cached + * @param int $ttl Time to live + * @param bool $raw Whether to store the raw value + * @return bool TRUE on success, FALSE on failure */ - public function save($id, $data, $ttl = 60) + public function save($id, $data, $ttl = 60, $raw = FALSE) { - if (get_class($this->_memcached) == 'Memcached') + if ($raw !== TRUE) { - return $this->_memcached->set($id, array($data, time(), $ttl), $ttl); + $data = array($data, time(), $ttl); } - else if (get_class($this->_memcached) == 'Memcache') + + if ($this->_memcached instanceof Memcached) { - return $this->_memcached->set($id, array($data, time(), $ttl), 0, $ttl); + return $this->_memcached->set($id, $data, $ttl); + } + elseif ($this->_memcached instanceof Memcache) + { + return $this->_memcached->set($id, $data, 0, $ttl); } return FALSE; @@ -81,8 +179,8 @@ class CI_Cache_memcached extends CI_Driver { /** * Delete from Cache * - * @param mixed key to be deleted. - * @return boolean true on success, false on failure + * @param mixed $id key to be deleted. + * @return bool true on success, false on failure */ public function delete($id) { @@ -91,10 +189,48 @@ class CI_Cache_memcached extends CI_Driver { // ------------------------------------------------------------------------ + /** + * Increment a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to add + * @return mixed New value on success or FALSE on failure + */ + public function increment($id, $offset = 1) + { + if (($result = $this->_memcached->increment($id, $offset)) === FALSE) + { + return $this->_memcached->add($id, $offset) ? $offset : FALSE; + } + + return $result; + } + + // ------------------------------------------------------------------------ + + /** + * Decrement a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to reduce by + * @return mixed New value on success or FALSE on failure + */ + public function decrement($id, $offset = 1) + { + if (($result = $this->_memcached->decrement($id, $offset)) === FALSE) + { + return $this->_memcached->add($id, 0) ? 0 : FALSE; + } + + return $result; + } + + // ------------------------------------------------------------------------ + /** * Clean the Cache * - * @return boolean false on failure/true on success + * @return bool false on failure/true on success */ public function clean() { @@ -106,10 +242,9 @@ class CI_Cache_memcached extends CI_Driver { /** * Cache Info * - * @param null type not supported in memcached - * @return mixed array on success, false on failure + * @return mixed array on success, false on failure */ - public function cache_info($type = NULL) + public function cache_info() { return $this->_memcached->getStats(); } @@ -119,8 +254,8 @@ class CI_Cache_memcached extends CI_Driver { /** * Get Cache Metadata * - * @param mixed key to get cache metadata on - * @return mixed FALSE on failure, array on success. + * @param mixed $id key to get cache metadata on + * @return mixed FALSE on failure, array on success. */ public function get_metadata($id) { @@ -142,73 +277,37 @@ class CI_Cache_memcached extends CI_Driver { // ------------------------------------------------------------------------ - /** - * Setup memcached. - */ - private function _setup_memcached() - { - // Try to load memcached server info from the config file. - $CI =& get_instance(); - if ($CI->config->load('memcached', TRUE, TRUE)) - { - if (is_array($CI->config->config['memcached'])) - { - $this->_memcache_conf = NULL; - - foreach ($CI->config->config['memcached'] as $name => $conf) - { - $this->_memcache_conf[$name] = $conf; - } - } - } - - $this->_memcached = new Memcached(); - - foreach ($this->_memcache_conf as $name => $cache_server) - { - if ( ! array_key_exists('hostname', $cache_server)) - { - $cache_server['hostname'] = $this->_default_options['default_host']; - } - - if ( ! array_key_exists('port', $cache_server)) - { - $cache_server['port'] = $this->_default_options['default_port']; - } - - if ( ! array_key_exists('weight', $cache_server)) - { - $cache_server['weight'] = $this->_default_options['default_weight']; - } - - $this->_memcached->addServer( - $cache_server['hostname'], $cache_server['port'], $cache_server['weight'] - ); - } - } - - // ------------------------------------------------------------------------ - - /** * Is supported * * Returns FALSE if memcached is not supported on the system. * If it is, we setup the memcached object & return TRUE + * + * @return bool */ public function is_supported() { - if ( ! extension_loaded('memcached')) - { - log_message('error', 'The Memcached Extension must be loaded to use Memcached Cache.'); - return FALSE; - } - - $this->_setup_memcached(); - return TRUE; + return (extension_loaded('memcached') OR extension_loaded('memcache')); } -} + // ------------------------------------------------------------------------ -/* End of file Cache_memcached.php */ -/* Location: ./system/libraries/Cache/drivers/Cache_memcached.php */ \ No newline at end of file + /** + * Class destructor + * + * Closes the connection to Memcache(d) if present. + * + * @return void + */ + public function __destruct() + { + if ($this->_memcached instanceof Memcache) + { + $this->_memcached->close(); + } + elseif ($this->_memcached instanceof Memcached && method_exists($this->_memcached, 'quit')) + { + $this->_memcached->quit(); + } + } +} diff --git a/system/libraries/Cache/drivers/Cache_redis.php b/system/libraries/Cache/drivers/Cache_redis.php new file mode 100644 index 0000000..3759618 --- /dev/null +++ b/system/libraries/Cache/drivers/Cache_redis.php @@ -0,0 +1,328 @@ + + * @link + */ +class CI_Cache_redis extends CI_Driver +{ + /** + * Default config + * + * @static + * @var array + */ + protected static $_default_config = array( + 'socket_type' => 'tcp', + 'host' => '127.0.0.1', + 'password' => NULL, + 'port' => 6379, + 'timeout' => 0 + ); + + /** + * Redis connection + * + * @var Redis + */ + protected $_redis; + + /** + * An internal cache for storing keys of serialized values. + * + * @var array + */ + protected $_serialized = array(); + + // ------------------------------------------------------------------------ + + /** + * Class constructor + * + * Setup Redis + * + * Loads Redis config file if present. Will halt execution + * if a Redis connection can't be established. + * + * @return void + * @see Redis::connect() + */ + public function __construct() + { + if ( ! $this->is_supported()) + { + log_message('error', 'Cache: Failed to create Redis object; extension not loaded?'); + return; + } + + $CI =& get_instance(); + + if ($CI->config->load('redis', TRUE, TRUE)) + { + $config = array_merge(self::$_default_config, $CI->config->item('redis')); + } + else + { + $config = self::$_default_config; + } + + $this->_redis = new Redis(); + + try + { + if ($config['socket_type'] === 'unix') + { + $success = $this->_redis->connect($config['socket']); + } + else // tcp socket + { + $success = $this->_redis->connect($config['host'], $config['port'], $config['timeout']); + } + + if ( ! $success) + { + log_message('error', 'Cache: Redis connection failed. Check your configuration.'); + } + + if (isset($config['password']) && ! $this->_redis->auth($config['password'])) + { + log_message('error', 'Cache: Redis authentication failed.'); + } + } + catch (RedisException $e) + { + log_message('error', 'Cache: Redis connection refused ('.$e->getMessage().')'); + } + + // Initialize the index of serialized values. + $serialized = $this->_redis->sMembers('_ci_redis_serialized'); + empty($serialized) OR $this->_serialized = array_flip($serialized); + } + + // ------------------------------------------------------------------------ + + /** + * Get cache + * + * @param string $key Cache ID + * @return mixed + */ + public function get($key) + { + $value = $this->_redis->get($key); + + if ($value !== FALSE && isset($this->_serialized[$key])) + { + return unserialize($value); + } + + return $value; + } + + // ------------------------------------------------------------------------ + + /** + * Save cache + * + * @param string $id Cache ID + * @param mixed $data Data to save + * @param int $ttl Time to live in seconds + * @param bool $raw Whether to store the raw value (unused) + * @return bool TRUE on success, FALSE on failure + */ + public function save($id, $data, $ttl = 60, $raw = FALSE) + { + if (is_array($data) OR is_object($data)) + { + if ( ! $this->_redis->sIsMember('_ci_redis_serialized', $id) && ! $this->_redis->sAdd('_ci_redis_serialized', $id)) + { + return FALSE; + } + + isset($this->_serialized[$id]) OR $this->_serialized[$id] = TRUE; + $data = serialize($data); + } + elseif (isset($this->_serialized[$id])) + { + $this->_serialized[$id] = NULL; + $this->_redis->sRemove('_ci_redis_serialized', $id); + } + + return $this->_redis->set($id, $data, $ttl); + } + + // ------------------------------------------------------------------------ + + /** + * Delete from cache + * + * @param string $key Cache key + * @return bool + */ + public function delete($key) + { + if ($this->_redis->delete($key) !== 1) + { + return FALSE; + } + + if (isset($this->_serialized[$key])) + { + $this->_serialized[$key] = NULL; + $this->_redis->sRemove('_ci_redis_serialized', $key); + } + + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Increment a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to add + * @return mixed New value on success or FALSE on failure + */ + public function increment($id, $offset = 1) + { + return $this->_redis->incr($id, $offset); + } + + // ------------------------------------------------------------------------ + + /** + * Decrement a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to reduce by + * @return mixed New value on success or FALSE on failure + */ + public function decrement($id, $offset = 1) + { + return $this->_redis->decr($id, $offset); + } + + // ------------------------------------------------------------------------ + + /** + * Clean cache + * + * @return bool + * @see Redis::flushDB() + */ + public function clean() + { + return $this->_redis->flushDB(); + } + + // ------------------------------------------------------------------------ + + /** + * Get cache driver info + * + * @param string $type Not supported in Redis. + * Only included in order to offer a + * consistent cache API. + * @return array + * @see Redis::info() + */ + public function cache_info($type = NULL) + { + return $this->_redis->info(); + } + + // ------------------------------------------------------------------------ + + /** + * Get cache metadata + * + * @param string $key Cache key + * @return array + */ + public function get_metadata($key) + { + $value = $this->get($key); + + if ($value !== FALSE) + { + return array( + 'expire' => time() + $this->_redis->ttl($key), + 'data' => $value + ); + } + + return FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * Check if Redis driver is supported + * + * @return bool + */ + public function is_supported() + { + return extension_loaded('redis'); + } + + // ------------------------------------------------------------------------ + + /** + * Class destructor + * + * Closes the connection to Redis if present. + * + * @return void + */ + public function __destruct() + { + if ($this->_redis) + { + $this->_redis->close(); + } + } +} diff --git a/system/libraries/Cache/drivers/Cache_wincache.php b/system/libraries/Cache/drivers/Cache_wincache.php new file mode 100644 index 0000000..1feaa15 --- /dev/null +++ b/system/libraries/Cache/drivers/Cache_wincache.php @@ -0,0 +1,217 @@ +is_supported()) + { + log_message('error', 'Cache: Failed to initialize Wincache; extension not loaded/enabled?'); + } + } + + // ------------------------------------------------------------------------ + + /** + * Get + * + * Look for a value in the cache. If it exists, return the data, + * if not, return FALSE + * + * @param string $id Cache Ide + * @return mixed Value that is stored/FALSE on failure + */ + public function get($id) + { + $success = FALSE; + $data = wincache_ucache_get($id, $success); + + // Success returned by reference from wincache_ucache_get() + return ($success) ? $data : FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * Cache Save + * + * @param string $id Cache ID + * @param mixed $data Data to store + * @param int $ttl Time to live (in seconds) + * @param bool $raw Whether to store the raw value (unused) + * @return bool true on success/false on failure + */ + public function save($id, $data, $ttl = 60, $raw = FALSE) + { + return wincache_ucache_set($id, $data, $ttl); + } + + // ------------------------------------------------------------------------ + + /** + * Delete from Cache + * + * @param mixed unique identifier of the item in the cache + * @return bool true on success/false on failure + */ + public function delete($id) + { + return wincache_ucache_delete($id); + } + + // ------------------------------------------------------------------------ + + /** + * Increment a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to add + * @return mixed New value on success or FALSE on failure + */ + public function increment($id, $offset = 1) + { + $success = FALSE; + $value = wincache_ucache_inc($id, $offset, $success); + + return ($success === TRUE) ? $value : FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * Decrement a raw value + * + * @param string $id Cache ID + * @param int $offset Step/value to reduce by + * @return mixed New value on success or FALSE on failure + */ + public function decrement($id, $offset = 1) + { + $success = FALSE; + $value = wincache_ucache_dec($id, $offset, $success); + + return ($success === TRUE) ? $value : FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * Clean the cache + * + * @return bool false on failure/true on success + */ + public function clean() + { + return wincache_ucache_clear(); + } + + // ------------------------------------------------------------------------ + + /** + * Cache Info + * + * @return mixed array on success, false on failure + */ + public function cache_info() + { + return wincache_ucache_info(TRUE); + } + + // ------------------------------------------------------------------------ + + /** + * Get Cache Metadata + * + * @param mixed key to get cache metadata on + * @return mixed array on success/false on failure + */ + public function get_metadata($id) + { + if ($stored = wincache_ucache_info(FALSE, $id)) + { + $age = $stored['ucache_entries'][1]['age_seconds']; + $ttl = $stored['ucache_entries'][1]['ttl_seconds']; + $hitcount = $stored['ucache_entries'][1]['hitcount']; + + return array( + 'expire' => $ttl - $age, + 'hitcount' => $hitcount, + 'age' => $age, + 'ttl' => $ttl + ); + } + + return FALSE; + } + + // ------------------------------------------------------------------------ + + /** + * is_supported() + * + * Check to see if WinCache is available on this system, bail if it isn't. + * + * @return bool + */ + public function is_supported() + { + return (extension_loaded('wincache') && ini_get('wincache.ucenabled')); + } +} diff --git a/system/libraries/Cache/drivers/index.html b/system/libraries/Cache/drivers/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/libraries/Cache/drivers/index.html +++ b/system/libraries/Cache/drivers/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file + diff --git a/system/libraries/Cache/index.html b/system/libraries/Cache/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/libraries/Cache/index.html +++ b/system/libraries/Cache/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file + diff --git a/system/libraries/Calendar.php b/system/libraries/Calendar.php old mode 100755 new mode 100644 index 626097a..a6bdae5 --- a/system/libraries/Calendar.php +++ b/system/libraries/Calendar.php @@ -1,19 +1,41 @@ -CI =& get_instance(); + $this->CI->lang->load('calendar'); - if ( ! in_array('calendar_lang.php', $this->CI->lang->is_loaded, TRUE)) - { - $this->CI->lang->load('calendar'); - } + empty($config) OR $this->initialize($config); - $this->local_time = time(); - - if (count($config) > 0) - { - $this->initialize($config); - } - - log_message('debug', "Calendar Class Initialized"); + log_message('info', 'Calendar Class Initialized'); } // -------------------------------------------------------------------- @@ -69,11 +144,10 @@ class CI_Calendar { * * Accepts an associative array as input, containing display preferences * - * @access public * @param array config preferences - * @return void + * @return CI_Calendar */ - function initialize($config = array()) + public function initialize($config = array()) { foreach ($config as $key => $val) { @@ -82,6 +156,14 @@ class CI_Calendar { $this->$key = $val; } } + + // Set the next_prev_url to the controller if required but not defined + if ($this->show_next_prev === TRUE && empty($this->next_prev_url)) + { + $this->next_prev_url = $this->CI->config->site_url($this->CI->router->class.'/'.$this->CI->router->method); + } + + return $this; } // -------------------------------------------------------------------- @@ -89,29 +171,37 @@ class CI_Calendar { /** * Generate the calendar * - * @access public - * @param integer the year - * @param integer the month + * @param int the year + * @param int the month * @param array the data to be shown in the calendar cells * @return string */ - function generate($year = '', $month = '', $data = array()) + public function generate($year = '', $month = '', $data = array()) { + $local_time = time(); + // Set and validate the supplied month/year - if ($year == '') - $year = date("Y", $this->local_time); - - if ($month == '') - $month = date("m", $this->local_time); - - if (strlen($year) == 1) + if (empty($year)) + { + $year = date('Y', $local_time); + } + elseif (strlen($year) === 1) + { $year = '200'.$year; - - if (strlen($year) == 2) + } + elseif (strlen($year) === 2) + { $year = '20'.$year; + } - if (strlen($month) == 1) + if (empty($month)) + { + $month = date('m', $local_time); + } + elseif (strlen($month) === 1) + { $month = '0'.$month; + } $adjusted_date = $this->adjust_date($month, $year); @@ -123,12 +213,12 @@ class CI_Calendar { // Set the starting day of the week $start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6); - $start_day = ( ! isset($start_days[$this->start_day])) ? 0 : $start_days[$this->start_day]; + $start_day = isset($start_days[$this->start_day]) ? $start_days[$this->start_day] : 0; // Set the starting day number $local_date = mktime(12, 0, 0, $month, 1, $year); $date = getdate($local_date); - $day = $start_day + 1 - $date["wday"]; + $day = $start_day + 1 - $date['wday']; while ($day > 1) { @@ -137,115 +227,116 @@ class CI_Calendar { // Set the current month/year/day // We use this to determine the "today" date - $cur_year = date("Y", $this->local_time); - $cur_month = date("m", $this->local_time); - $cur_day = date("j", $this->local_time); + $cur_year = date('Y', $local_time); + $cur_month = date('m', $local_time); + $cur_day = date('j', $local_time); - $is_current_month = ($cur_year == $year AND $cur_month == $month) ? TRUE : FALSE; + $is_current_month = ($cur_year == $year && $cur_month == $month); // Generate the template data array $this->parse_template(); // Begin building the calendar output - $out = $this->temp['table_open']; - $out .= "\n"; - - $out .= "\n"; - $out .= $this->temp['heading_row_start']; - $out .= "\n"; + $out = $this->replacements['table_open']."\n\n".$this->replacements['heading_row_start']."\n"; // "previous" month link - if ($this->show_next_prev == TRUE) + if ($this->show_next_prev === TRUE) { - // Add a trailing slash to the URL if needed - $this->next_prev_url = preg_replace("/(.+?)\/*$/", "\\1/", $this->next_prev_url); + // Add a trailing slash to the URL if needed + $this->next_prev_url = preg_replace('/(.+?)\/*$/', '\\1/', $this->next_prev_url); $adjusted_date = $this->adjust_date($month - 1, $year); - $out .= str_replace('{previous_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_previous_cell']); - $out .= "\n"; + $out .= str_replace('{previous_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->replacements['heading_previous_cell'])."\n"; } // Heading containing the month/year - $colspan = ($this->show_next_prev == TRUE) ? 5 : 7; + $colspan = ($this->show_next_prev === TRUE) ? 5 : 7; - $this->temp['heading_title_cell'] = str_replace('{colspan}', $colspan, $this->temp['heading_title_cell']); - $this->temp['heading_title_cell'] = str_replace('{heading}', $this->get_month_name($month)." ".$year, $this->temp['heading_title_cell']); + $this->replacements['heading_title_cell'] = str_replace('{colspan}', $colspan, + str_replace('{heading}', $this->get_month_name($month).' '.$year, $this->replacements['heading_title_cell'])); - $out .= $this->temp['heading_title_cell']; - $out .= "\n"; + $out .= $this->replacements['heading_title_cell']."\n"; // "next" month link - if ($this->show_next_prev == TRUE) + if ($this->show_next_prev === TRUE) { $adjusted_date = $this->adjust_date($month + 1, $year); - $out .= str_replace('{next_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_next_cell']); + $out .= str_replace('{next_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->replacements['heading_next_cell']); } - $out .= "\n"; - $out .= $this->temp['heading_row_end']; - $out .= "\n"; - - // Write the cells containing the days of the week - $out .= "\n"; - $out .= $this->temp['week_row_start']; - $out .= "\n"; + $out .= "\n".$this->replacements['heading_row_end']."\n\n" + // Write the cells containing the days of the week + .$this->replacements['week_row_start']."\n"; $day_names = $this->get_day_names(); for ($i = 0; $i < 7; $i ++) { - $out .= str_replace('{week_day}', $day_names[($start_day + $i) %7], $this->temp['week_day_cell']); + $out .= str_replace('{week_day}', $day_names[($start_day + $i) %7], $this->replacements['week_day_cell']); } - $out .= "\n"; - $out .= $this->temp['week_row_end']; - $out .= "\n"; + $out .= "\n".$this->replacements['week_row_end']."\n"; // Build the main body of the calendar while ($day <= $total_days) { - $out .= "\n"; - $out .= $this->temp['cal_row_start']; - $out .= "\n"; + $out .= "\n".$this->replacements['cal_row_start']."\n"; for ($i = 0; $i < 7; $i++) { - $out .= ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_start_today'] : $this->temp['cal_cell_start']; - - if ($day > 0 AND $day <= $total_days) + if ($day > 0 && $day <= $total_days) { + $out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_start_today'] : $this->replacements['cal_cell_start']; + if (isset($data[$day])) { // Cells with content - $temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_content_today'] : $this->temp['cal_cell_content']; - $out .= str_replace('{day}', $day, str_replace('{content}', $data[$day], $temp)); + $temp = ($is_current_month === TRUE && $day == $cur_day) ? + $this->replacements['cal_cell_content_today'] : $this->replacements['cal_cell_content']; + $out .= str_replace(array('{content}', '{day}'), array($data[$day], $day), $temp); } else { // Cells with no content - $temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_no_content_today'] : $this->temp['cal_cell_no_content']; + $temp = ($is_current_month === TRUE && $day == $cur_day) ? + $this->replacements['cal_cell_no_content_today'] : $this->replacements['cal_cell_no_content']; $out .= str_replace('{day}', $day, $temp); } + + $out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->replacements['cal_cell_end_today'] : $this->replacements['cal_cell_end']; + } + elseif ($this->show_other_days === TRUE) + { + $out .= $this->replacements['cal_cell_start_other']; + + if ($day <= 0) + { + // Day of previous month + $prev_month = $this->adjust_date($month - 1, $year); + $prev_month_days = $this->get_total_days($prev_month['month'], $prev_month['year']); + $out .= str_replace('{day}', $prev_month_days + $day, $this->replacements['cal_cell_other']); + } + else + { + // Day of next month + $out .= str_replace('{day}', $day - $total_days, $this->replacements['cal_cell_other']); + } + + $out .= $this->replacements['cal_cell_end_other']; } else { // Blank cells - $out .= $this->temp['cal_cell_blank']; + $out .= $this->replacements['cal_cell_start'].$this->replacements['cal_cell_blank'].$this->replacements['cal_cell_end']; } - $out .= ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_end_today'] : $this->temp['cal_cell_end']; $day++; } - $out .= "\n"; - $out .= $this->temp['cal_row_end']; - $out .= "\n"; + $out .= "\n".$this->replacements['cal_row_end']."\n"; } - $out .= "\n"; - $out .= $this->temp['table_close']; - - return $out; + return $out .= "\n".$this->replacements['table_close']; } // -------------------------------------------------------------------- @@ -256,13 +347,12 @@ class CI_Calendar { * Generates a textual month name based on the numeric * month provided. * - * @access public - * @param integer the month + * @param int the month * @return string */ - function get_month_name($month) + public function get_month_name($month) { - if ($this->month_type == 'short') + if ($this->month_type === 'short') { $month_names = array('01' => 'cal_jan', '02' => 'cal_feb', '03' => 'cal_mar', '04' => 'cal_apr', '05' => 'cal_may', '06' => 'cal_jun', '07' => 'cal_jul', '08' => 'cal_aug', '09' => 'cal_sep', '10' => 'cal_oct', '11' => 'cal_nov', '12' => 'cal_dec'); } @@ -271,14 +361,9 @@ class CI_Calendar { $month_names = array('01' => 'cal_january', '02' => 'cal_february', '03' => 'cal_march', '04' => 'cal_april', '05' => 'cal_mayl', '06' => 'cal_june', '07' => 'cal_july', '08' => 'cal_august', '09' => 'cal_september', '10' => 'cal_october', '11' => 'cal_november', '12' => 'cal_december'); } - $month = $month_names[$month]; - - if ($this->CI->lang->line($month) === FALSE) - { - return ucfirst(str_replace('cal_', '', $month)); - } - - return $this->CI->lang->line($month); + return ($this->CI->lang->line($month_names[$month]) === FALSE) + ? ucfirst(substr($month_names[$month], 4)) + : $this->CI->lang->line($month_names[$month]); } // -------------------------------------------------------------------- @@ -287,22 +372,23 @@ class CI_Calendar { * Get Day Names * * Returns an array of day names (Sunday, Monday, etc.) based - * on the type. Options: long, short, abrev + * on the type. Options: long, short, abr * - * @access public * @param string * @return array */ - function get_day_names($day_type = '') + public function get_day_names($day_type = '') { - if ($day_type != '') + if ($day_type !== '') + { $this->day_type = $day_type; + } - if ($this->day_type == 'long') + if ($this->day_type === 'long') { $day_names = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'); } - elseif ($this->day_type == 'short') + elseif ($this->day_type === 'short') { $day_names = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'); } @@ -312,9 +398,9 @@ class CI_Calendar { } $days = array(); - foreach ($day_names as $val) + for ($i = 0, $c = count($day_names); $i < $c; $i++) { - $days[] = ($this->CI->lang->line('cal_'.$val) === FALSE) ? ucfirst($val) : $this->CI->lang->line('cal_'.$val); + $days[] = ($this->CI->lang->line('cal_'.$day_names[$i]) === FALSE) ? ucfirst($day_names[$i]) : $this->CI->lang->line('cal_'.$day_names[$i]); } return $days; @@ -329,12 +415,11 @@ class CI_Calendar { * For example, if you submit 13 as the month, the year will * increment and the month will become January. * - * @access public - * @param integer the month - * @param integer the year + * @param int the month + * @param int the year * @return array */ - function adjust_date($month, $year) + public function adjust_date($month, $year) { $date = array(); @@ -353,7 +438,7 @@ class CI_Calendar { $date['year']--; } - if (strlen($date['month']) == 1) + if (strlen($date['month']) === 1) { $date['month'] = '0'.$date['month']; } @@ -366,30 +451,14 @@ class CI_Calendar { /** * Total days in a given month * - * @access public - * @param integer the month - * @param integer the year - * @return integer + * @param int the month + * @param int the year + * @return int */ - function get_total_days($month, $year) + public function get_total_days($month, $year) { - $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); - - if ($month < 1 OR $month > 12) - { - return 0; - } - - // Is the year a leap year? - if ($month == 2) - { - if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0)) - { - return 29; - } - } - - return $days_in_month[$month - 1]; + $this->CI->load->helper('date'); + return days_in_month($month, $year); } // -------------------------------------------------------------------- @@ -399,34 +468,36 @@ class CI_Calendar { * * This is used in the event that the user has not created their own template * - * @access public - * @return array + * @return array */ - function default_template() + public function default_template() { - return array ( - 'table_open' => '', - 'heading_row_start' => '', - 'heading_previous_cell' => '', - 'heading_title_cell' => '', - 'heading_next_cell' => '', - 'heading_row_end' => '', - 'week_row_start' => '', - 'week_day_cell' => '', - 'week_row_end' => '', - 'cal_row_start' => '', - 'cal_cell_start' => '', - 'cal_cell_end_today' => '', - 'cal_row_end' => '', - 'table_close' => '
    <<{heading}>>
    {week_day}
    ', - 'cal_cell_start_today' => '', - 'cal_cell_content' => '{day}', - 'cal_cell_content_today' => '{day}', - 'cal_cell_no_content' => '{day}', - 'cal_cell_no_content_today' => '{day}', - 'cal_cell_blank' => ' ', - 'cal_cell_end' => '
    ' - ); + return array( + 'table_open' => '', + 'heading_row_start' => '', + 'heading_previous_cell' => '', + 'heading_title_cell' => '', + 'heading_next_cell' => '', + 'heading_row_end' => '', + 'week_row_start' => '', + 'week_day_cell' => '', + 'week_row_end' => '', + 'cal_row_start' => '', + 'cal_cell_start' => '', + 'cal_cell_end_today' => '', + 'cal_cell_end_other' => '', + 'cal_row_end' => '', + 'table_close' => '
    <<{heading}>>
    {week_day}
    ', + 'cal_cell_start_today' => '', + 'cal_cell_start_other' => '', + 'cal_cell_content' => '{day}', + 'cal_cell_content_today' => '{day}', + 'cal_cell_no_content' => '{day}', + 'cal_cell_no_content_today' => '{day}', + 'cal_cell_blank' => ' ', + 'cal_cell_other' => '{day}', + 'cal_cell_end' => '
    ' + ); } // -------------------------------------------------------------------- @@ -437,39 +508,39 @@ class CI_Calendar { * Harvests the data within the template {pseudo-variables} * used to display the calendar * - * @access public - * @return void + * @return CI_Calendar */ - function parse_template() + public function parse_template() { - $this->temp = $this->default_template(); + $this->replacements = $this->default_template(); - if ($this->template == '') + if (empty($this->template)) { - return; + return $this; } - $today = array('cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today'); - - foreach (array('table_open', 'table_close', 'heading_row_start', 'heading_previous_cell', 'heading_title_cell', 'heading_next_cell', 'heading_row_end', 'week_row_start', 'week_day_cell', 'week_row_end', 'cal_row_start', 'cal_cell_start', 'cal_cell_content', 'cal_cell_no_content', 'cal_cell_blank', 'cal_cell_end', 'cal_row_end', 'cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today') as $val) + if (is_string($this->template)) { - if (preg_match("/\{".$val."\}(.*?)\{\/".$val."\}/si", $this->template, $match)) + $today = array('cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today'); + + foreach (array('table_open', 'table_close', 'heading_row_start', 'heading_previous_cell', 'heading_title_cell', 'heading_next_cell', 'heading_row_end', 'week_row_start', 'week_day_cell', 'week_row_end', 'cal_row_start', 'cal_cell_start', 'cal_cell_content', 'cal_cell_no_content', 'cal_cell_blank', 'cal_cell_end', 'cal_row_end', 'cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today', 'cal_cell_start_other', 'cal_cell_other', 'cal_cell_end_other') as $val) { - $this->temp[$val] = $match['1']; - } - else - { - if (in_array($val, $today, TRUE)) + if (preg_match('/\{'.$val.'\}(.*?)\{\/'.$val.'\}/si', $this->template, $match)) { - $this->temp[$val] = $this->temp[str_replace('_today', '', $val)]; + $this->replacements[$val] = $match[1]; + } + elseif (in_array($val, $today, TRUE)) + { + $this->replacements[$val] = $this->replacements[substr($val, 0, -6)]; } } } + elseif (is_array($this->template)) + { + $this->replacements = array_merge($this->replacements, $this->template); + } + + return $this; } } - -// END CI_Calendar class - -/* End of file Calendar.php */ -/* Location: ./system/libraries/Calendar.php */ \ No newline at end of file diff --git a/system/libraries/Cart.php b/system/libraries/Cart.php old mode 100755 new mode 100644 index 86a01f7..6a10775 --- a/system/libraries/Cart.php +++ b/system/libraries/Cart.php @@ -1,19 +1,41 @@ -CI =& get_instance(); // Are any config settings being passed manually? If so, set them - $config = array(); - if (count($params) > 0) - { - foreach ($params as $key => $val) - { - $config[$key] = $val; - } - } + $config = is_array($params) ? $params : array(); // Load the Sessions class - $this->CI->load->library('session', $config); + $this->CI->load->driver('session', $config); - // Grab the shopping cart array from the session table, if it exists - if ($this->CI->session->userdata('cart_contents') !== FALSE) - { - $this->_cart_contents = $this->CI->session->userdata('cart_contents'); - } - else + // Grab the shopping cart array from the session table + $this->_cart_contents = $this->CI->session->userdata('cart_contents'); + if ($this->_cart_contents === NULL) { // No cart exists so we'll set some base values - $this->_cart_contents['cart_total'] = 0; - $this->_cart_contents['total_items'] = 0; + $this->_cart_contents = array('cart_total' => 0, 'total_items' => 0); } - log_message('debug', "Cart Class Initialized"); + log_message('info', 'Cart Class Initialized'); } // -------------------------------------------------------------------- @@ -78,14 +123,13 @@ class CI_Cart { /** * Insert items into the cart and save it to the session table * - * @access public * @param array * @return bool */ - function insert($items = array()) + public function insert($items = array()) { // Was any cart data passed? No? Bah... - if ( ! is_array($items) OR count($items) == 0) + if ( ! is_array($items) OR count($items) === 0) { log_message('error', 'The insert method must be passed an array containing data.'); return FALSE; @@ -108,7 +152,7 @@ class CI_Cart { { foreach ($items as $val) { - if (is_array($val) AND isset($val['id'])) + if (is_array($val) && isset($val['id'])) { if ($this->_insert($val)) { @@ -119,7 +163,7 @@ class CI_Cart { } // Save the cart data if the insert was successful - if ($save_cart == TRUE) + if ($save_cart === TRUE) { $this->_save_cart(); return isset($rowid) ? $rowid : TRUE; @@ -133,14 +177,13 @@ class CI_Cart { /** * Insert * - * @access private * @param array * @return bool */ - function _insert($items = array()) + protected function _insert($items = array()) { // Was any cart data passed? No? Bah... - if ( ! is_array($items) OR count($items) == 0) + if ( ! is_array($items) OR count($items) === 0) { log_message('error', 'The insert method must be passed an array containing data.'); return FALSE; @@ -149,7 +192,7 @@ class CI_Cart { // -------------------------------------------------------------------- // Does the $items array contain an id, quantity, price, and name? These are required - if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name'])) + if ( ! isset($items['id'], $items['qty'], $items['price'], $items['name'])) { log_message('error', 'The cart array must contain a product ID, quantity, price, and name.'); return FALSE; @@ -157,13 +200,11 @@ class CI_Cart { // -------------------------------------------------------------------- - // Prep the quantity. It can only be a number. Duh... - $items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty'])); - // Trim any leading zeros - $items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty'])); + // Prep the quantity. It can only be a number. Duh... also trim any leading zeros + $items['qty'] = (float) $items['qty']; // If the quantity is zero or blank there's nothing for us to do - if ( ! is_numeric($items['qty']) OR $items['qty'] == 0) + if ($items['qty'] == 0) { return FALSE; } @@ -173,7 +214,7 @@ class CI_Cart { // Validate the product ID. It can only be alpha-numeric, dashes, underscores or periods // Not totally sure we should impose this rule, but it seems prudent to standardize IDs. // Note: These can be user-specified by setting the $this->product_id_rules variable. - if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id'])) + if ( ! preg_match('/^['.$this->product_id_rules.']+$/i', $items['id'])) { log_message('error', 'Invalid product ID. The product ID can only contain alpha-numeric characters, dashes, and underscores'); return FALSE; @@ -183,7 +224,7 @@ class CI_Cart { // Validate the product name. It can only be alpha-numeric, dashes, underscores, colons or periods. // Note: These can be user-specified by setting the $this->product_name_rules variable. - if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name'])) + if ($this->product_name_safe && ! preg_match('/^['.$this->product_name_rules.']+$/i'.(UTF8_ENABLED ? 'u' : ''), $items['name'])) { log_message('error', 'An invalid name was submitted as the product name: '.$items['name'].' The name can only contain alpha-numeric characters, dashes, underscores, colons, and spaces'); return FALSE; @@ -191,19 +232,8 @@ class CI_Cart { // -------------------------------------------------------------------- - // Prep the price. Remove anything that isn't a number or decimal point. - $items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price'])); - // Trim any leading zeros - $items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price'])); - - // Is the price a valid number? - if ( ! is_numeric($items['price'])) - { - log_message('error', 'An invalid price was submitted for product ID: '.$items['id']); - return FALSE; - } - - // -------------------------------------------------------------------- + // Prep the price. Remove leading zeros and anything that isn't a number or decimal point. + $items['price'] = (float) $items['price']; // We now need to create a unique identifier for the item being inserted into the cart. // Every time something is added to the cart it is stored in the master cart array. @@ -215,9 +245,9 @@ class CI_Cart { // Internally, we need to treat identical submissions, but with different options, as a unique product. // Our solution is to convert the options array to a string and MD5 it along with the product ID. // This becomes the unique "row ID" - if (isset($items['options']) AND count($items['options']) > 0) + if (isset($items['options']) && count($items['options']) > 0) { - $rowid = md5($items['id'].implode('', $items['options'])); + $rowid = md5($items['id'].serialize($items['options'])); } else { @@ -230,20 +260,14 @@ class CI_Cart { // -------------------------------------------------------------------- // Now that we have our unique "row ID", we'll add our cart items to the master array + // grab quantity if it's already there and add it on + $old_quantity = isset($this->_cart_contents[$rowid]['qty']) ? (int) $this->_cart_contents[$rowid]['qty'] : 0; - // let's unset this first, just to make sure our index contains only the data from this submission - unset($this->_cart_contents[$rowid]); + // Re-create the entry, just to make sure our index contains only the data from this submission + $items['rowid'] = $rowid; + $items['qty'] += $old_quantity; + $this->_cart_contents[$rowid] = $items; - // Create a new index with our new row ID - $this->_cart_contents[$rowid]['rowid'] = $rowid; - - // And add the new items to the cart array - foreach ($items as $key => $val) - { - $this->_cart_contents[$rowid][$key] = $val; - } - - // Woot! return $rowid; } @@ -257,27 +281,25 @@ class CI_Cart { * changes to the quantity before checkout. That array must contain the * product ID and quantity for each item. * - * @access public * @param array - * @param string * @return bool */ - function update($items = array()) + public function update($items = array()) { // Was any cart data passed? - if ( ! is_array($items) OR count($items) == 0) + if ( ! is_array($items) OR count($items) === 0) { return FALSE; } // You can either update a single product using a one-dimensional array, // or multiple products using a multi-dimensional one. The way we - // determine the array type is by looking for a required array key named "id". + // determine the array type is by looking for a required array key named "rowid". // If it's not found we assume it's a multi-dimensional array $save_cart = FALSE; - if (isset($items['rowid']) AND isset($items['qty'])) + if (isset($items['rowid'])) { - if ($this->_update($items) == TRUE) + if ($this->_update($items) === TRUE) { $save_cart = TRUE; } @@ -286,9 +308,9 @@ class CI_Cart { { foreach ($items as $val) { - if (is_array($val) AND isset($val['rowid']) AND isset($val['qty'])) + if (is_array($val) && isset($val['rowid'])) { - if ($this->_update($val) == TRUE) + if ($this->_update($val) === TRUE) { $save_cart = TRUE; } @@ -297,7 +319,7 @@ class CI_Cart { } // Save the cart data if the insert was successful - if ($save_cart == TRUE) + if ($save_cart === TRUE) { $this->_save_cart(); return TRUE; @@ -311,48 +333,47 @@ class CI_Cart { /** * Update the cart * - * This function permits the quantity of a given item to be changed. + * This function permits changing item properties. * Typically it is called from the "view cart" page if a user makes * changes to the quantity before checkout. That array must contain the - * product ID and quantity for each item. + * rowid and quantity for each item. * - * @access private * @param array * @return bool */ - function _update($items = array()) + protected function _update($items = array()) { // Without these array indexes there is nothing we can do - if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']])) + if ( ! isset($items['rowid'], $this->_cart_contents[$items['rowid']])) { return FALSE; } // Prep the quantity - $items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']); - - // Is the quantity a number? - if ( ! is_numeric($items['qty'])) + if (isset($items['qty'])) { - return FALSE; + $items['qty'] = (float) $items['qty']; + // Is the quantity zero? If so we will remove the item from the cart. + // If the quantity is greater than zero we are updating + if ($items['qty'] == 0) + { + unset($this->_cart_contents[$items['rowid']]); + return TRUE; + } } - // Is the new quantity different than what is already saved in the cart? - // If it's the same there's nothing to do - if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty']) + // find updatable keys + $keys = array_intersect(array_keys($this->_cart_contents[$items['rowid']]), array_keys($items)); + // if a price was passed, make sure it contains valid data + if (isset($items['price'])) { - return FALSE; + $items['price'] = (float) $items['price']; } - // Is the quantity zero? If so we will remove the item from the cart. - // If the quantity is greater than zero we are updating - if ($items['qty'] == 0) + // product id & name shouldn't be changed + foreach (array_diff($keys, array('id', 'name')) as $key) { - unset($this->_cart_contents[$items['rowid']]); - } - else - { - $this->_cart_contents[$items['rowid']]['qty'] = $items['qty']; + $this->_cart_contents[$items['rowid']][$key] = $items[$key]; } return TRUE; @@ -363,38 +384,26 @@ class CI_Cart { /** * Save the cart array to the session DB * - * @access private * @return bool */ - function _save_cart() + protected function _save_cart() { - // Unset these so our total can be calculated correctly below - unset($this->_cart_contents['total_items']); - unset($this->_cart_contents['cart_total']); - - // Lets add up the individual prices and set the cart sub-total - $total = 0; - $items = 0; + // Let's add up the individual prices and set the cart sub-total + $this->_cart_contents['total_items'] = $this->_cart_contents['cart_total'] = 0; foreach ($this->_cart_contents as $key => $val) { // We make sure the array contains the proper indexes - if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty'])) + if ( ! is_array($val) OR ! isset($val['price'], $val['qty'])) { continue; } - $total += ($val['price'] * $val['qty']); - $items += $val['qty']; - - // Set the subtotal + $this->_cart_contents['cart_total'] += ($val['price'] * $val['qty']); + $this->_cart_contents['total_items'] += $val['qty']; $this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']); } - // Set the cart total and total items. - $this->_cart_contents['total_items'] = $items; - $this->_cart_contents['cart_total'] = $total; - - // Is our cart empty? If so we delete it from the session + // Is our cart empty? If so we delete it from the session if (count($this->_cart_contents) <= 2) { $this->CI->session->unset_userdata('cart_contents'); @@ -416,25 +425,41 @@ class CI_Cart { /** * Cart Total * - * @access public - * @return integer + * @return int */ - function total() + public function total() { return $this->_cart_contents['cart_total']; } // -------------------------------------------------------------------- + /** + * Remove Item + * + * Removes an item from the cart + * + * @param int + * @return bool + */ + public function remove($rowid) + { + // unset & save + unset($this->_cart_contents[$rowid]); + $this->_save_cart(); + return TRUE; + } + + // -------------------------------------------------------------------- + /** * Total Items * * Returns the total item count * - * @access public - * @return integer + * @return int */ - function total_items() + public function total_items() { return $this->_cart_contents['total_items']; } @@ -446,12 +471,13 @@ class CI_Cart { * * Returns the entire cart array * - * @access public + * @param bool * @return array */ - function contents() + public function contents($newest_first = FALSE) { - $cart = $this->_cart_contents; + // do we want the newest first? + $cart = ($newest_first) ? array_reverse($this->_cart_contents) : $this->_cart_contents; // Remove these so they don't create a problem when showing the cart table unset($cart['total_items']); @@ -462,23 +488,35 @@ class CI_Cart { // -------------------------------------------------------------------- + /** + * Get cart item + * + * Returns the details of a specific item in the cart + * + * @param string $row_id + * @return array + */ + public function get_item($row_id) + { + return (in_array($row_id, array('total_items', 'cart_total'), TRUE) OR ! isset($this->_cart_contents[$row_id])) + ? FALSE + : $this->_cart_contents[$row_id]; + } + + // -------------------------------------------------------------------- + /** * Has options * * Returns TRUE if the rowid passed to this function correlates to an item * that has options associated with it. * - * @access public - * @return array + * @param string $row_id = '' + * @return bool */ - function has_options($rowid = '') + public function has_options($row_id = '') { - if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0) - { - return FALSE; - } - - return TRUE; + return (isset($this->_cart_contents[$row_id]['options']) && count($this->_cart_contents[$row_id]['options']) !== 0); } // -------------------------------------------------------------------- @@ -488,17 +526,12 @@ class CI_Cart { * * Returns the an array of options, for a particular product row ID * - * @access public + * @param string $row_id = '' * @return array */ - function product_options($rowid = '') + public function product_options($row_id = '') { - if ( ! isset($this->_cart_contents[$rowid]['options'])) - { - return array(); - } - - return $this->_cart_contents[$rowid]['options']; + return isset($this->_cart_contents[$row_id]['options']) ? $this->_cart_contents[$row_id]['options'] : array(); } // -------------------------------------------------------------------- @@ -508,20 +541,12 @@ class CI_Cart { * * Returns the supplied number with commas and a decimal point. * - * @access public - * @return integer + * @param float + * @return string */ - function format_number($n = '') + public function format_number($n = '') { - if ($n == '') - { - return ''; - } - - // Remove anything that isn't a number or decimal point. - $n = trim(preg_replace('/([^0-9\.])/i', '', $n)); - - return number_format($n, 2, '.', ','); + return ($n === '') ? '' : number_format( (float) $n, 2, '.', ','); } // -------------------------------------------------------------------- @@ -531,21 +556,12 @@ class CI_Cart { * * Empties the cart and kills the session * - * @access public - * @return null + * @return void */ - function destroy() + public function destroy() { - unset($this->_cart_contents); - - $this->_cart_contents['cart_total'] = 0; - $this->_cart_contents['total_items'] = 0; - + $this->_cart_contents = array('cart_total' => 0, 'total_items' => 0); $this->CI->session->unset_userdata('cart_contents'); } - } - -/* End of file Cart.php */ -/* Location: ./system/libraries/Cart.php */ \ No newline at end of file diff --git a/system/libraries/Driver.php b/system/libraries/Driver.php old mode 100755 new mode 100644 index 9ae7b0c..7e6cf4f --- a/system/libraries/Driver.php +++ b/system/libraries/Driver.php @@ -1,19 +1,41 @@ -lib_name)) - { - $this->lib_name = get_class($this); - } - - // The class will be prefixed with the parent lib - $child_class = $this->lib_name.'_'.$child; - - // Remove the CI_ prefix and lowercase - $lib_name = ucfirst(strtolower(str_replace('CI_', '', $this->lib_name))); - $driver_name = strtolower(str_replace('CI_', '', $child_class)); - - if (in_array($driver_name, array_map('strtolower', $this->valid_drivers))) - { - // check and see if the driver is in a separate file - if ( ! class_exists($child_class)) - { - // check application path first - foreach (get_instance()->load->get_package_paths(TRUE) as $path) - { - // loves me some nesting! - foreach (array(ucfirst($driver_name), $driver_name) as $class) - { - $filepath = $path.'libraries/'.$lib_name.'/drivers/'.$class.'.php'; - - if (file_exists($filepath)) - { - include_once $filepath; - break; - } - } - } - - // it's a valid driver, but the file simply can't be found - if ( ! class_exists($child_class)) - { - log_message('error', "Unable to load the requested driver: ".$child_class); - show_error("Unable to load the requested driver: ".$child_class); - } - } - - $obj = new $child_class; - $obj->decorate($this); - $this->$child = $obj; - return $this->$child; - } - - // The requested driver isn't valid! - log_message('error', "Invalid driver requested: ".$child_class); - show_error("Invalid driver requested: ".$child_class); + // Try to load the driver + return $this->load_driver($child); } - // -------------------------------------------------------------------- + /** + * Load driver + * + * Separate load_driver call to support explicit driver load by library or user + * + * @param string Driver name (w/o parent prefix) + * @return object Child class + */ + public function load_driver($child) + { + // Get CodeIgniter instance and subclass prefix + $prefix = config_item('subclass_prefix'); + + if ( ! isset($this->lib_name)) + { + // Get library name without any prefix + $this->lib_name = str_replace(array('CI_', $prefix), '', get_class($this)); + } + + // The child will be prefixed with the parent lib + $child_name = $this->lib_name.'_'.$child; + + // See if requested child is a valid driver + if ( ! in_array($child, $this->valid_drivers)) + { + // The requested driver isn't valid! + $msg = 'Invalid driver requested: '.$child_name; + log_message('error', $msg); + show_error($msg); + } + + // Get package paths and filename case variations to search + $CI = get_instance(); + $paths = $CI->load->get_package_paths(TRUE); + + // Is there an extension? + $class_name = $prefix.$child_name; + $found = class_exists($class_name, FALSE); + if ( ! $found) + { + // Check for subclass file + foreach ($paths as $path) + { + // Does the file exist? + $file = $path.'libraries/'.$this->lib_name.'/drivers/'.$prefix.$child_name.'.php'; + if (file_exists($file)) + { + // Yes - require base class from BASEPATH + $basepath = BASEPATH.'libraries/'.$this->lib_name.'/drivers/'.$child_name.'.php'; + if ( ! file_exists($basepath)) + { + $msg = 'Unable to load the requested class: CI_'.$child_name; + log_message('error', $msg); + show_error($msg); + } + + // Include both sources and mark found + include_once($basepath); + include_once($file); + $found = TRUE; + break; + } + } + } + + // Do we need to search for the class? + if ( ! $found) + { + // Use standard class name + $class_name = 'CI_'.$child_name; + if ( ! class_exists($class_name, FALSE)) + { + // Check package paths + foreach ($paths as $path) + { + // Does the file exist? + $file = $path.'libraries/'.$this->lib_name.'/drivers/'.$child_name.'.php'; + if (file_exists($file)) + { + // Include source + include_once($file); + break; + } + } + } + } + + // Did we finally find the class? + if ( ! class_exists($class_name, FALSE)) + { + if (class_exists($child_name, FALSE)) + { + $class_name = $child_name; + } + else + { + $msg = 'Unable to load the requested driver: '.$class_name; + log_message('error', $msg); + show_error($msg); + } + } + + // Instantiate, decorate and add child + $obj = new $class_name(); + $obj->decorate($this); + $this->$child = $obj; + return $this->$child; + } } -// END CI_Driver_Library CLASS +// -------------------------------------------------------------------------- /** * CodeIgniter Driver Class @@ -107,12 +206,35 @@ class CI_Driver_Library { * @link */ class CI_Driver { - protected $parent; - private $methods = array(); - private $properties = array(); + /** + * Instance of the parent class + * + * @var object + */ + protected $_parent; - private static $reflections = array(); + /** + * List of methods in the parent class + * + * @var array + */ + protected $_methods = array(); + + /** + * List of properties in the parent class + * + * @var array + */ + protected $_properties = array(); + + /** + * Array of methods and properties for the parent class(es) + * + * @static + * @var array + */ + protected static $_reflections = array(); /** * Decorate @@ -124,14 +246,14 @@ class CI_Driver { */ public function decorate($parent) { - $this->parent = $parent; + $this->_parent = $parent; // Lock down attributes to what is defined in the class // and speed up references in magic methods $class_name = get_class($parent); - if ( ! isset(self::$reflections[$class_name])) + if ( ! isset(self::$_reflections[$class_name])) { $r = new ReflectionObject($parent); @@ -139,7 +261,7 @@ class CI_Driver { { if ($method->isPublic()) { - $this->methods[] = $method->getName(); + $this->_methods[] = $method->getName(); } } @@ -147,15 +269,15 @@ class CI_Driver { { if ($prop->isPublic()) { - $this->properties[] = $prop->getName(); + $this->_properties[] = $prop->getName(); } } - self::$reflections[$class_name] = array($this->methods, $this->properties); + self::$_reflections[$class_name] = array($this->_methods, $this->_properties); } else { - list($this->methods, $this->properties) = self::$reflections[$class_name]; + list($this->_methods, $this->_properties) = self::$_reflections[$class_name]; } } @@ -166,21 +288,18 @@ class CI_Driver { * * Handles access to the parent driver library's methods * - * @access public * @param string * @param array * @return mixed */ public function __call($method, $args = array()) { - if (in_array($method, $this->methods)) + if (in_array($method, $this->_methods)) { - return call_user_func_array(array($this->parent, $method), $args); + return call_user_func_array(array($this->_parent, $method), $args); } - $trace = debug_backtrace(); - _exception_handler(E_ERROR, "No such method '{$method}'", $trace[1]['file'], $trace[1]['line']); - exit; + throw new BadMethodCallException('No such method: '.$method.'()'); } // -------------------------------------------------------------------- @@ -195,9 +314,9 @@ class CI_Driver { */ public function __get($var) { - if (in_array($var, $this->properties)) + if (in_array($var, $this->_properties)) { - return $this->parent->$var; + return $this->_parent->$var; } } @@ -214,14 +333,10 @@ class CI_Driver { */ public function __set($var, $val) { - if (in_array($var, $this->properties)) + if (in_array($var, $this->_properties)) { - $this->parent->$var = $val; + $this->_parent->$var = $val; } } } -// END CI_Driver CLASS - -/* End of file Driver.php */ -/* Location: ./system/libraries/Driver.php */ \ No newline at end of file diff --git a/system/libraries/Email.php b/system/libraries/Email.php old mode 100755 new mode 100644 index 10cbc34..10b7477 --- a/system/libraries/Email.php +++ b/system/libraries/Email.php @@ -1,19 +1,41 @@ - '1 (Highest)', + 2 => '2 (High)', + 3 => '3 (Normal)', + 4 => '4 (Low)', + 5 => '5 (Lowest)' + ); + + /** + * mbstring.func_overload flag + * + * @var bool + */ + protected static $func_overload; + + // -------------------------------------------------------------------- /** * Constructor - Sets Email Preferences * * The constructor can be passed an array of config values + * + * @param array $config = array() + * @return void */ - public function __construct($config = array()) + public function __construct(array $config = array()) { - if (count($config) > 0) - { - $this->initialize($config); - } - else - { - $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE; - $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE; - } + $this->charset = config_item('charset'); + $this->initialize($config); + $this->_safe_mode = ( ! is_php('5.4') && ini_get('safe_mode')); - log_message('debug', "Email Class Initialized"); + isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload')); + + log_message('info', 'Email Class Initialized'); } // -------------------------------------------------------------------- @@ -103,12 +407,13 @@ class CI_Email { /** * Initialize preferences * - * @access public - * @param array - * @return void + * @param array $config + * @return CI_Email */ - public function initialize($config = array()) + public function initialize(array $config = array()) { + $this->clear(); + foreach ($config as $key => $val) { if (isset($this->$key)) @@ -125,10 +430,9 @@ class CI_Email { } } } - $this->clear(); - $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE; - $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE; + $this->charset = strtoupper($this->charset); + $this->_smtp_auth = isset($this->smtp_user[0], $this->smtp_pass[0]); return $this; } @@ -138,30 +442,27 @@ class CI_Email { /** * Initialize the Email Data * - * @access public - * @return void + * @param bool + * @return CI_Email */ public function clear($clear_attachments = FALSE) { - $this->_subject = ""; - $this->_body = ""; - $this->_finalbody = ""; - $this->_header_str = ""; - $this->_replyto_flag = FALSE; + $this->_subject = ''; + $this->_body = ''; + $this->_finalbody = ''; + $this->_header_str = ''; + $this->_replyto_flag = FALSE; $this->_recipients = array(); $this->_cc_array = array(); $this->_bcc_array = array(); $this->_headers = array(); $this->_debug_msg = array(); - $this->_set_header('User-Agent', $this->useragent); - $this->_set_header('Date', $this->_set_date()); + $this->set_header('Date', $this->_set_date()); if ($clear_attachments !== FALSE) { - $this->_attach_name = array(); - $this->_attach_type = array(); - $this->_attach_disp = array(); + $this->_attachments = array(); } return $this; @@ -172,25 +473,29 @@ class CI_Email { /** * Set FROM * - * @access public - * @param string - * @param string - * @return void + * @param string $from + * @param string $name + * @param string $return_path = NULL Return-Path + * @return CI_Email */ - public function from($from, $name = '') + public function from($from, $name = '', $return_path = NULL) { - if (preg_match( '/\<(.*)\>/', $from, $match)) + if (preg_match('/\<(.*)\>/', $from, $match)) { - $from = $match['1']; + $from = $match[1]; } if ($this->validate) { $this->validate_email($this->_str_to_array($from)); + if ($return_path) + { + $this->validate_email($this->_str_to_array($return_path)); + } } // prepare the display name - if ($name != '') + if ($name !== '') { // only use Q encoding if there are characters that would require it if ( ! preg_match('/[\200-\377]/', $name)) @@ -200,12 +505,14 @@ class CI_Email { } else { - $name = $this->_prep_q_encoding($name, TRUE); + $name = $this->_prep_q_encoding($name); } } - $this->_set_header('From', $name.' <'.$from.'>'); - $this->_set_header('Return-Path', '<'.$from.'>'); + $this->set_header('From', $name.' <'.$from.'>'); + + isset($return_path) OR $return_path = $from; + $this->set_header('Return-Path', '<'.$return_path.'>'); return $this; } @@ -215,16 +522,15 @@ class CI_Email { /** * Set Reply-to * - * @access public * @param string * @param string - * @return void + * @return CI_Email */ public function reply_to($replyto, $name = '') { - if (preg_match( '/\<(.*)\>/', $replyto, $match)) + if (preg_match('/\<(.*)\>/', $replyto, $match)) { - $replyto = $match['1']; + $replyto = $match[1]; } if ($this->validate) @@ -232,17 +538,21 @@ class CI_Email { $this->validate_email($this->_str_to_array($replyto)); } - if ($name == '') + if ($name !== '') { - $name = $replyto; + // only use Q encoding if there are characters that would require it + if ( ! preg_match('/[\200-\377]/', $name)) + { + // add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes + $name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"'; + } + else + { + $name = $this->_prep_q_encoding($name); + } } - if (strncmp($name, '"', 1) != 0) - { - $name = '"'.$name.'"'; - } - - $this->_set_header('Reply-To', $name.' <'.$replyto.'>'); + $this->set_header('Reply-To', $name.' <'.$replyto.'>'); $this->_replyto_flag = TRUE; return $this; @@ -253,9 +563,8 @@ class CI_Email { /** * Set Recipients * - * @access public * @param string - * @return void + * @return CI_Email */ public function to($to) { @@ -267,21 +576,12 @@ class CI_Email { $this->validate_email($to); } - if ($this->_get_protocol() != 'mail') + if ($this->_get_protocol() !== 'mail') { - $this->_set_header('To', implode(", ", $to)); + $this->set_header('To', implode(', ', $to)); } - switch ($this->_get_protocol()) - { - case 'smtp' : - $this->_recipients = $to; - break; - case 'sendmail' : - case 'mail' : - $this->_recipients = implode(", ", $to); - break; - } + $this->_recipients = $to; return $this; } @@ -291,23 +591,21 @@ class CI_Email { /** * Set CC * - * @access public * @param string - * @return void + * @return CI_Email */ public function cc($cc) { - $cc = $this->_str_to_array($cc); - $cc = $this->clean_email($cc); + $cc = $this->clean_email($this->_str_to_array($cc)); if ($this->validate) { $this->validate_email($cc); } - $this->_set_header('Cc', implode(", ", $cc)); + $this->set_header('Cc', implode(', ', $cc)); - if ($this->_get_protocol() == "smtp") + if ($this->_get_protocol() === 'smtp') { $this->_cc_array = $cc; } @@ -320,34 +618,32 @@ class CI_Email { /** * Set BCC * - * @access public * @param string * @param string - * @return void + * @return CI_Email */ public function bcc($bcc, $limit = '') { - if ($limit != '' && is_numeric($limit)) + if ($limit !== '' && is_numeric($limit)) { $this->bcc_batch_mode = TRUE; $this->bcc_batch_size = $limit; } - $bcc = $this->_str_to_array($bcc); - $bcc = $this->clean_email($bcc); + $bcc = $this->clean_email($this->_str_to_array($bcc)); if ($this->validate) { $this->validate_email($bcc); } - if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size)) + if ($this->_get_protocol() === 'smtp' OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size)) { $this->_bcc_array = $bcc; } else { - $this->_set_header('Bcc', implode(", ", $bcc)); + $this->set_header('Bcc', implode(', ', $bcc)); } return $this; @@ -358,14 +654,13 @@ class CI_Email { /** * Set Email Subject * - * @access public * @param string - * @return void + * @return CI_Email */ public function subject($subject) { $subject = $this->_prep_q_encoding($subject); - $this->_set_header('Subject', $subject); + $this->set_header('Subject', $subject); return $this; } @@ -374,13 +669,12 @@ class CI_Email { /** * Set Body * - * @access public * @param string - * @return void + * @return CI_Email */ public function message($body) { - $this->_body = rtrim(str_replace("\r", "", $body)); + $this->_body = rtrim(str_replace("\r", '', $body)); /* strip slashes only if magic quotes is ON if we do it with magic quotes OFF, it strips real, user-inputted chars. @@ -401,31 +695,86 @@ class CI_Email { /** * Assign file attachments * - * @access public - * @param string - * @return void + * @param string $file Can be local path, URL or buffered content + * @param string $disposition = 'attachment' + * @param string $newname = NULL + * @param string $mime = '' + * @return CI_Email */ - public function attach($filename, $disposition = 'attachment') + public function attach($file, $disposition = '', $newname = NULL, $mime = '') { - $this->_attach_name[] = $filename; - $this->_attach_type[] = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION)); - $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters + if ($mime === '') + { + if (strpos($file, '://') === FALSE && ! file_exists($file)) + { + $this->_set_error_message('lang:email_attachment_missing', $file); + return FALSE; + } + + if ( ! $fp = @fopen($file, 'rb')) + { + $this->_set_error_message('lang:email_attachment_unreadable', $file); + return FALSE; + } + + $file_content = stream_get_contents($fp); + $mime = $this->_mime_types(pathinfo($file, PATHINFO_EXTENSION)); + fclose($fp); + } + else + { + $file_content =& $file; // buffered file + } + + $this->_attachments[] = array( + 'name' => array($file, $newname), + 'disposition' => empty($disposition) ? 'attachment' : $disposition, // Can also be 'inline' Not sure if it matters + 'type' => $mime, + 'content' => chunk_split(base64_encode($file_content)), + 'multipart' => 'mixed' + ); + return $this; } // -------------------------------------------------------------------- + /** + * Set and return attachment Content-ID + * + * Useful for attached inline pictures + * + * @param string $filename + * @return string + */ + public function attachment_cid($filename) + { + for ($i = 0, $c = count($this->_attachments); $i < $c; $i++) + { + if ($this->_attachments[$i]['name'][0] === $filename) + { + $this->_attachments[$i]['multipart'] = 'related'; + $this->_attachments[$i]['cid'] = uniqid(basename($this->_attachments[$i]['name'][0]).'@'); + return $this->_attachments[$i]['cid']; + } + } + + return FALSE; + } + + // -------------------------------------------------------------------- + /** * Add a Header Item * - * @access protected * @param string * @param string - * @return void + * @return CI_Email */ - protected function _set_header($header, $value) + public function set_header($header, $value) { - $this->_headers[$header] = $value; + $this->_headers[$header] = str_replace(array("\n", "\r"), '', $value); + return $this; } // -------------------------------------------------------------------- @@ -433,7 +782,6 @@ class CI_Email { /** * Convert a String to an Array * - * @access protected * @param string * @return array */ @@ -441,16 +789,11 @@ class CI_Email { { if ( ! is_array($email)) { - if (strpos($email, ',') !== FALSE) - { - $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY); - } - else - { - $email = trim($email); - settype($email, "array"); - } + return (strpos($email, ',') !== FALSE) + ? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY) + : (array) trim($email); } + return $email; } @@ -459,13 +802,12 @@ class CI_Email { /** * Set Multipart Value * - * @access public * @param string - * @return void + * @return CI_Email */ - public function set_alt_message($str = '') + public function set_alt_message($str) { - $this->alt_message = $str; + $this->alt_message = (string) $str; return $this; } @@ -474,13 +816,12 @@ class CI_Email { /** * Set Mailtype * - * @access public * @param string - * @return void + * @return CI_Email */ public function set_mailtype($type = 'text') { - $this->mailtype = ($type == 'html') ? 'html' : 'text'; + $this->mailtype = ($type === 'html') ? 'html' : 'text'; return $this; } @@ -489,13 +830,12 @@ class CI_Email { /** * Set Wordwrap * - * @access public - * @param string - * @return void + * @param bool + * @return CI_Email */ public function set_wordwrap($wordwrap = TRUE) { - $this->wordwrap = ($wordwrap === FALSE) ? FALSE : TRUE; + $this->wordwrap = (bool) $wordwrap; return $this; } @@ -504,13 +844,12 @@ class CI_Email { /** * Set Protocol * - * @access public * @param string - * @return void + * @return CI_Email */ public function set_protocol($protocol = 'mail') { - $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol); + $this->protocol = in_array($protocol, $this->_protocols, TRUE) ? strtolower($protocol) : 'mail'; return $this; } @@ -519,25 +858,12 @@ class CI_Email { /** * Set Priority * - * @access public - * @param integer - * @return void + * @param int + * @return CI_Email */ public function set_priority($n = 3) { - if ( ! is_numeric($n)) - { - $this->priority = 3; - return; - } - - if ($n < 1 OR $n > 5) - { - $this->priority = 3; - return; - } - - $this->priority = $n; + $this->priority = preg_match('/^[1-5]$/', $n) ? (int) $n : 3; return $this; } @@ -546,20 +872,12 @@ class CI_Email { /** * Set Newline Character * - * @access public * @param string - * @return void + * @return CI_Email */ public function set_newline($newline = "\n") { - if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r") - { - $this->newline = "\n"; - return; - } - - $this->newline = $newline; - + $this->newline = in_array($newline, array("\n", "\r\n", "\r")) ? $newline : "\n"; return $this; } @@ -568,52 +886,26 @@ class CI_Email { /** * Set CRLF * - * @access public * @param string - * @return void + * @return CI_Email */ public function set_crlf($crlf = "\n") { - if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r") - { - $this->crlf = "\n"; - return; - } - - $this->crlf = $crlf; - + $this->crlf = ($crlf !== "\n" && $crlf !== "\r\n" && $crlf !== "\r") ? "\n" : $crlf; return $this; } // -------------------------------------------------------------------- - /** - * Set Message Boundary - * - * @access protected - * @return void - */ - protected function _set_boundaries() - { - $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative - $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary - } - - // -------------------------------------------------------------------- - /** * Get the Message ID * - * @access protected * @return string */ protected function _get_message_id() { - $from = $this->_headers['Return-Path']; - $from = str_replace(">", "", $from); - $from = str_replace("<", "", $from); - - return "<".uniqid('').strstr($from, '@').">"; + $from = str_replace(array('>', '<'), '', $this->_headers['Return-Path']); + return '<'.uniqid('').strstr($from, '@').'>'; } // -------------------------------------------------------------------- @@ -621,19 +913,13 @@ class CI_Email { /** * Get Mail Protocol * - * @access protected - * @param bool - * @return string + * @return mixed */ - protected function _get_protocol($return = TRUE) + protected function _get_protocol() { $this->protocol = strtolower($this->protocol); - $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol; - - if ($return == TRUE) - { - return $this->protocol; - } + in_array($this->protocol, $this->_protocols, TRUE) OR $this->protocol = 'mail'; + return $this->protocol; } // -------------------------------------------------------------------- @@ -641,26 +927,21 @@ class CI_Email { /** * Get Mail Encoding * - * @access protected - * @param bool * @return string */ - protected function _get_encoding($return = TRUE) + protected function _get_encoding() { - $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding; + in_array($this->_encoding, $this->_bit_depths) OR $this->_encoding = '8bit'; foreach ($this->_base_charsets as $charset) { - if (strncmp($charset, $this->charset, strlen($charset)) == 0) + if (strpos($this->charset, $charset) === 0) { $this->_encoding = '7bit'; } } - if ($return == TRUE) - { - return $this->_encoding; - } + return $this->_encoding; } // -------------------------------------------------------------------- @@ -668,27 +949,20 @@ class CI_Email { /** * Get content type (text/html/attachment) * - * @access protected * @return string */ protected function _get_content_type() { - if ($this->mailtype == 'html' && count($this->_attach_name) == 0) + if ($this->mailtype === 'html') { - return 'html'; + return empty($this->_attachments) ? 'html' : 'html-attach'; } - elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0) - { - return 'html-attach'; - } - elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0) + elseif ($this->mailtype === 'text' && ! empty($this->_attachments)) { return 'plain-attach'; } - else - { - return 'plain'; - } + + return 'plain'; } // -------------------------------------------------------------------- @@ -696,17 +970,16 @@ class CI_Email { /** * Set RFC 822 Date * - * @access protected * @return string */ protected function _set_date() { - $timezone = date("Z"); - $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+'; + $timezone = date('Z'); + $operator = ($timezone[0] === '-') ? '-' : '+'; $timezone = abs($timezone); - $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60; + $timezone = floor($timezone/3600) * 100 + ($timezone % 3600) / 60; - return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone); + return sprintf('%s %s%04d', date('D, j M Y H:i:s'), $operator, $timezone); } // -------------------------------------------------------------------- @@ -714,12 +987,11 @@ class CI_Email { /** * Mime message * - * @access protected * @return string */ protected function _get_mime_message() { - return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format."; + return 'This is a multi-part message in MIME format.'.$this->newline.'Your email application may not support this format.'; } // -------------------------------------------------------------------- @@ -727,7 +999,6 @@ class CI_Email { /** * Validate Email Address * - * @access public * @param string * @return bool */ @@ -756,13 +1027,25 @@ class CI_Email { /** * Email Validation * - * @access public * @param string * @return bool */ - public function valid_email($address) + public function valid_email($email) { - return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE; + if (function_exists('idn_to_ascii') && strpos($email, '@')) + { + list($account, $domain) = explode('@', $email, 2); + $domain = defined('INTL_IDNA_VARIANT_UTS46') + ? idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) + : idn_to_ascii($domain); + + if ($domain !== FALSE) + { + $email = $account.'@'.$domain; + } + } + + return (bool) filter_var($email, FILTER_VALIDATE_EMAIL); } // -------------------------------------------------------------------- @@ -770,7 +1053,6 @@ class CI_Email { /** * Clean Extended Email Address: Joe Smith * - * @access public * @param string * @return string */ @@ -778,28 +1060,14 @@ class CI_Email { { if ( ! is_array($email)) { - if (preg_match('/\<(.*)\>/', $email, $match)) - { - return $match['1']; - } - else - { - return $email; - } + return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email; } $clean_email = array(); foreach ($email as $addy) { - if (preg_match( '/\<(.*)\>/', $addy, $match)) - { - $clean_email[] = $match['1']; - } - else - { - $clean_email[] = $addy; - } + $clean_email[] = preg_match('/\<(.*)\>/', $addy, $match) ? $match[1] : $addy; } return $clean_email; @@ -810,47 +1078,36 @@ class CI_Email { /** * Build alternative plain text message * - * This public function provides the raw message for use - * in plain-text headers of HTML-formatted emails. + * Provides the raw message for use in plain-text headers of + * HTML-formatted emails. * If the user hasn't specified his own alternative message * it creates one by stripping the HTML * - * @access protected * @return string */ protected function _get_alt_message() { - if ($this->alt_message != "") + if ( ! empty($this->alt_message)) { - return $this->word_wrap($this->alt_message, '76'); + return ($this->wordwrap) + ? $this->word_wrap($this->alt_message, 76) + : $this->alt_message; } - if (preg_match('/\(.*)\<\/body\>/si', $this->_body, $match)) - { - $body = $match['1']; - } - else - { - $body = $this->_body; - } - - $body = trim(strip_tags($body)); - $body = preg_replace( '# '.$msg."\n"; - - flock($fp, LOCK_EX); - fwrite($fp, $message); - flock($fp, LOCK_UN); - fclose($fp); - - @chmod($filepath, FILE_WRITE_MODE); - return TRUE; - } - -} -// END Log Class - -/* End of file Log.php */ -/* Location: ./system/libraries/Log.php */ \ No newline at end of file diff --git a/system/libraries/Migration.php b/system/libraries/Migration.php old mode 100755 new mode 100644 index 241ce1e..1b78089 --- a/system/libraries/Migration.php +++ b/system/libraries/Migration.php @@ -1,19 +1,41 @@ - $val) { - $this->{'_' . $key} = $val; + $this->{'_'.$key} = $val; } - log_message('debug', 'Migrations class initialized'); + log_message('info', 'Migrations Class Initialized'); // Are they trying to use migrations while it is disabled? if ($this->_migration_enabled !== TRUE) @@ -57,7 +135,7 @@ class CI_Migration { } // If not set, set it - $this->_migration_path == '' AND $this->_migration_path = APPPATH . 'migrations/'; + $this->_migration_path !== '' OR $this->_migration_path = APPPATH.'migrations/'; // Add trailing slash if not set $this->_migration_path = rtrim($this->_migration_path, '/').'/'; @@ -68,16 +146,39 @@ class CI_Migration { // They'll probably be using dbforge $this->load->dbforge(); + // Make sure the migration table name was set. + if (empty($this->_migration_table)) + { + show_error('Migrations configuration file (migration.php) must have "migration_table" set.'); + } + + // Migration basename regex + $this->_migration_regex = ($this->_migration_type === 'timestamp') + ? '/^\d{14}_(\w+)$/' + : '/^\d{3}_(\w+)$/'; + + // Make sure a valid migration numbering type was set. + if ( ! in_array($this->_migration_type, array('sequential', 'timestamp'))) + { + show_error('An invalid migration numbering type was specified: '.$this->_migration_type); + } + // If the migrations table is missing, make it - if ( ! $this->db->table_exists('migrations')) + if ( ! $this->db->table_exists($this->_migration_table)) { $this->dbforge->add_field(array( - 'version' => array('type' => 'INT', 'constraint' => 3), + 'version' => array('type' => 'BIGINT', 'constraint' => 20), )); - $this->dbforge->create_table('migrations', TRUE); + $this->dbforge->create_table($this->_migration_table, TRUE); - $this->db->insert('migrations', array('version' => 0)); + $this->db->insert($this->_migration_table, array('version' => 0)); + } + + // Do we auto migrate to the latest migration? + if ($this->_migration_auto_latest === TRUE && ! $this->latest()) + { + show_error($this->error_string()); } } @@ -89,154 +190,166 @@ class CI_Migration { * Calls each migration step required to get to the schema version of * choice * - * @param int Target schema version - * @return mixed TRUE if already latest, FALSE if failed, int if upgraded + * @param string $target_version Target schema version + * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure */ public function version($target_version) { - $start = $current_version = $this->_get_version(); - $stop = $target_version; + // Note: We use strings, so that timestamp versions work on 32-bit systems + $current_version = $this->_get_version(); - if ($target_version > $current_version) + if ($this->_migration_type === 'sequential') { - // Moving Up - ++$start; - ++$stop; - $step = 1; + $target_version = sprintf('%03d', $target_version); } else { - // Moving Down - $step = -1; + $target_version = (string) $target_version; } - $method = ($step === 1) ? 'up' : 'down'; - $migrations = array(); + $migrations = $this->find_migrations(); - // We now prepare to actually DO the migrations - // But first let's make sure that everything is the way it should be - for ($i = $start; $i != $stop; $i += $step) + if ($target_version > 0 && ! isset($migrations[$target_version])) { - $f = glob(sprintf($this->_migration_path . '%03d_*.php', $i)); - - // Only one migration per step is permitted - if (count($f) > 1) - { - $this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $i); - return FALSE; - } - - // Migration step not found - if (count($f) == 0) - { - // If trying to migrate up to a version greater than the last - // existing one, migrate to the last one. - if ($step == 1) - { - break; - } - - // If trying to migrate down but we're missing a step, - // something must definitely be wrong. - $this->_error_string = sprintf($this->lang->line('migration_not_found'), $i); - return FALSE; - } - - $file = basename($f[0]); - $name = basename($f[0], '.php'); - - // Filename validations - if (preg_match('/^\d{3}_(\w+)$/', $name, $match)) - { - $match[1] = strtolower($match[1]); - - // Cannot repeat a migration at different steps - if (in_array($match[1], $migrations)) - { - $this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $match[1]); - return FALSE; - } - - include $f[0]; - $class = 'Migration_' . ucfirst($match[1]); - - if ( ! class_exists($class)) - { - $this->_error_string = sprintf($this->lang->line('migration_class_doesnt_exist'), $class); - return FALSE; - } - - if ( ! is_callable(array($class, $method))) - { - $this->_error_string = sprintf($this->lang->line('migration_missing_'.$method.'_method'), $class); - return FALSE; - } - - $migrations[] = $match[1]; - } - else - { - $this->_error_string = sprintf($this->lang->line('migration_invalid_filename'), $file); - return FALSE; - } + $this->_error_string = sprintf($this->lang->line('migration_not_found'), $target_version); + return FALSE; } - log_message('debug', 'Current migration: ' . $current_version); - - $version = $i + ($step == 1 ? -1 : 0); - - // If there is nothing to do so quit - if ($migrations === array()) + if ($target_version > $current_version) { + $method = 'up'; + } + elseif ($target_version < $current_version) + { + $method = 'down'; + // We need this so that migrations are applied in reverse order + krsort($migrations); + } + else + { + // Well, there's nothing to migrate then ... return TRUE; } - log_message('debug', 'Migrating from ' . $method . ' to version ' . $version); - - // Loop through the migrations - foreach ($migrations AS $migration) + // Validate all available migrations within our target range. + // + // Unfortunately, we'll have to use another loop to run them + // in order to avoid leaving the procedure in a broken state. + // + // See https://github.com/bcit-ci/CodeIgniter/issues/4539 + $pending = array(); + foreach ($migrations as $number => $file) { - // Run the migration class - $class = 'Migration_' . ucfirst(strtolower($migration)); - call_user_func(array(new $class, $method)); + // Ignore versions out of our range. + // + // Because we've previously sorted the $migrations array depending on the direction, + // we can safely break the loop once we reach $target_version ... + if ($method === 'up') + { + if ($number <= $current_version) + { + continue; + } + elseif ($number > $target_version) + { + break; + } + } + else + { + if ($number > $current_version) + { + continue; + } + elseif ($number <= $target_version) + { + break; + } + } - $current_version += $step; + // Check for sequence gaps + if ($this->_migration_type === 'sequential') + { + if (isset($previous) && abs($number - $previous) > 1) + { + $this->_error_string = sprintf($this->lang->line('migration_sequence_gap'), $number); + return FALSE; + } + + $previous = $number; + } + + include_once($file); + $class = 'Migration_'.ucfirst(strtolower($this->_get_migration_name(basename($file, '.php')))); + + // Validate the migration file structure + if ( ! class_exists($class, FALSE)) + { + $this->_error_string = sprintf($this->lang->line('migration_class_doesnt_exist'), $class); + return FALSE; + } + elseif ( ! is_callable(array($class, $method))) + { + $this->_error_string = sprintf($this->lang->line('migration_missing_'.$method.'_method'), $class); + return FALSE; + } + + $pending[$number] = array($class, $method); + } + + // Now just run the necessary migrations + foreach ($pending as $number => $migration) + { + log_message('debug', 'Migrating '.$method.' from version '.$current_version.' to version '.$number); + + $migration[0] = new $migration[0]; + call_user_func($migration); + $current_version = $number; + $this->_update_version($current_version); + } + + // This is necessary when moving down, since the the last migration applied + // will be the down() method for the next migration up from the target + if ($current_version <> $target_version) + { + $current_version = $target_version; $this->_update_version($current_version); } log_message('debug', 'Finished migrating to '.$current_version); - return $current_version; } // -------------------------------------------------------------------- /** - * Set's the schema to the latest migration + * Sets the schema to the latest migration * - * @return mixed true if already latest, false if failed, int if upgraded + * @return mixed Current version string on success, FALSE on failure */ public function latest() { - if ( ! $migrations = $this->find_migrations()) + $migrations = $this->find_migrations(); + + if (empty($migrations)) { $this->_error_string = $this->lang->line('migration_none_found'); - return false; + return FALSE; } $last_migration = basename(end($migrations)); // Calculate the last migration step from existing migration - // filenames and procceed to the standard version migration - return $this->version((int) substr($last_migration, 0, 3)); + // filenames and proceed to the standard version migration + return $this->version($this->_get_migration_number($last_migration)); } // -------------------------------------------------------------------- /** - * Set's the schema to the migration version set in config + * Sets the schema to the migration version set in config * - * @return mixed true if already current, false if failed, int if upgraded + * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure */ public function current() { @@ -258,28 +371,66 @@ class CI_Migration { // -------------------------------------------------------------------- /** - * Set's the schema to the latest migration + * Retrieves list of available migration scripts * - * @return mixed true if already latest, false if failed, int if upgraded + * @return array list of migration file paths sorted by version */ - protected function find_migrations() + public function find_migrations() { - // Load all *_*.php files in the migrations path - $files = glob($this->_migration_path . '*_*.php'); - $file_count = count($files); + $migrations = array(); - for ($i = 0; $i < $file_count; $i++) + // Load all *_*.php files in the migrations path + foreach (glob($this->_migration_path.'*_*.php') as $file) { - // Mark wrongly formatted files as false for later filtering - $name = basename($files[$i], '.php'); - if ( ! preg_match('/^\d{3}_(\w+)$/', $name)) + $name = basename($file, '.php'); + + // Filter out non-migration files + if (preg_match($this->_migration_regex, $name)) { - $files[$i] = FALSE; + $number = $this->_get_migration_number($name); + + // There cannot be duplicate migration numbers + if (isset($migrations[$number])) + { + $this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $number); + show_error($this->_error_string); + } + + $migrations[$number] = $file; } } - sort($files); - return $files; + ksort($migrations); + return $migrations; + } + + // -------------------------------------------------------------------- + + /** + * Extracts the migration number from a filename + * + * @param string $migration + * @return string Numeric portion of a migration filename + */ + protected function _get_migration_number($migration) + { + return sscanf($migration, '%[0-9]+', $number) + ? $number : '0'; + } + + // -------------------------------------------------------------------- + + /** + * Extracts the migration class name from a filename + * + * @param string $migration + * @return string text portion of a migration filename + */ + protected function _get_migration_name($migration) + { + $parts = explode('_', $migration); + array_shift($parts); + return implode('_', $parts); } // -------------------------------------------------------------------- @@ -287,12 +438,12 @@ class CI_Migration { /** * Retrieves current schema version * - * @return int Current Migration + * @return string Current migration version */ protected function _get_version() { - $row = $this->db->get('migrations')->row(); - return $row ? $row->version : 0; + $row = $this->db->select('version')->get($this->_migration_table)->row(); + return $row ? $row->version : '0'; } // -------------------------------------------------------------------- @@ -300,13 +451,13 @@ class CI_Migration { /** * Stores the current schema version * - * @param int Migration reached - * @return bool + * @param string $migration Migration reached + * @return void */ - protected function _update_version($migrations) + protected function _update_version($migration) { - return $this->db->update('migrations', array( - 'version' => $migrations + $this->db->update($this->_migration_table, array( + 'version' => $migration )); } @@ -315,7 +466,7 @@ class CI_Migration { /** * Enable the use of CI super-global * - * @param mixed $var + * @param string $var * @return mixed */ public function __get($var) @@ -324,6 +475,3 @@ class CI_Migration { } } - -/* End of file Migration.php */ -/* Location: ./system/libraries/Migration.php */ \ No newline at end of file diff --git a/system/libraries/Pagination.php b/system/libraries/Pagination.php old mode 100755 new mode 100644 index 8b3aa87..5d501a9 --- a/system/libraries/Pagination.php +++ b/system/libraries/Pagination.php @@ -1,19 +1,41 @@ -'; - var $cur_tag_close = ''; - var $next_tag_open = ' '; - var $next_tag_close = ' '; - var $prev_tag_open = ' '; - var $prev_tag_close = ''; - var $num_tag_open = ' '; - var $num_tag_close = ''; - var $page_query_string = FALSE; - var $query_string_segment = 'per_page'; - var $display_pages = TRUE; - var $anchor_class = ''; + /** + * Prefix + * + * @var string + */ + protected $prefix = ''; + + /** + * Suffix + * + * @var string + */ + protected $suffix = ''; + + /** + * Total number of items + * + * @var int + */ + protected $total_rows = 0; + + /** + * Number of links to show + * + * Relates to "digit" type links shown before/after + * the currently viewed page. + * + * @var int + */ + protected $num_links = 2; + + /** + * Items per page + * + * @var int + */ + public $per_page = 10; + + /** + * Current page + * + * @var int + */ + public $cur_page = 0; + + /** + * Use page numbers flag + * + * Whether to use actual page numbers instead of an offset + * + * @var bool + */ + protected $use_page_numbers = FALSE; + + /** + * First link + * + * @var string + */ + protected $first_link = '‹ First'; + + /** + * Next link + * + * @var string + */ + protected $next_link = '>'; + + /** + * Previous link + * + * @var string + */ + protected $prev_link = '<'; + + /** + * Last link + * + * @var string + */ + protected $last_link = 'Last ›'; + + /** + * URI Segment + * + * @var int + */ + protected $uri_segment = 0; + + /** + * Full tag open + * + * @var string + */ + protected $full_tag_open = ''; + + /** + * Full tag close + * + * @var string + */ + protected $full_tag_close = ''; + + /** + * First tag open + * + * @var string + */ + protected $first_tag_open = ''; + + /** + * First tag close + * + * @var string + */ + protected $first_tag_close = ''; + + /** + * Last tag open + * + * @var string + */ + protected $last_tag_open = ''; + + /** + * Last tag close + * + * @var string + */ + protected $last_tag_close = ''; + + /** + * First URL + * + * An alternative URL for the first page + * + * @var string + */ + protected $first_url = ''; + + /** + * Current tag open + * + * @var string + */ + protected $cur_tag_open = ''; + + /** + * Current tag close + * + * @var string + */ + protected $cur_tag_close = ''; + + /** + * Next tag open + * + * @var string + */ + protected $next_tag_open = ''; + + /** + * Next tag close + * + * @var string + */ + protected $next_tag_close = ''; + + /** + * Previous tag open + * + * @var string + */ + protected $prev_tag_open = ''; + + /** + * Previous tag close + * + * @var string + */ + protected $prev_tag_close = ''; + + /** + * Number tag open + * + * @var string + */ + protected $num_tag_open = ''; + + /** + * Number tag close + * + * @var string + */ + protected $num_tag_close = ''; + + /** + * Page query string flag + * + * @var bool + */ + protected $page_query_string = FALSE; + + /** + * Query string segment + * + * @var string + */ + protected $query_string_segment = 'per_page'; + + /** + * Display pages flag + * + * @var bool + */ + protected $display_pages = TRUE; + + /** + * Attributes + * + * @var string + */ + protected $_attributes = ''; + + /** + * Link types + * + * "rel" attribute + * + * @see CI_Pagination::_attr_rel() + * @var array + */ + protected $_link_types = array(); + + /** + * Reuse query string flag + * + * @var bool + */ + protected $reuse_query_string = FALSE; + + /** + * Use global URL suffix flag + * + * @var bool + */ + protected $use_global_url_suffix = FALSE; + + /** + * Data page attribute + * + * @var string + */ + protected $data_page_attr = 'data-ci-pagination-page'; + + /** + * CI Singleton + * + * @var object + */ + protected $CI; + + // -------------------------------------------------------------------- /** * Constructor * - * @access public - * @param array initialization parameters + * @param array $params Initialization parameters + * @return void */ public function __construct($params = array()) { - if (count($params) > 0) + $this->CI =& get_instance(); + $this->CI->load->language('pagination'); + foreach (array('first_link', 'next_link', 'prev_link', 'last_link') as $key) { - $this->initialize($params); + if (($val = $this->CI->lang->line('pagination_'.$key)) !== FALSE) + { + $this->$key = $val; + } } - if ($this->anchor_class != '') - { - $this->anchor_class = 'class="'.$this->anchor_class.'" '; - } + // _parse_attributes(), called by initialize(), needs to run at least once + // in order to enable "rel" attributes, and this triggers it. + isset($params['attributes']) OR $params['attributes'] = array(); - log_message('debug', "Pagination Class Initialized"); + $this->initialize($params); + log_message('info', 'Pagination Class Initialized'); } // -------------------------------------------------------------------- @@ -86,22 +352,44 @@ class CI_Pagination { /** * Initialize Preferences * - * @access public - * @param array initialization parameters - * @return void + * @param array $params Initialization parameters + * @return CI_Pagination */ - function initialize($params = array()) + public function initialize(array $params = array()) { - if (count($params) > 0) + if (isset($params['attributes']) && is_array($params['attributes'])) { - foreach ($params as $key => $val) + $this->_parse_attributes($params['attributes']); + unset($params['attributes']); + } + + // Deprecated legacy support for the anchor_class option + // Should be removed in CI 3.1+ + if (isset($params['anchor_class'])) + { + empty($params['anchor_class']) OR $attributes['class'] = $params['anchor_class']; + unset($params['anchor_class']); + } + + foreach ($params as $key => $val) + { + if (property_exists($this, $key)) { - if (isset($this->$key)) - { - $this->$key = $val; - } + $this->$key = $val; } } + + if ($this->CI->config->item('enable_query_strings') === TRUE) + { + $this->page_query_string = TRUE; + } + + if ($this->use_global_url_suffix === TRUE) + { + $this->suffix = $this->CI->config->item('url_suffix'); + } + + return $this; } // -------------------------------------------------------------------- @@ -109,80 +397,143 @@ class CI_Pagination { /** * Generate the pagination links * - * @access public * @return string */ - function create_links() + public function create_links() { // If our item count or per-page total is zero there is no need to continue. + // Note: DO NOT change the operator to === here! if ($this->total_rows == 0 OR $this->per_page == 0) { return ''; } // Calculate the total number of pages - $num_pages = ceil($this->total_rows / $this->per_page); + $num_pages = (int) ceil($this->total_rows / $this->per_page); // Is there only one page? Hm... nothing more to do here then. - if ($num_pages == 1) + if ($num_pages === 1) { return ''; } - // Set the base page index for starting page number - if ($this->use_page_numbers) + // Check the user defined number of links. + $this->num_links = (int) $this->num_links; + + if ($this->num_links < 0) { - $base_page = 1; + show_error('Your number of links must be a non-negative number.'); + } + + // Keep any existing query string items. + // Note: Has nothing to do with any other query string option. + if ($this->reuse_query_string === TRUE) + { + $get = $this->CI->input->get(); + + // Unset the control, method, old-school routing options + unset($get['c'], $get['m'], $get[$this->query_string_segment]); } else { - $base_page = 0; + $get = array(); + } + + // Put together our base and first URLs. + // Note: DO NOT append to the properties as that would break successive calls + $base_url = trim($this->base_url); + $first_url = $this->first_url; + + $query_string = ''; + $query_string_sep = (strpos($base_url, '?') === FALSE) ? '?' : '&'; + + // Are we using query strings? + if ($this->page_query_string === TRUE) + { + // If a custom first_url hasn't been specified, we'll create one from + // the base_url, but without the page item. + if ($first_url === '') + { + $first_url = $base_url; + + // If we saved any GET items earlier, make sure they're appended. + if ( ! empty($get)) + { + $first_url .= $query_string_sep.http_build_query($get); + } + } + + // Add the page segment to the end of the query string, where the + // page number will be appended. + $base_url .= $query_string_sep.http_build_query(array_merge($get, array($this->query_string_segment => ''))); + } + else + { + // Standard segment mode. + // Generate our saved query string to append later after the page number. + if ( ! empty($get)) + { + $query_string = $query_string_sep.http_build_query($get); + $this->suffix .= $query_string; + } + + // Does the base_url have the query string in it? + // If we're supposed to save it, remove it so we can append it later. + if ($this->reuse_query_string === TRUE && ($base_query_pos = strpos($base_url, '?')) !== FALSE) + { + $base_url = substr($base_url, 0, $base_query_pos); + } + + if ($first_url === '') + { + $first_url = $base_url.$query_string; + } + + $base_url = rtrim($base_url, '/').'/'; } // Determine the current page number. - $CI =& get_instance(); + $base_page = ($this->use_page_numbers) ? 1 : 0; - if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) + // Are we using query strings? + if ($this->page_query_string === TRUE) { - if ($CI->input->get($this->query_string_segment) != $base_page) + $this->cur_page = $this->CI->input->get($this->query_string_segment); + } + elseif (empty($this->cur_page)) + { + // Default to the last segment number if one hasn't been defined. + if ($this->uri_segment === 0) { - $this->cur_page = $CI->input->get($this->query_string_segment); + $this->uri_segment = count($this->CI->uri->segment_array()); + } - // Prep the current page - no funny business! - $this->cur_page = (int) $this->cur_page; + $this->cur_page = $this->CI->uri->segment($this->uri_segment); + + // Remove any specified prefix/suffix from the segment. + if ($this->prefix !== '' OR $this->suffix !== '') + { + $this->cur_page = str_replace(array($this->prefix, $this->suffix), '', $this->cur_page); } } else { - if ($CI->uri->segment($this->uri_segment) != $base_page) - { - $this->cur_page = $CI->uri->segment($this->uri_segment); - - // Prep the current page - no funny business! - $this->cur_page = (int) $this->cur_page; - } + $this->cur_page = (string) $this->cur_page; } - - // Set current page to 1 if using page numbers instead of offset - if ($this->use_page_numbers AND $this->cur_page == 0) + + // If something isn't quite right, back to the default base page. + if ( ! ctype_digit($this->cur_page) OR ($this->use_page_numbers && (int) $this->cur_page === 0)) { $this->cur_page = $base_page; } - - $this->num_links = (int)$this->num_links; - - if ($this->num_links < 1) + else { - show_error('Your number of links must be a positive number.'); - } - - if ( ! is_numeric($this->cur_page)) - { - $this->cur_page = $base_page; + // Make sure we're using integers for comparisons later. + $this->cur_page = (int) $this->cur_page; } // Is the page number beyond the result range? - // If so we show the last page + // If so, we show the last page. if ($this->use_page_numbers) { if ($this->cur_page > $num_pages) @@ -190,67 +541,56 @@ class CI_Pagination { $this->cur_page = $num_pages; } } - else + elseif ($this->cur_page > $this->total_rows) { - if ($this->cur_page > $this->total_rows) - { - $this->cur_page = ($num_pages - 1) * $this->per_page; - } + $this->cur_page = ($num_pages - 1) * $this->per_page; } $uri_page_number = $this->cur_page; - + + // If we're using offset instead of page numbers, convert it + // to a page number, so we can generate the surrounding number links. if ( ! $this->use_page_numbers) { - $this->cur_page = floor(($this->cur_page/$this->per_page) + 1); + $this->cur_page = (int) floor(($this->cur_page/$this->per_page) + 1); } // Calculate the start and end numbers. These determine - // which number to start and end the digit links with - $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1; - $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages; - - // Is pagination being used over GET or POST? If get, add a per_page query - // string. If post, add a trailing slash to the base URL if needed - if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) - { - $this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'='; - } - else - { - $this->base_url = rtrim($this->base_url, '/') .'/'; - } + // which number to start and end the digit links with. + $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1; + $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages; // And here we go... $output = ''; - // Render the "First" link - if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1)) + // Render the "First" link. + if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + ! $this->num_links)) { - $first_url = ($this->first_url == '') ? $this->base_url : $this->first_url; - $output .= $this->first_tag_open.'anchor_class.'href="'.$first_url.'">'.$this->first_link.''.$this->first_tag_close; + // Take the general parameters, and squeeze this pagination-page attr in for JS frameworks. + $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1); + + $output .= $this->first_tag_open.'_attr_rel('start').'>' + .$this->first_link.''.$this->first_tag_close; } - // Render the "previous" link - if ($this->prev_link !== FALSE AND $this->cur_page != 1) + // Render the "Previous" link. + if ($this->prev_link !== FALSE && $this->cur_page !== 1) { - if ($this->use_page_numbers) - { - $i = $uri_page_number - 1; - } - else - { - $i = $uri_page_number - $this->per_page; - } + $i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page; - if ($i == 0 && $this->first_url != '') + $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, ($this->cur_page - 1)); + + if ($i === $base_page) { - $output .= $this->prev_tag_open.'anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.''.$this->prev_tag_close; + // First page + $output .= $this->prev_tag_open.'_attr_rel('prev').'>' + .$this->prev_link.''.$this->prev_tag_close; } else { - $i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix; - $output .= $this->prev_tag_open.'anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.''.$this->prev_tag_close; + $append = $this->prefix.$i.$this->suffix; + $output .= $this->prev_tag_open.'_attr_rel('prev').'>' + .$this->prev_link.''.$this->prev_tag_close; } } @@ -259,82 +599,106 @@ class CI_Pagination { if ($this->display_pages !== FALSE) { // Write the digit links - for ($loop = $start -1; $loop <= $end; $loop++) + for ($loop = $start - 1; $loop <= $end; $loop++) { - if ($this->use_page_numbers) - { - $i = $loop; - } - else - { - $i = ($loop * $this->per_page) - $this->per_page; - } + $i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page; + + $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop); if ($i >= $base_page) { - if ($this->cur_page == $loop) + if ($this->cur_page === $loop) { - $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page + // Current page + $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; + } + elseif ($i === $base_page) + { + // First page + $output .= $this->num_tag_open.'_attr_rel('start').'>' + .$loop.''.$this->num_tag_close; } else { - $n = ($i == $base_page) ? '' : $i; - - if ($n == '' && $this->first_url != '') - { - $output .= $this->num_tag_open.'anchor_class.'href="'.$this->first_url.'">'.$loop.''.$this->num_tag_close; - } - else - { - $n = ($n == '') ? '' : $this->prefix.$n.$this->suffix; - - $output .= $this->num_tag_open.'anchor_class.'href="'.$this->base_url.$n.'">'.$loop.''.$this->num_tag_close; - } + $append = $this->prefix.$i.$this->suffix; + $output .= $this->num_tag_open.'' + .$loop.''.$this->num_tag_close; } } } } // Render the "next" link - if ($this->next_link !== FALSE AND $this->cur_page < $num_pages) + if ($this->next_link !== FALSE && $this->cur_page < $num_pages) { - if ($this->use_page_numbers) - { - $i = $this->cur_page + 1; - } - else - { - $i = ($this->cur_page * $this->per_page); - } + $i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page; - $output .= $this->next_tag_open.'anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->next_link.''.$this->next_tag_close; + $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1); + + $output .= $this->next_tag_open.'_attr_rel('next').'>'.$this->next_link.''.$this->next_tag_close; } // Render the "Last" link - if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages) + if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + ! $this->num_links) < $num_pages) { - if ($this->use_page_numbers) - { - $i = $num_pages; - } - else - { - $i = (($num_pages * $this->per_page) - $this->per_page); - } - $output .= $this->last_tag_open.'anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.''.$this->last_tag_close; + $i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page; + + $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages); + + $output .= $this->last_tag_open.'' + .$this->last_link.''.$this->last_tag_close; } - // Kill double slashes. Note: Sometimes we can end up with a double slash + // Kill double slashes. Note: Sometimes we can end up with a double slash // in the penultimate link so we'll kill all double slashes. - $output = preg_replace("#([^:])//+#", "\\1/", $output); + $output = preg_replace('#([^:"])//+#', '\\1/', $output); // Add the wrapper HTML if exists - $output = $this->full_tag_open.$output.$this->full_tag_close; - - return $output; + return $this->full_tag_open.$output.$this->full_tag_close; } -} -// END Pagination Class -/* End of file Pagination.php */ -/* Location: ./system/libraries/Pagination.php */ \ No newline at end of file + // -------------------------------------------------------------------- + + /** + * Parse attributes + * + * @param array $attributes + * @return void + */ + protected function _parse_attributes($attributes) + { + isset($attributes['rel']) OR $attributes['rel'] = TRUE; + $this->_link_types = ($attributes['rel']) + ? array('start' => 'start', 'prev' => 'prev', 'next' => 'next') + : array(); + unset($attributes['rel']); + + $this->_attributes = ''; + foreach ($attributes as $key => $value) + { + $this->_attributes .= ' '.$key.'="'.$value.'"'; + } + } + + // -------------------------------------------------------------------- + + /** + * Add "rel" attribute + * + * @link http://www.w3.org/TR/html5/links.html#linkTypes + * @param string $type + * @return string + */ + protected function _attr_rel($type) + { + if (isset($this->_link_types[$type])) + { + unset($this->_link_types[$type]); + return ' rel="'.$type.'"'; + } + + return ''; + } + +} diff --git a/system/libraries/Parser.php b/system/libraries/Parser.php old mode 100755 new mode 100644 index 4d31f81..d3c6500 --- a/system/libraries/Parser.php +++ b/system/libraries/Parser.php @@ -1,19 +1,41 @@ -CI =& get_instance(); + log_message('info', 'Parser Class Initialized'); + } + + // -------------------------------------------------------------------- + + /** + * Parse a template * * Parses pseudo-variables contained in the specified template view, * replacing them with the data in the second param * - * @access public * @param string * @param array * @param bool @@ -44,8 +97,7 @@ class CI_Parser { */ public function parse($template, $data, $return = FALSE) { - $CI =& get_instance(); - $template = $CI->load->view($template, $data, TRUE); + $template = $this->CI->load->view($template, $data, TRUE); return $this->_parse($template, $data, $return); } @@ -53,18 +105,17 @@ class CI_Parser { // -------------------------------------------------------------------- /** - * Parse a String + * Parse a String * * Parses pseudo-variables contained in the specified string, * replacing them with the data in the second param * - * @access public * @param string * @param array * @param bool * @return string */ - function parse_string($template, $data, $return = FALSE) + public function parse_string($template, $data, $return = FALSE) { return $this->_parse($template, $data, $return); } @@ -72,40 +123,40 @@ class CI_Parser { // -------------------------------------------------------------------- /** - * Parse a template + * Parse a template * * Parses pseudo-variables contained in the specified template, * replacing them with the data in the second param * - * @access public * @param string * @param array * @param bool * @return string */ - function _parse($template, $data, $return = FALSE) + protected function _parse($template, $data, $return = FALSE) { - if ($template == '') + if ($template === '') { return FALSE; } + $replace = array(); foreach ($data as $key => $val) { - if (is_array($val)) - { - $template = $this->_parse_pair($key, $val, $template); - } - else - { - $template = $this->_parse_single($key, (string)$val, $template); - } + $replace = array_merge( + $replace, + is_array($val) + ? $this->_parse_pair($key, $val, $template) + : $this->_parse_single($key, (string) $val, $template) + ); } - if ($return == FALSE) + unset($data); + $template = strtr($template, $replace); + + if ($return === FALSE) { - $CI =& get_instance(); - $CI->output->append_output($template); + $this->CI->output->append_output($template); } return $template; @@ -114,14 +165,13 @@ class CI_Parser { // -------------------------------------------------------------------- /** - * Set the left/right variable delimiters + * Set the left/right variable delimiters * - * @access public * @param string * @param string * @return void */ - function set_delimiters($l = '{', $r = '}') + public function set_delimiters($l = '{', $r = '}') { $this->l_delim = $l; $this->r_delim = $r; @@ -130,83 +180,69 @@ class CI_Parser { // -------------------------------------------------------------------- /** - * Parse a single key/value + * Parse a single key/value * - * @access private * @param string * @param string * @param string * @return string */ - function _parse_single($key, $val, $string) + protected function _parse_single($key, $val, $string) { - return str_replace($this->l_delim.$key.$this->r_delim, $val, $string); + return array($this->l_delim.$key.$this->r_delim => (string) $val); } // -------------------------------------------------------------------- /** - * Parse a tag pair + * Parse a tag pair * - * Parses tag pairs: {some_tag} string... {/some_tag} + * Parses tag pairs: {some_tag} string... {/some_tag} * - * @access private * @param string * @param array * @param string * @return string */ - function _parse_pair($variable, $data, $string) + protected function _parse_pair($variable, $data, $string) { - if (FALSE === ($match = $this->_match_pair($string, $variable))) - { - return $string; - } + $replace = array(); + preg_match_all( + '#'.preg_quote($this->l_delim.$variable.$this->r_delim).'(.+?)'.preg_quote($this->l_delim.'/'.$variable.$this->r_delim).'#s', + $string, + $matches, + PREG_SET_ORDER + ); - $str = ''; - foreach ($data as $row) + foreach ($matches as $match) { - $temp = $match['1']; - foreach ($row as $key => $val) + $str = ''; + foreach ($data as $row) { - if ( ! is_array($val)) + $temp = array(); + foreach ($row as $key => $val) { - $temp = $this->_parse_single($key, $val, $temp); - } - else - { - $temp = $this->_parse_pair($key, $val, $temp); + if (is_array($val)) + { + $pair = $this->_parse_pair($key, $val, $match[1]); + if ( ! empty($pair)) + { + $temp = array_merge($temp, $pair); + } + + continue; + } + + $temp[$this->l_delim.$key.$this->r_delim] = $val; } + + $str .= strtr($match[1], $temp); } - $str .= $temp; + $replace[$match[0]] = $str; } - return str_replace($match['0'], $str, $string); - } - - // -------------------------------------------------------------------- - - /** - * Matches a variable pair - * - * @access private - * @param string - * @param string - * @return mixed - */ - function _match_pair($string, $variable) - { - if ( ! preg_match("|" . preg_quote($this->l_delim) . $variable . preg_quote($this->r_delim) . "(.+?)". preg_quote($this->l_delim) . '/' . $variable . preg_quote($this->r_delim) . "|s", $string, $match)) - { - return FALSE; - } - - return $match; + return $replace; } } -// END Parser Class - -/* End of file Parser.php */ -/* Location: ./system/libraries/Parser.php */ diff --git a/system/libraries/Profiler.php b/system/libraries/Profiler.php old mode 100755 new mode 100644 index 2fe21db..77af7b9 --- a/system/libraries/Profiler.php +++ b/system/libraries/Profiler.php @@ -1,19 +1,41 @@ -CI =& get_instance(); $this->CI->load->language('profiler'); - if (isset($config['query_toggle_count'])) - { - $this->_query_toggle_count = (int) $config['query_toggle_count']; - unset($config['query_toggle_count']); - } - // default all sections to display foreach ($this->_available_sections as $section) { @@ -72,6 +110,7 @@ class CI_Profiler { } $this->set_sections($config); + log_message('info', 'Profiler Class Initialized'); } // -------------------------------------------------------------------- @@ -81,16 +120,22 @@ class CI_Profiler { * * Sets the private _compile_* properties to enable/disable Profiler sections * - * @param mixed + * @param mixed $config * @return void */ public function set_sections($config) { + if (isset($config['query_toggle_count'])) + { + $this->_query_toggle_count = (int) $config['query_toggle_count']; + unset($config['query_toggle_count']); + } + foreach ($config as $method => $enable) { if (in_array($method, $this->_available_sections)) { - $this->_compile_{$method} = ($enable !== FALSE) ? TRUE : FALSE; + $this->_compile_{$method} = ($enable !== FALSE); } } } @@ -114,36 +159,32 @@ class CI_Profiler { { // We match the "end" marker so that the list ends // up in the order that it was defined - if (preg_match("/(.+?)_end/i", $key, $match)) + if (preg_match('/(.+?)_end$/i', $key, $match) + && isset($this->CI->benchmark->marker[$match[1].'_end'], $this->CI->benchmark->marker[$match[1].'_start'])) { - if (isset($this->CI->benchmark->marker[$match[1].'_end']) AND isset($this->CI->benchmark->marker[$match[1].'_start'])) - { - $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key); - } + $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key); } } // Build a table containing the profile data. // Note: At some point we should turn this into a template that can - // be modified. We also might want to make this data available to be logged + // be modified. We also might want to make this data available to be logged - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_benchmarks').'  '; - $output .= "\n"; - $output .= "\n\n\n"; + $output = "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_benchmarks')."  " + ."\n\n\n
    \n"; foreach ($profile as $key => $val) { $key = ucwords(str_replace(array('_', '-'), ' ', $key)); - $output .= "\n"; + $output .= '\n"; } - $output .= "
    ".$key."  ".$val."
    ' + .$key.'  ' + .$val."
    \n"; - $output .= "
    "; - - return $output; + return $output."\n"; } // -------------------------------------------------------------------- @@ -158,27 +199,37 @@ class CI_Profiler { $dbs = array(); // Let's determine which databases are currently connected to - foreach (get_object_vars($this->CI) as $CI_object) + foreach (get_object_vars($this->CI) as $name => $cobject) { - if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB') ) + if (is_object($cobject)) { - $dbs[] = $CI_object; + if ($cobject instanceof CI_DB) + { + $dbs[get_class($this->CI).':$'.$name] = $cobject; + } + elseif ($cobject instanceof CI_Model) + { + foreach (get_object_vars($cobject) as $mname => $mobject) + { + if ($mobject instanceof CI_DB) + { + $dbs[get_class($cobject).':$'.$mname] = $mobject; + } + } + } } } - if (count($dbs) == 0) + if (count($dbs) === 0) { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_queries').'  '; - $output .= "\n"; - $output .= "\n\n\n"; - $output .="\n"; - $output .= "
    ".$this->CI->lang->line('profiler_no_db')."
    \n"; - $output .= "
    "; - - return $output; + return "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_queries').'  ' + ."\n\n\n\n" + .'\n
    ' + .$this->CI->lang->line('profiler_no_db') + ."
    \n
    "; } // Load the text helper so we can highlight the SQL @@ -188,58 +239,57 @@ class CI_Profiler { $highlight = array('SELECT', 'DISTINCT', 'FROM', 'WHERE', 'AND', 'LEFT JOIN', 'ORDER BY', 'GROUP BY', 'LIMIT', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'OR ', 'HAVING', 'OFFSET', 'NOT IN', 'IN', 'LIKE', 'NOT LIKE', 'COUNT', 'MAX', 'MIN', 'ON', 'AS', 'AVG', 'SUM', '(', ')'); $output = "\n\n"; - $count = 0; - foreach ($dbs as $db) + foreach ($dbs as $name => $db) { - $count++; - $hide_queries = (count($db->queries) > $this->_query_toggle_count) ? ' display:none' : ''; + $total_time = number_format(array_sum($db->query_times), 4).' '.$this->CI->lang->line('profiler_seconds'); $show_hide_js = '('.$this->CI->lang->line('profiler_section_hide').')'; - if ($hide_queries != '') + if ($hide_queries !== '') { $show_hide_js = '('.$this->CI->lang->line('profiler_section_show').')'; } - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_database').':  '.$db->database.'   '.$this->CI->lang->line('profiler_queries').': '.count($db->queries).'  '.$show_hide_js.''; - $output .= "\n"; - $output .= "\n\n\n"; + $output .= '
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_database') + .':  '.$db->database.' ('.$name.')   '.$this->CI->lang->line('profiler_queries') + .': '.count($db->queries).' ('.$total_time.')  '.$show_hide_js."\n\n\n" + .'
    \n"; - if (count($db->queries) == 0) + if (count($db->queries) === 0) { - $output .= "\n"; + $output .= '\n"; } else { foreach ($db->queries as $key => $val) { $time = number_format($db->query_times[$key], 4); - - $val = highlight_code($val, ENT_QUOTES); + $val = highlight_code($val); foreach ($highlight as $bold) { $val = str_replace($bold, ''.$bold.'', $val); } - $output .= "\n"; + $output .= '\n"; } } - $output .= "
    ".$this->CI->lang->line('profiler_no_queries')."
    ' + .$this->CI->lang->line('profiler_no_queries')."
    ".$time."  ".$val."
    ' + .$time.'  ' + .$val."
    \n"; - $output .= "
    "; - + $output .= "\n"; + $count++; } return $output; } - // -------------------------------------------------------------------- /** @@ -249,44 +299,35 @@ class CI_Profiler { */ protected function _compile_get() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_get_data').'  '; - $output .= "\n"; + $output = "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_get_data')."  \n"; - if (count($_GET) == 0) + if (count($_GET) === 0) { - $output .= "
    ".$this->CI->lang->line('profiler_no_get')."
    "; + $output .= '
    '.$this->CI->lang->line('profiler_no_get').'
    '; } else { - $output .= "\n\n\n"; + $output .= "\n\n
    \n"; foreach ($_GET as $key => $val) { - if ( ! is_numeric($key)) - { - $key = "'".$key."'"; - } + is_int($key) OR $key = "'".htmlspecialchars($key, ENT_QUOTES, config_item('charset'))."'"; + $val = (is_array($val) OR is_object($val)) + ? '
    '.htmlspecialchars(print_r($val, TRUE), ENT_QUOTES, config_item('charset')).'
    ' + : htmlspecialchars($val, ENT_QUOTES, config_item('charset')); - $output .= "\n"; + $output .= '\n"; } $output .= "
    $_GET[".$key."]   "; - if (is_array($val)) - { - $output .= "
    " . htmlspecialchars(stripslashes(print_r($val, true))) . "
    "; - } - else - { - $output .= htmlspecialchars(stripslashes($val)); - } - $output .= "
    $_GET[' + .$key.']   ' + .$val."
    \n"; } - $output .= "
    "; - return $output; + return $output.'
    '; } // -------------------------------------------------------------------- @@ -298,44 +339,47 @@ class CI_Profiler { */ protected function _compile_post() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_post_data').'  '; - $output .= "\n"; + $output = "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_post_data')."  \n"; - if (count($_POST) == 0) + if (count($_POST) === 0 && count($_FILES) === 0) { - $output .= "
    ".$this->CI->lang->line('profiler_no_post')."
    "; + $output .= '
    '.$this->CI->lang->line('profiler_no_post').'
    '; } else { - $output .= "\n\n\n"; + $output .= "\n\n
    \n"; foreach ($_POST as $key => $val) { - if ( ! is_numeric($key)) - { - $key = "'".$key."'"; - } + is_int($key) OR $key = "'".htmlspecialchars($key, ENT_QUOTES, config_item('charset'))."'"; + $val = (is_array($val) OR is_object($val)) + ? '
    '.htmlspecialchars(print_r($val, TRUE), ENT_QUOTES, config_item('charset')).'
    ' + : htmlspecialchars($val, ENT_QUOTES, config_item('charset')); - $output .= "\n"; + $output .= '\n"; + } + + foreach ($_FILES as $key => $val) + { + is_int($key) OR $key = "'".htmlspecialchars($key, ENT_QUOTES, config_item('charset'))."'"; + $val = (is_array($val) OR is_object($val)) + ? '
    '.htmlspecialchars(print_r($val, TRUE), ENT_QUOTES, config_item('charset')).'
    ' + : htmlspecialchars($val, ENT_QUOTES, config_item('charset')); + + $output .= '\n"; } $output .= "
    $_POST[".$key."]   "; - if (is_array($val)) - { - $output .= "
    " . htmlspecialchars(stripslashes(print_r($val, TRUE))) . "
    "; - } - else - { - $output .= htmlspecialchars(stripslashes($val)); - } - $output .= "
    $_POST[' + .$key.']   ' + .$val."
    $_FILES[' + .$key.']   ' + .$val."
    \n"; } - $output .= "
    "; - return $output; + return $output.'
    '; } // -------------------------------------------------------------------- @@ -347,24 +391,13 @@ class CI_Profiler { */ protected function _compile_uri_string() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_uri_string').'  '; - $output .= "\n"; - - if ($this->CI->uri->uri_string == '') - { - $output .= "
    ".$this->CI->lang->line('profiler_no_uri')."
    "; - } - else - { - $output .= "
    ".$this->CI->uri->uri_string."
    "; - } - - $output .= "
    "; - - return $output; + return "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_uri_string')."  \n" + .'
    ' + .($this->CI->uri->uri_string === '' ? $this->CI->lang->line('profiler_no_uri') : $this->CI->uri->uri_string) + .'
    '; } // -------------------------------------------------------------------- @@ -376,17 +409,12 @@ class CI_Profiler { */ protected function _compile_controller_info() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_controller_info').'  '; - $output .= "\n"; - - $output .= "
    ".$this->CI->router->fetch_class()."/".$this->CI->router->fetch_method()."
    "; - - $output .= "
    "; - - return $output; + return "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_controller_info')."  \n" + .'
    '.$this->CI->router->class.'/'.$this->CI->router->method + .'
    '; } // -------------------------------------------------------------------- @@ -400,24 +428,13 @@ class CI_Profiler { */ protected function _compile_memory_usage() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_memory_usage').'  '; - $output .= "\n"; - - if (function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '') - { - $output .= "
    ".number_format($usage).' bytes
    '; - } - else - { - $output .= "
    ".$this->CI->lang->line('profiler_no_memory')."
    "; - } - - $output .= "
    "; - - return $output; + return "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_memory_usage')."  \n" + .'
    ' + .(($usage = memory_get_usage()) != '' ? number_format($usage).' bytes' : $this->CI->lang->line('profiler_no_memory')) + .'
    '; } // -------------------------------------------------------------------- @@ -431,24 +448,21 @@ class CI_Profiler { */ protected function _compile_http_headers() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_headers').'  ('.$this->CI->lang->line('profiler_section_show').')'; - $output .= "\n"; + $output = "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_headers') + .'  ('.$this->CI->lang->line('profiler_section_show').")\n\n\n" + .''."\n"; - $output .= "\n\n\n"; - - foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD',' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR') as $header) + foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD',' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR', 'HTTP_DNT') as $header) { - $val = (isset($_SERVER[$header])) ? $_SERVER[$header] : ''; - $output .= "\n"; + $val = isset($_SERVER[$header]) ? htmlspecialchars($_SERVER[$header], ENT_QUOTES, config_item('charset')) : ''; + $output .= '\n"; } - $output .= "\n"; - $output .= "
    "; - - return $output; + return $output."\n
    "; } // -------------------------------------------------------------------- @@ -462,28 +476,30 @@ class CI_Profiler { */ protected function _compile_config() { - $output = "\n\n"; - $output .= '
    '; - $output .= "\n"; - $output .= '  '.$this->CI->lang->line('profiler_config').'  ('.$this->CI->lang->line('profiler_section_show').')'; - $output .= "\n"; + $output = "\n\n" + .'
    ' + ."\n" + .'  '.$this->CI->lang->line('profiler_config').'  ('.$this->CI->lang->line('profiler_section_show').")\n\n\n" + .''."\n"; - $output .= "\n\n\n"; - - foreach ($this->CI->config->config as $config=>$val) + foreach ($this->CI->config->config as $config => $val) { - if (is_array($val)) + $pre = ''; + $pre_close = ''; + + if (is_array($val) OR is_object($val)) { $val = print_r($val, TRUE); + + $pre = '
    ' ;
    + 				$pre_close = '
    '; } - $output .= "\n"; + $output .= '\n"; } - $output .= "\n"; - $output .= "
    "; - - return $output; + return $output."\n
    "; } // -------------------------------------------------------------------- @@ -493,30 +509,35 @@ class CI_Profiler { * * @return string */ - private function _compile_session_data() + protected function _compile_session_data() { if ( ! isset($this->CI->session)) { return; } - $output = '
    '; - $output .= '  '.$this->CI->lang->line('profiler_session_data').'  ('.$this->CI->lang->line('profiler_section_show').')'; - $output .= ""; + $output = '
    ' + .'  '.$this->CI->lang->line('profiler_session_data').'  ('.$this->CI->lang->line('profiler_section_show').')' + .'
    '; - foreach ($this->CI->session->all_userdata() as $key => $val) + foreach ($this->CI->session->userdata() as $key => $val) { + $pre = ''; + $pre_close = ''; + if (is_array($val) OR is_object($val)) { $val = print_r($val, TRUE); + + $pre = '
    ' ;
    + 				$pre_close = '
    '; } - $output .= "\n"; + $output .= '\n"; } - $output .= ''; - $output .= "
    "; - return $output; + return $output."\n"; } // -------------------------------------------------------------------- @@ -528,31 +549,26 @@ class CI_Profiler { */ public function run() { - $output = "
    "; + $output = '
    '; $fields_displayed = 0; foreach ($this->_available_sections as $section) { if ($this->_compile_{$section} !== FALSE) { - $func = "_compile_{$section}"; + $func = '_compile_'.$section; $output .= $this->{$func}(); $fields_displayed++; } } - if ($fields_displayed == 0) + if ($fields_displayed === 0) { - $output .= '

    '.$this->CI->lang->line('profiler_no_profiles').'

    '; + $output .= '

    ' + .$this->CI->lang->line('profiler_no_profiles').'

    '; } - $output .= '
    '; - - return $output; + return $output.'
    '; } + } - -// END CI_Profiler class - -/* End of file Profiler.php */ -/* Location: ./system/libraries/Profiler.php */ \ No newline at end of file diff --git a/system/libraries/Session.php b/system/libraries/Session.php deleted file mode 100755 index 5f4f605..0000000 --- a/system/libraries/Session.php +++ /dev/null @@ -1,793 +0,0 @@ -CI =& get_instance(); - - // Set all the session preferences, which can either be set - // manually via the $params array above or via the config file - foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration', 'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path', 'cookie_domain', 'cookie_secure', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key) - { - $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key); - } - - if ($this->encryption_key == '') - { - show_error('In order to use the Session class you are required to set an encryption key in your config file.'); - } - - // Load the string helper so we can use the strip_slashes() function - $this->CI->load->helper('string'); - - // Do we need encryption? If so, load the encryption class - if ($this->sess_encrypt_cookie == TRUE) - { - $this->CI->load->library('encrypt'); - } - - // Are we using a database? If so, load it - if ($this->sess_use_database === TRUE AND $this->sess_table_name != '') - { - $this->CI->load->database(); - } - - // Set the "now" time. Can either be GMT or server time, based on the - // config prefs. We use this to set the "last activity" time - $this->now = $this->_get_time(); - - // Set the session length. If the session expiration is - // set to zero we'll set the expiration two years from now. - if ($this->sess_expiration == 0) - { - $this->sess_expiration = (60*60*24*365*2); - } - - // Set the cookie name - $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name; - - // Run the Session routine. If a session doesn't exist we'll - // create a new one. If it does, we'll update it. - if ( ! $this->sess_read()) - { - $this->sess_create(); - } - else - { - $this->sess_update(); - } - - // Delete 'old' flashdata (from last request) - $this->_flashdata_sweep(); - - // Mark all new flashdata as old (data will be deleted before next request) - $this->_flashdata_mark(); - - // Delete expired sessions if necessary - $this->_sess_gc(); - - log_message('debug', "Session routines successfully run"); - } - - // -------------------------------------------------------------------- - - /** - * Fetch the current session data if it exists - * - * @access public - * @return bool - */ - function sess_read() - { - // Fetch the cookie - $session = $this->CI->input->cookie($this->sess_cookie_name); - - // No cookie? Goodbye cruel world!... - if ($session === FALSE) - { - log_message('debug', 'A session cookie was not found.'); - return FALSE; - } - - // HMAC authentication - $len = strlen($session) - 40; - - if ($len <= 0) - { - log_message('error', 'Session: The session cookie was not signed.'); - return FALSE; - } - - // Check cookie authentication - $hmac = substr($session, $len); - $session = substr($session, 0, $len); - - // Time-attack-safe comparison - $hmac_check = hash_hmac('sha1', $session, $this->encryption_key); - $diff = 0; - - for ($i = 0; $i < 40; $i++) - { - $xor = ord($hmac[$i]) ^ ord($hmac_check[$i]); - $diff |= $xor; - } - - if ($diff !== 0) - { - log_message('error', 'Session: HMAC mismatch. The session cookie data did not match what was expected.'); - $this->sess_destroy(); - return FALSE; - } - - // Decrypt the cookie data - if ($this->sess_encrypt_cookie == TRUE) - { - $session = $this->CI->encrypt->decode($session); - } - - // Unserialize the session array - $session = $this->_unserialize($session); - - // Is the session data we unserialized an array with the correct format? - if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity'])) - { - $this->sess_destroy(); - return FALSE; - } - - // Is the session current? - if (($session['last_activity'] + $this->sess_expiration) < $this->now) - { - $this->sess_destroy(); - return FALSE; - } - - // Does the IP Match? - if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address()) - { - $this->sess_destroy(); - return FALSE; - } - - // Does the User Agent Match? - if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 120))) - { - $this->sess_destroy(); - return FALSE; - } - - // Is there a corresponding session in the DB? - if ($this->sess_use_database === TRUE) - { - $this->CI->db->where('session_id', $session['session_id']); - - if ($this->sess_match_ip == TRUE) - { - $this->CI->db->where('ip_address', $session['ip_address']); - } - - if ($this->sess_match_useragent == TRUE) - { - $this->CI->db->where('user_agent', $session['user_agent']); - } - - $query = $this->CI->db->get($this->sess_table_name); - - // No result? Kill it! - if ($query->num_rows() == 0) - { - $this->sess_destroy(); - return FALSE; - } - - // Is there custom data? If so, add it to the main session array - $row = $query->row(); - if (isset($row->user_data) AND $row->user_data != '') - { - $custom_data = $this->_unserialize($row->user_data); - - if (is_array($custom_data)) - { - foreach ($custom_data as $key => $val) - { - $session[$key] = $val; - } - } - } - } - - // Session is valid! - $this->userdata = $session; - unset($session); - - return TRUE; - } - - // -------------------------------------------------------------------- - - /** - * Write the session data - * - * @access public - * @return void - */ - function sess_write() - { - // Are we saving custom data to the DB? If not, all we do is update the cookie - if ($this->sess_use_database === FALSE) - { - $this->_set_cookie(); - return; - } - - // set the custom userdata, the session data we will set in a second - $custom_userdata = $this->userdata; - $cookie_userdata = array(); - - // Before continuing, we need to determine if there is any custom data to deal with. - // Let's determine this by removing the default indexes to see if there's anything left in the array - // and set the session data while we're at it - foreach (array('session_id','ip_address','user_agent','last_activity') as $val) - { - unset($custom_userdata[$val]); - $cookie_userdata[$val] = $this->userdata[$val]; - } - - // Did we find any custom data? If not, we turn the empty array into a string - // since there's no reason to serialize and store an empty array in the DB - if (count($custom_userdata) === 0) - { - $custom_userdata = ''; - } - else - { - // Serialize the custom data array so we can store it - $custom_userdata = $this->_serialize($custom_userdata); - } - - // Run the update query - $this->CI->db->where('session_id', $this->userdata['session_id']); - $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata)); - - // Write the cookie. Notice that we manually pass the cookie data array to the - // _set_cookie() function. Normally that function will store $this->userdata, but - // in this case that array contains custom data, which we do not want in the cookie. - $this->_set_cookie($cookie_userdata); - } - - // -------------------------------------------------------------------- - - /** - * Create a new session - * - * @access public - * @return void - */ - function sess_create() - { - $sessid = ''; - while (strlen($sessid) < 32) - { - $sessid .= mt_rand(0, mt_getrandmax()); - } - - // To make the session ID even more secure we'll combine it with the user's IP - $sessid .= $this->CI->input->ip_address(); - - $this->userdata = array( - 'session_id' => md5(uniqid($sessid, TRUE)), - 'ip_address' => $this->CI->input->ip_address(), - 'user_agent' => substr($this->CI->input->user_agent(), 0, 120), - 'last_activity' => $this->now, - 'user_data' => '' - ); - - - // Save the data to the DB if needed - if ($this->sess_use_database === TRUE) - { - $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata)); - } - - // Write the cookie - $this->_set_cookie(); - } - - // -------------------------------------------------------------------- - - /** - * Update an existing session - * - * @access public - * @return void - */ - function sess_update() - { - // We only update the session every five minutes by default - if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now) - { - return; - } - - // Save the old session id so we know which record to - // update in the database if we need it - $old_sessid = $this->userdata['session_id']; - $new_sessid = ''; - while (strlen($new_sessid) < 32) - { - $new_sessid .= mt_rand(0, mt_getrandmax()); - } - - // To make the session ID even more secure we'll combine it with the user's IP - $new_sessid .= $this->CI->input->ip_address(); - - // Turn it into a hash - $new_sessid = md5(uniqid($new_sessid, TRUE)); - - // Update the session data in the session data array - $this->userdata['session_id'] = $new_sessid; - $this->userdata['last_activity'] = $this->now; - - // _set_cookie() will handle this for us if we aren't using database sessions - // by pushing all userdata to the cookie. - $cookie_data = NULL; - - // Update the session ID and last_activity field in the DB if needed - if ($this->sess_use_database === TRUE) - { - // set cookie explicitly to only have our session data - $cookie_data = array(); - foreach (array('session_id','ip_address','user_agent','last_activity') as $val) - { - $cookie_data[$val] = $this->userdata[$val]; - } - - $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid))); - } - - // Write the cookie - $this->_set_cookie($cookie_data); - } - - // -------------------------------------------------------------------- - - /** - * Destroy the current session - * - * @access public - * @return void - */ - function sess_destroy() - { - // Kill the session DB row - if ($this->sess_use_database === TRUE && isset($this->userdata['session_id'])) - { - $this->CI->db->where('session_id', $this->userdata['session_id']); - $this->CI->db->delete($this->sess_table_name); - } - - // Kill the cookie - setcookie( - $this->sess_cookie_name, - addslashes(serialize(array())), - ($this->now - 31500000), - $this->cookie_path, - $this->cookie_domain, - 0 - ); - - // Kill session data - $this->userdata = array(); - } - - // -------------------------------------------------------------------- - - /** - * Fetch a specific item from the session array - * - * @access public - * @param string - * @return string - */ - function userdata($item) - { - return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item]; - } - - // -------------------------------------------------------------------- - - /** - * Fetch all session data - * - * @access public - * @return array - */ - function all_userdata() - { - return $this->userdata; - } - - // -------------------------------------------------------------------- - - /** - * Add or change data in the "userdata" array - * - * @access public - * @param mixed - * @param string - * @return void - */ - function set_userdata($newdata = array(), $newval = '') - { - if (is_string($newdata)) - { - $newdata = array($newdata => $newval); - } - - if (count($newdata) > 0) - { - foreach ($newdata as $key => $val) - { - $this->userdata[$key] = $val; - } - } - - $this->sess_write(); - } - - // -------------------------------------------------------------------- - - /** - * Delete a session variable from the "userdata" array - * - * @access array - * @return void - */ - function unset_userdata($newdata = array()) - { - if (is_string($newdata)) - { - $newdata = array($newdata => ''); - } - - if (count($newdata) > 0) - { - foreach ($newdata as $key => $val) - { - unset($this->userdata[$key]); - } - } - - $this->sess_write(); - } - - // ------------------------------------------------------------------------ - - /** - * Add or change flashdata, only available - * until the next request - * - * @access public - * @param mixed - * @param string - * @return void - */ - function set_flashdata($newdata = array(), $newval = '') - { - if (is_string($newdata)) - { - $newdata = array($newdata => $newval); - } - - if (count($newdata) > 0) - { - foreach ($newdata as $key => $val) - { - $flashdata_key = $this->flashdata_key.':new:'.$key; - $this->set_userdata($flashdata_key, $val); - } - } - } - - // ------------------------------------------------------------------------ - - /** - * Keeps existing flashdata available to next request. - * - * @access public - * @param string - * @return void - */ - function keep_flashdata($key) - { - // 'old' flashdata gets removed. Here we mark all - // flashdata as 'new' to preserve it from _flashdata_sweep() - // Note the function will return FALSE if the $key - // provided cannot be found - $old_flashdata_key = $this->flashdata_key.':old:'.$key; - $value = $this->userdata($old_flashdata_key); - - $new_flashdata_key = $this->flashdata_key.':new:'.$key; - $this->set_userdata($new_flashdata_key, $value); - } - - // ------------------------------------------------------------------------ - - /** - * Fetch a specific flashdata item from the session array - * - * @access public - * @param string - * @return string - */ - function flashdata($key) - { - $flashdata_key = $this->flashdata_key.':old:'.$key; - return $this->userdata($flashdata_key); - } - - // ------------------------------------------------------------------------ - - /** - * Identifies flashdata as 'old' for removal - * when _flashdata_sweep() runs. - * - * @access private - * @return void - */ - function _flashdata_mark() - { - $userdata = $this->all_userdata(); - foreach ($userdata as $name => $value) - { - $parts = explode(':new:', $name); - if (is_array($parts) && count($parts) === 2) - { - $new_name = $this->flashdata_key.':old:'.$parts[1]; - $this->set_userdata($new_name, $value); - $this->unset_userdata($name); - } - } - } - - // ------------------------------------------------------------------------ - - /** - * Removes all flashdata marked as 'old' - * - * @access private - * @return void - */ - - function _flashdata_sweep() - { - $userdata = $this->all_userdata(); - foreach ($userdata as $key => $value) - { - if (strpos($key, ':old:')) - { - $this->unset_userdata($key); - } - } - - } - - // -------------------------------------------------------------------- - - /** - * Get the "now" time - * - * @access private - * @return string - */ - function _get_time() - { - if (strtolower($this->time_reference) == 'gmt') - { - $now = time(); - $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now)); - } - else - { - $time = time(); - } - - return $time; - } - - // -------------------------------------------------------------------- - - /** - * Write the session cookie - * - * @access public - * @return void - */ - function _set_cookie($cookie_data = NULL) - { - if (is_null($cookie_data)) - { - $cookie_data = $this->userdata; - } - - // Serialize the userdata for the cookie - $cookie_data = $this->_serialize($cookie_data); - - if ($this->sess_encrypt_cookie == TRUE) - { - $cookie_data = $this->CI->encrypt->encode($cookie_data); - } - - $cookie_data .= hash_hmac('sha1', $cookie_data, $this->encryption_key); - - $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time(); - - // Set the cookie - setcookie( - $this->sess_cookie_name, - $cookie_data, - $expire, - $this->cookie_path, - $this->cookie_domain, - $this->cookie_secure - ); - } - - // -------------------------------------------------------------------- - - /** - * Serialize an array - * - * This function first converts any slashes found in the array to a temporary - * marker, so when it gets unserialized the slashes will be preserved - * - * @access private - * @param array - * @return string - */ - function _serialize($data) - { - if (is_array($data)) - { - foreach ($data as $key => $val) - { - if (is_string($val)) - { - $data[$key] = str_replace('\\', '{{slash}}', $val); - } - } - } - else - { - if (is_string($data)) - { - $data = str_replace('\\', '{{slash}}', $data); - } - } - - return serialize($data); - } - - // -------------------------------------------------------------------- - - /** - * Unserialize - * - * This function unserializes a data string, then converts any - * temporary slash markers back to actual slashes - * - * @access private - * @param array - * @return string - */ - function _unserialize($data) - { - $data = @unserialize(strip_slashes($data)); - - if (is_array($data)) - { - foreach ($data as $key => $val) - { - if (is_string($val)) - { - $data[$key] = str_replace('{{slash}}', '\\', $val); - } - } - - return $data; - } - - return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data; - } - - // -------------------------------------------------------------------- - - /** - * Garbage collection - * - * This deletes expired session rows from database - * if the probability percentage is met - * - * @access public - * @return void - */ - function _sess_gc() - { - if ($this->sess_use_database != TRUE) - { - return; - } - - srand(time()); - if ((rand() % 100) < $this->gc_probability) - { - $expire = $this->now - $this->sess_expiration; - - $this->CI->db->where("last_activity < {$expire}"); - $this->CI->db->delete($this->sess_table_name); - - log_message('debug', 'Session garbage collection performed.'); - } - } - - -} -// END Session Class - -/* End of file Session.php */ -/* Location: ./system/libraries/Session.php */ diff --git a/system/libraries/Session/Session.php b/system/libraries/Session/Session.php new file mode 100644 index 0000000..9b834f8 --- /dev/null +++ b/system/libraries/Session/Session.php @@ -0,0 +1,983 @@ +_driver = $params['driver']; + unset($params['driver']); + } + elseif ($driver = config_item('sess_driver')) + { + $this->_driver = $driver; + } + // Note: BC workaround + elseif (config_item('sess_use_database')) + { + log_message('debug', 'Session: "sess_driver" is empty; using BC fallback to "sess_use_database".'); + $this->_driver = 'database'; + } + + $class = $this->_ci_load_classes($this->_driver); + + // Configuration ... + $this->_configure($params); + $this->_config['_sid_regexp'] = $this->_sid_regexp; + + $class = new $class($this->_config); + if ($class instanceof SessionHandlerInterface) + { + if (is_php('5.4')) + { + session_set_save_handler($class, TRUE); + } + else + { + session_set_save_handler( + array($class, 'open'), + array($class, 'close'), + array($class, 'read'), + array($class, 'write'), + array($class, 'destroy'), + array($class, 'gc') + ); + + register_shutdown_function('session_write_close'); + } + } + else + { + log_message('error', "Session: Driver '".$this->_driver."' doesn't implement SessionHandlerInterface. Aborting."); + return; + } + + // Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers + if (isset($_COOKIE[$this->_config['cookie_name']]) + && ( + ! is_string($_COOKIE[$this->_config['cookie_name']]) + OR ! preg_match('#\A'.$this->_sid_regexp.'\z#', $_COOKIE[$this->_config['cookie_name']]) + ) + ) + { + unset($_COOKIE[$this->_config['cookie_name']]); + } + + session_start(); + + // Is session ID auto-regeneration configured? (ignoring ajax requests) + if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) OR strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') + && ($regenerate_time = config_item('sess_time_to_update')) > 0 + ) + { + if ( ! isset($_SESSION['__ci_last_regenerate'])) + { + $_SESSION['__ci_last_regenerate'] = time(); + } + elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerate_time)) + { + $this->sess_regenerate((bool) config_item('sess_regenerate_destroy')); + } + } + // Another work-around ... PHP doesn't seem to send the session cookie + // unless it is being currently created or regenerated + elseif (isset($_COOKIE[$this->_config['cookie_name']]) && $_COOKIE[$this->_config['cookie_name']] === session_id()) + { + setcookie( + $this->_config['cookie_name'], + session_id(), + (empty($this->_config['cookie_lifetime']) ? 0 : time() + $this->_config['cookie_lifetime']), + $this->_config['cookie_path'], + $this->_config['cookie_domain'], + $this->_config['cookie_secure'], + TRUE + ); + } + + $this->_ci_init_vars(); + + log_message('info', "Session: Class initialized using '".$this->_driver."' driver."); + } + + // ------------------------------------------------------------------------ + + /** + * CI Load Classes + * + * An internal method to load all possible dependency and extension + * classes. It kind of emulates the CI_Driver library, but is + * self-sufficient. + * + * @param string $driver Driver name + * @return string Driver class name + */ + protected function _ci_load_classes($driver) + { + // PHP 5.4 compatibility + interface_exists('SessionHandlerInterface', FALSE) OR require_once(BASEPATH.'libraries/Session/SessionHandlerInterface.php'); + + $prefix = config_item('subclass_prefix'); + + if ( ! class_exists('CI_Session_driver', FALSE)) + { + require_once( + file_exists(APPPATH.'libraries/Session/Session_driver.php') + ? APPPATH.'libraries/Session/Session_driver.php' + : BASEPATH.'libraries/Session/Session_driver.php' + ); + + if (file_exists($file_path = APPPATH.'libraries/Session/'.$prefix.'Session_driver.php')) + { + require_once($file_path); + } + } + + $class = 'Session_'.$driver.'_driver'; + + // Allow custom drivers without the CI_ or MY_ prefix + if ( ! class_exists($class, FALSE) && file_exists($file_path = APPPATH.'libraries/Session/drivers/'.$class.'.php')) + { + require_once($file_path); + if (class_exists($class, FALSE)) + { + return $class; + } + } + + if ( ! class_exists('CI_'.$class, FALSE)) + { + if (file_exists($file_path = APPPATH.'libraries/Session/drivers/'.$class.'.php') OR file_exists($file_path = BASEPATH.'libraries/Session/drivers/'.$class.'.php')) + { + require_once($file_path); + } + + if ( ! class_exists('CI_'.$class, FALSE) && ! class_exists($class, FALSE)) + { + throw new UnexpectedValueException("Session: Configured driver '".$driver."' was not found. Aborting."); + } + } + + if ( ! class_exists($prefix.$class, FALSE) && file_exists($file_path = APPPATH.'libraries/Session/drivers/'.$prefix.$class.'.php')) + { + require_once($file_path); + if (class_exists($prefix.$class, FALSE)) + { + return $prefix.$class; + } + + log_message('debug', 'Session: '.$prefix.$class.".php found but it doesn't declare class ".$prefix.$class.'.'); + } + + return 'CI_'.$class; + } + + // ------------------------------------------------------------------------ + + /** + * Configuration + * + * Handle input parameters and configuration defaults + * + * @param array &$params Input parameters + * @return void + */ + protected function _configure(&$params) + { + $expiration = config_item('sess_expiration'); + + if (isset($params['cookie_lifetime'])) + { + $params['cookie_lifetime'] = (int) $params['cookie_lifetime']; + } + else + { + $params['cookie_lifetime'] = ( ! isset($expiration) && config_item('sess_expire_on_close')) + ? 0 : (int) $expiration; + } + + isset($params['cookie_name']) OR $params['cookie_name'] = config_item('sess_cookie_name'); + if (empty($params['cookie_name'])) + { + $params['cookie_name'] = ini_get('session.name'); + } + else + { + ini_set('session.name', $params['cookie_name']); + } + + isset($params['cookie_path']) OR $params['cookie_path'] = config_item('cookie_path'); + isset($params['cookie_domain']) OR $params['cookie_domain'] = config_item('cookie_domain'); + isset($params['cookie_secure']) OR $params['cookie_secure'] = (bool) config_item('cookie_secure'); + + session_set_cookie_params( + $params['cookie_lifetime'], + $params['cookie_path'], + $params['cookie_domain'], + $params['cookie_secure'], + TRUE // HttpOnly; Yes, this is intentional and not configurable for security reasons + ); + + if (empty($expiration)) + { + $params['expiration'] = (int) ini_get('session.gc_maxlifetime'); + } + else + { + $params['expiration'] = (int) $expiration; + ini_set('session.gc_maxlifetime', $expiration); + } + + $params['match_ip'] = (bool) (isset($params['match_ip']) ? $params['match_ip'] : config_item('sess_match_ip')); + + isset($params['save_path']) OR $params['save_path'] = config_item('sess_save_path'); + + $this->_config = $params; + + // Security is king + ini_set('session.use_trans_sid', 0); + ini_set('session.use_strict_mode', 1); + ini_set('session.use_cookies', 1); + ini_set('session.use_only_cookies', 1); + + $this->_configure_sid_length(); + } + + // ------------------------------------------------------------------------ + + /** + * Configure session ID length + * + * To make life easier, we used to force SHA-1 and 4 bits per + * character on everyone. And of course, someone was unhappy. + * + * Then PHP 7.1 broke backwards-compatibility because ext/session + * is such a mess that nobody wants to touch it with a pole stick, + * and the one guy who does, nobody has the energy to argue with. + * + * So we were forced to make changes, and OF COURSE something was + * going to break and now we have this pile of shit. -- Narf + * + * @return void + */ + protected function _configure_sid_length() + { + if (PHP_VERSION_ID < 70100) + { + $hash_function = ini_get('session.hash_function'); + if (ctype_digit($hash_function)) + { + if ($hash_function !== '1') + { + ini_set('session.hash_function', 1); + } + + $bits = 160; + } + elseif ( ! in_array($hash_function, hash_algos(), TRUE)) + { + ini_set('session.hash_function', 1); + $bits = 160; + } + elseif (($bits = strlen(hash($hash_function, 'dummy', false)) * 4) < 160) + { + ini_set('session.hash_function', 1); + $bits = 160; + } + + $bits_per_character = (int) ini_get('session.hash_bits_per_character'); + $sid_length = (int) ceil($bits / $bits_per_character); + } + else + { + $bits_per_character = (int) ini_get('session.sid_bits_per_character'); + $sid_length = (int) ini_get('session.sid_length'); + if (($bits = $sid_length * $bits_per_character) < 160) + { + // Add as many more characters as necessary to reach at least 160 bits + $sid_length += (int) ceil((160 % $bits) / $bits_per_character); + ini_set('session.sid_length', $sid_length); + } + } + + // Yes, 4,5,6 are the only known possible values as of 2016-10-27 + switch ($bits_per_character) + { + case 4: + $this->_sid_regexp = '[0-9a-f]'; + break; + case 5: + $this->_sid_regexp = '[0-9a-v]'; + break; + case 6: + $this->_sid_regexp = '[0-9a-zA-Z,-]'; + break; + } + + $this->_sid_regexp .= '{'.$sid_length.'}'; + } + + // ------------------------------------------------------------------------ + + /** + * Handle temporary variables + * + * Clears old "flash" data, marks the new one for deletion and handles + * "temp" data deletion. + * + * @return void + */ + protected function _ci_init_vars() + { + if ( ! empty($_SESSION['__ci_vars'])) + { + $current_time = time(); + + foreach ($_SESSION['__ci_vars'] as $key => &$value) + { + if ($value === 'new') + { + $_SESSION['__ci_vars'][$key] = 'old'; + } + // Hacky, but 'old' will (implicitly) always be less than time() ;) + // DO NOT move this above the 'new' check! + elseif ($value < $current_time) + { + unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]); + } + } + + if (empty($_SESSION['__ci_vars'])) + { + unset($_SESSION['__ci_vars']); + } + } + + $this->userdata =& $_SESSION; + } + + // ------------------------------------------------------------------------ + + /** + * Mark as flash + * + * @param mixed $key Session data key(s) + * @return bool + */ + public function mark_as_flash($key) + { + if (is_array($key)) + { + for ($i = 0, $c = count($key); $i < $c; $i++) + { + if ( ! isset($_SESSION[$key[$i]])) + { + return FALSE; + } + } + + $new = array_fill_keys($key, 'new'); + + $_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) + ? array_merge($_SESSION['__ci_vars'], $new) + : $new; + + return TRUE; + } + + if ( ! isset($_SESSION[$key])) + { + return FALSE; + } + + $_SESSION['__ci_vars'][$key] = 'new'; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Get flash keys + * + * @return array + */ + public function get_flash_keys() + { + if ( ! isset($_SESSION['__ci_vars'])) + { + return array(); + } + + $keys = array(); + foreach (array_keys($_SESSION['__ci_vars']) as $key) + { + is_int($_SESSION['__ci_vars'][$key]) OR $keys[] = $key; + } + + return $keys; + } + + // ------------------------------------------------------------------------ + + /** + * Unmark flash + * + * @param mixed $key Session data key(s) + * @return void + */ + public function unmark_flash($key) + { + if (empty($_SESSION['__ci_vars'])) + { + return; + } + + is_array($key) OR $key = array($key); + + foreach ($key as $k) + { + if (isset($_SESSION['__ci_vars'][$k]) && ! is_int($_SESSION['__ci_vars'][$k])) + { + unset($_SESSION['__ci_vars'][$k]); + } + } + + if (empty($_SESSION['__ci_vars'])) + { + unset($_SESSION['__ci_vars']); + } + } + + // ------------------------------------------------------------------------ + + /** + * Mark as temp + * + * @param mixed $key Session data key(s) + * @param int $ttl Time-to-live in seconds + * @return bool + */ + public function mark_as_temp($key, $ttl = 300) + { + $ttl += time(); + + if (is_array($key)) + { + $temp = array(); + + foreach ($key as $k => $v) + { + // Do we have a key => ttl pair, or just a key? + if (is_int($k)) + { + $k = $v; + $v = $ttl; + } + else + { + $v += time(); + } + + if ( ! isset($_SESSION[$k])) + { + return FALSE; + } + + $temp[$k] = $v; + } + + $_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) + ? array_merge($_SESSION['__ci_vars'], $temp) + : $temp; + + return TRUE; + } + + if ( ! isset($_SESSION[$key])) + { + return FALSE; + } + + $_SESSION['__ci_vars'][$key] = $ttl; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Get temp keys + * + * @return array + */ + public function get_temp_keys() + { + if ( ! isset($_SESSION['__ci_vars'])) + { + return array(); + } + + $keys = array(); + foreach (array_keys($_SESSION['__ci_vars']) as $key) + { + is_int($_SESSION['__ci_vars'][$key]) && $keys[] = $key; + } + + return $keys; + } + + // ------------------------------------------------------------------------ + + /** + * Unmark temp + * + * @param mixed $key Session data key(s) + * @return void + */ + public function unmark_temp($key) + { + if (empty($_SESSION['__ci_vars'])) + { + return; + } + + is_array($key) OR $key = array($key); + + foreach ($key as $k) + { + if (isset($_SESSION['__ci_vars'][$k]) && is_int($_SESSION['__ci_vars'][$k])) + { + unset($_SESSION['__ci_vars'][$k]); + } + } + + if (empty($_SESSION['__ci_vars'])) + { + unset($_SESSION['__ci_vars']); + } + } + + // ------------------------------------------------------------------------ + + /** + * __get() + * + * @param string $key 'session_id' or a session data key + * @return mixed + */ + public function __get($key) + { + // Note: Keep this order the same, just in case somebody wants to + // use 'session_id' as a session data key, for whatever reason + if (isset($_SESSION[$key])) + { + return $_SESSION[$key]; + } + elseif ($key === 'session_id') + { + return session_id(); + } + + return NULL; + } + + // ------------------------------------------------------------------------ + + /** + * __isset() + * + * @param string $key 'session_id' or a session data key + * @return bool + */ + public function __isset($key) + { + if ($key === 'session_id') + { + return (session_status() === PHP_SESSION_ACTIVE); + } + + return isset($_SESSION[$key]); + } + + // ------------------------------------------------------------------------ + + /** + * __set() + * + * @param string $key Session data key + * @param mixed $value Session data value + * @return void + */ + public function __set($key, $value) + { + $_SESSION[$key] = $value; + } + + // ------------------------------------------------------------------------ + + /** + * Session destroy + * + * Legacy CI_Session compatibility method + * + * @return void + */ + public function sess_destroy() + { + session_destroy(); + } + + // ------------------------------------------------------------------------ + + /** + * Session regenerate + * + * Legacy CI_Session compatibility method + * + * @param bool $destroy Destroy old session data flag + * @return void + */ + public function sess_regenerate($destroy = FALSE) + { + $_SESSION['__ci_last_regenerate'] = time(); + session_regenerate_id($destroy); + } + + // ------------------------------------------------------------------------ + + /** + * Get userdata reference + * + * Legacy CI_Session compatibility method + * + * @returns array + */ + public function &get_userdata() + { + return $_SESSION; + } + + // ------------------------------------------------------------------------ + + /** + * Userdata (fetch) + * + * Legacy CI_Session compatibility method + * + * @param string $key Session data key + * @return mixed Session data value or NULL if not found + */ + public function userdata($key = NULL) + { + if (isset($key)) + { + return isset($_SESSION[$key]) ? $_SESSION[$key] : NULL; + } + elseif (empty($_SESSION)) + { + return array(); + } + + $userdata = array(); + $_exclude = array_merge( + array('__ci_vars'), + $this->get_flash_keys(), + $this->get_temp_keys() + ); + + foreach (array_keys($_SESSION) as $key) + { + if ( ! in_array($key, $_exclude, TRUE)) + { + $userdata[$key] = $_SESSION[$key]; + } + } + + return $userdata; + } + + // ------------------------------------------------------------------------ + + /** + * Set userdata + * + * Legacy CI_Session compatibility method + * + * @param mixed $data Session data key or an associative array + * @param mixed $value Value to store + * @return void + */ + public function set_userdata($data, $value = NULL) + { + if (is_array($data)) + { + foreach ($data as $key => &$value) + { + $_SESSION[$key] = $value; + } + + return; + } + + $_SESSION[$data] = $value; + } + + // ------------------------------------------------------------------------ + + /** + * Unset userdata + * + * Legacy CI_Session compatibility method + * + * @param mixed $key Session data key(s) + * @return void + */ + public function unset_userdata($key) + { + if (is_array($key)) + { + foreach ($key as $k) + { + unset($_SESSION[$k]); + } + + return; + } + + unset($_SESSION[$key]); + } + + // ------------------------------------------------------------------------ + + /** + * All userdata (fetch) + * + * Legacy CI_Session compatibility method + * + * @return array $_SESSION, excluding flash data items + */ + public function all_userdata() + { + return $this->userdata(); + } + + // ------------------------------------------------------------------------ + + /** + * Has userdata + * + * Legacy CI_Session compatibility method + * + * @param string $key Session data key + * @return bool + */ + public function has_userdata($key) + { + return isset($_SESSION[$key]); + } + + // ------------------------------------------------------------------------ + + /** + * Flashdata (fetch) + * + * Legacy CI_Session compatibility method + * + * @param string $key Session data key + * @return mixed Session data value or NULL if not found + */ + public function flashdata($key = NULL) + { + if (isset($key)) + { + return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) && ! is_int($_SESSION['__ci_vars'][$key])) + ? $_SESSION[$key] + : NULL; + } + + $flashdata = array(); + + if ( ! empty($_SESSION['__ci_vars'])) + { + foreach ($_SESSION['__ci_vars'] as $key => &$value) + { + is_int($value) OR $flashdata[$key] = $_SESSION[$key]; + } + } + + return $flashdata; + } + + // ------------------------------------------------------------------------ + + /** + * Set flashdata + * + * Legacy CI_Session compatibility method + * + * @param mixed $data Session data key or an associative array + * @param mixed $value Value to store + * @return void + */ + public function set_flashdata($data, $value = NULL) + { + $this->set_userdata($data, $value); + $this->mark_as_flash(is_array($data) ? array_keys($data) : $data); + } + + // ------------------------------------------------------------------------ + + /** + * Keep flashdata + * + * Legacy CI_Session compatibility method + * + * @param mixed $key Session data key(s) + * @return void + */ + public function keep_flashdata($key) + { + $this->mark_as_flash($key); + } + + // ------------------------------------------------------------------------ + + /** + * Temp data (fetch) + * + * Legacy CI_Session compatibility method + * + * @param string $key Session data key + * @return mixed Session data value or NULL if not found + */ + public function tempdata($key = NULL) + { + if (isset($key)) + { + return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) && is_int($_SESSION['__ci_vars'][$key])) + ? $_SESSION[$key] + : NULL; + } + + $tempdata = array(); + + if ( ! empty($_SESSION['__ci_vars'])) + { + foreach ($_SESSION['__ci_vars'] as $key => &$value) + { + is_int($value) && $tempdata[$key] = $_SESSION[$key]; + } + } + + return $tempdata; + } + + // ------------------------------------------------------------------------ + + /** + * Set tempdata + * + * Legacy CI_Session compatibility method + * + * @param mixed $data Session data key or an associative array of items + * @param mixed $value Value to store + * @param int $ttl Time-to-live in seconds + * @return void + */ + public function set_tempdata($data, $value = NULL, $ttl = 300) + { + $this->set_userdata($data, $value); + $this->mark_as_temp(is_array($data) ? array_keys($data) : $data, $ttl); + } + + // ------------------------------------------------------------------------ + + /** + * Unset tempdata + * + * Legacy CI_Session compatibility method + * + * @param mixed $data Session data key(s) + * @return void + */ + public function unset_tempdata($key) + { + $this->unmark_temp($key); + } + +} diff --git a/system/libraries/Session/SessionHandlerInterface.php b/system/libraries/Session/SessionHandlerInterface.php new file mode 100644 index 0000000..240c5f5 --- /dev/null +++ b/system/libraries/Session/SessionHandlerInterface.php @@ -0,0 +1,59 @@ +_config =& $params; + + if (is_php('7')) + { + $this->_success = TRUE; + $this->_failure = FALSE; + } + else + { + $this->_success = 0; + $this->_failure = -1; + } + } + + // ------------------------------------------------------------------------ + + /** + * PHP 5.x validate ID + * + * Enforces session.use_strict_mode + * + * @return void + */ + public function php5_validate_id() + { + if (isset($_COOKIE[$this->_config['cookie_name']]) && ! $this->validateSessionId($_COOKIE[$this->_config['cookie_name']])) + { + unset($_COOKIE[$this->_config['cookie_name']]); + } + } + + // ------------------------------------------------------------------------ + + /** + * Cookie destroy + * + * Internal method to force removal of a cookie by the client + * when session_destroy() is called. + * + * @return bool + */ + protected function _cookie_destroy() + { + return setcookie( + $this->_config['cookie_name'], + NULL, + 1, + $this->_config['cookie_path'], + $this->_config['cookie_domain'], + $this->_config['cookie_secure'], + TRUE + ); + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * A dummy method allowing drivers with no locking functionality + * (databases other than PostgreSQL and MySQL) to act as if they + * do acquire a lock. + * + * @param string $session_id + * @return bool + */ + protected function _get_lock($session_id) + { + $this->_lock = TRUE; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * @return bool + */ + protected function _release_lock() + { + if ($this->_lock) + { + $this->_lock = FALSE; + } + + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Fail + * + * Drivers other than the 'files' one don't (need to) use the + * session.save_path INI setting, but that leads to confusing + * error messages emitted by PHP when open() or write() fail, + * as the message contains session.save_path ... + * To work around the problem, the drivers will call this method + * so that the INI is set just in time for the error message to + * be properly generated. + * + * @return mixed + */ + protected function _fail() + { + ini_set('session.save_path', config_item('sess_save_path')); + return $this->_failure; + } +} diff --git a/system/libraries/Session/drivers/Session_database_driver.php b/system/libraries/Session/drivers/Session_database_driver.php new file mode 100644 index 0000000..734fe62 --- /dev/null +++ b/system/libraries/Session/drivers/Session_database_driver.php @@ -0,0 +1,446 @@ +db) OR $CI->load->database(); + $this->_db = $CI->db; + + if ( ! $this->_db instanceof CI_DB_query_builder) + { + throw new Exception('Query Builder not enabled for the configured database. Aborting.'); + } + elseif ($this->_db->pconnect) + { + throw new Exception('Configured database connection is persistent. Aborting.'); + } + elseif ($this->_db->cache_on) + { + throw new Exception('Configured database connection has cache enabled. Aborting.'); + } + + $db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver); + if (strpos($db_driver, 'mysql') !== FALSE) + { + $this->_platform = 'mysql'; + } + elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE)) + { + $this->_platform = 'postgre'; + } + + // Note: BC work-around for the old 'sess_table_name' setting, should be removed in the future. + if ( ! isset($this->_config['save_path']) && ($this->_config['save_path'] = config_item('sess_table_name'))) + { + log_message('debug', 'Session: "sess_save_path" is empty; using BC fallback to "sess_table_name".'); + } + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Initializes the database connection + * + * @param string $save_path Table name + * @param string $name Session cookie name, unused + * @return bool + */ + public function open($save_path, $name) + { + if (empty($this->_db->conn_id) && ! $this->_db->db_connect()) + { + return $this->_fail(); + } + + $this->php5_validate_id(); + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + if ($this->_get_lock($session_id) !== FALSE) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + $this->_db + ->select('data') + ->from($this->_config['save_path']) + ->where('id', $session_id); + + if ($this->_config['match_ip']) + { + $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + } + + if ( ! ($result = $this->_db->get()) OR ($result = $result->row()) === NULL) + { + // PHP7 will reuse the same SessionHandler object after + // ID regeneration, so we need to explicitly set this to + // FALSE instead of relying on the default ... + $this->_row_exists = FALSE; + $this->_fingerprint = md5(''); + return ''; + } + + // PostgreSQL's variant of a BLOB datatype is Bytea, which is a + // PITA to work with, so we use base64-encoded data in a TEXT + // field instead. + $result = ($this->_platform === 'postgre') + ? base64_decode(rtrim($result->data)) + : $result->data; + + $this->_fingerprint = md5($result); + $this->_row_exists = TRUE; + return $result; + } + + $this->_fingerprint = md5(''); + return ''; + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + // Was the ID regenerated? + if (isset($this->_session_id) && $session_id !== $this->_session_id) + { + if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id)) + { + return $this->_fail(); + } + + $this->_row_exists = FALSE; + $this->_session_id = $session_id; + } + elseif ($this->_lock === FALSE) + { + return $this->_fail(); + } + + if ($this->_row_exists === FALSE) + { + $insert_data = array( + 'id' => $session_id, + 'ip_address' => $_SERVER['REMOTE_ADDR'], + 'timestamp' => time(), + 'data' => ($this->_platform === 'postgre' ? base64_encode($session_data) : $session_data) + ); + + if ($this->_db->insert($this->_config['save_path'], $insert_data)) + { + $this->_fingerprint = md5($session_data); + $this->_row_exists = TRUE; + return $this->_success; + } + + return $this->_fail(); + } + + $this->_db->where('id', $session_id); + if ($this->_config['match_ip']) + { + $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + } + + $update_data = array('timestamp' => time()); + if ($this->_fingerprint !== md5($session_data)) + { + $update_data['data'] = ($this->_platform === 'postgre') + ? base64_encode($session_data) + : $session_data; + } + + if ($this->_db->update($this->_config['save_path'], $update_data)) + { + $this->_fingerprint = md5($session_data); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks + * + * @return bool + */ + public function close() + { + return ($this->_lock && ! $this->_release_lock()) + ? $this->_fail() + : $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if ($this->_lock) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + $this->_db->where('id', $session_id); + if ($this->_config['match_ip']) + { + $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + } + + if ( ! $this->_db->delete($this->_config['save_path'])) + { + return $this->_fail(); + } + } + + if ($this->close() === $this->_success) + { + $this->_cookie_destroy(); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + return ($this->_db->delete($this->_config['save_path'], 'timestamp < '.(time() - $maxlifetime))) + ? $this->_success + : $this->_fail(); + } + + // -------------------------------------------------------------------- + + /** + * Validate ID + * + * Checks whether a session ID record exists server-side, + * to enforce session.use_strict_mode. + * + * @param string $id + * @return bool + */ + public function validateSessionId($id) + { + // Prevent previous QB calls from messing with our queries + $this->_db->reset_query(); + + $this->_db->select('1')->from($this->_config['save_path'])->where('id', $id); + empty($this->_config['match_ip']) OR $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']); + $result = $this->_db->get(); + empty($result) OR $result = $result->row(); + + return ! empty($result); + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * Acquires a lock, depending on the underlying platform. + * + * @param string $session_id Session ID + * @return bool + */ + protected function _get_lock($session_id) + { + if ($this->_platform === 'mysql') + { + $arg = md5($session_id.($this->_config['match_ip'] ? '_'.$_SERVER['REMOTE_ADDR'] : '')); + if ($this->_db->query("SELECT GET_LOCK('".$arg."', 300) AS ci_session_lock")->row()->ci_session_lock) + { + $this->_lock = $arg; + return TRUE; + } + + return FALSE; + } + elseif ($this->_platform === 'postgre') + { + $arg = "hashtext('".$session_id."')".($this->_config['match_ip'] ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : ''); + if ($this->_db->simple_query('SELECT pg_advisory_lock('.$arg.')')) + { + $this->_lock = $arg; + return TRUE; + } + + return FALSE; + } + + return parent::_get_lock($session_id); + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * Releases a previously acquired lock + * + * @return bool + */ + protected function _release_lock() + { + if ( ! $this->_lock) + { + return TRUE; + } + + if ($this->_platform === 'mysql') + { + if ($this->_db->query("SELECT RELEASE_LOCK('".$this->_lock."') AS ci_session_lock")->row()->ci_session_lock) + { + $this->_lock = FALSE; + return TRUE; + } + + return FALSE; + } + elseif ($this->_platform === 'postgre') + { + if ($this->_db->simple_query('SELECT pg_advisory_unlock('.$this->_lock.')')) + { + $this->_lock = FALSE; + return TRUE; + } + + return FALSE; + } + + return parent::_release_lock(); + } +} diff --git a/system/libraries/Session/drivers/Session_files_driver.php b/system/libraries/Session/drivers/Session_files_driver.php new file mode 100644 index 0000000..4670594 --- /dev/null +++ b/system/libraries/Session/drivers/Session_files_driver.php @@ -0,0 +1,426 @@ +_config['save_path'])) + { + $this->_config['save_path'] = rtrim($this->_config['save_path'], '/\\'); + ini_set('session.save_path', $this->_config['save_path']); + } + else + { + log_message('debug', 'Session: "sess_save_path" is empty; using "session.save_path" value from php.ini.'); + $this->_config['save_path'] = rtrim(ini_get('session.save_path'), '/\\'); + } + + $this->_sid_regexp = $this->_config['_sid_regexp']; + + isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload')); + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Sanitizes the save_path directory. + * + * @param string $save_path Path to session files' directory + * @param string $name Session cookie name + * @return bool + */ + public function open($save_path, $name) + { + if ( ! is_dir($save_path)) + { + if ( ! mkdir($save_path, 0700, TRUE)) + { + throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not a directory, doesn't exist or cannot be created."); + } + } + elseif ( ! is_writable($save_path)) + { + throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not writable by the PHP process."); + } + + $this->_config['save_path'] = $save_path; + $this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR + .$name // we'll use the session cookie name as a prefix to avoid collisions + .($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : ''); + + $this->php5_validate_id(); + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + // This might seem weird, but PHP 5.6 introduces session_reset(), + // which re-reads session data + if ($this->_file_handle === NULL) + { + $this->_file_new = ! file_exists($this->_file_path.$session_id); + + if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE) + { + log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'."); + return $this->_failure; + } + + if (flock($this->_file_handle, LOCK_EX) === FALSE) + { + log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'."); + fclose($this->_file_handle); + $this->_file_handle = NULL; + return $this->_failure; + } + + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + if ($this->_file_new) + { + chmod($this->_file_path.$session_id, 0600); + $this->_fingerprint = md5(''); + return ''; + } + } + // We shouldn't need this, but apparently we do ... + // See https://github.com/bcit-ci/CodeIgniter/issues/4039 + elseif ($this->_file_handle === FALSE) + { + return $this->_failure; + } + else + { + rewind($this->_file_handle); + } + + $session_data = ''; + for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer)) + { + if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE) + { + break; + } + + $session_data .= $buffer; + } + + $this->_fingerprint = md5($session_data); + return $session_data; + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + // If the two IDs don't match, we have a session_regenerate_id() call + // and we need to close the old handle and open a new one + if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure)) + { + return $this->_failure; + } + + if ( ! is_resource($this->_file_handle)) + { + return $this->_failure; + } + elseif ($this->_fingerprint === md5($session_data)) + { + return ( ! $this->_file_new && ! touch($this->_file_path.$session_id)) + ? $this->_failure + : $this->_success; + } + + if ( ! $this->_file_new) + { + ftruncate($this->_file_handle, 0); + rewind($this->_file_handle); + } + + if (($length = strlen($session_data)) > 0) + { + for ($written = 0; $written < $length; $written += $result) + { + if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE) + { + break; + } + } + + if ( ! is_int($result)) + { + $this->_fingerprint = md5(substr($session_data, 0, $written)); + log_message('error', 'Session: Unable to write data.'); + return $this->_failure; + } + } + + $this->_fingerprint = md5($session_data); + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks and closes file descriptor. + * + * @return bool + */ + public function close() + { + if (is_resource($this->_file_handle)) + { + flock($this->_file_handle, LOCK_UN); + fclose($this->_file_handle); + + $this->_file_handle = $this->_file_new = $this->_session_id = NULL; + } + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if ($this->close() === $this->_success) + { + if (file_exists($this->_file_path.$session_id)) + { + $this->_cookie_destroy(); + return unlink($this->_file_path.$session_id) + ? $this->_success + : $this->_failure; + } + + return $this->_success; + } + elseif ($this->_file_path !== NULL) + { + clearstatcache(); + if (file_exists($this->_file_path.$session_id)) + { + $this->_cookie_destroy(); + return unlink($this->_file_path.$session_id) + ? $this->_success + : $this->_failure; + } + + return $this->_success; + } + + return $this->_failure; + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE) + { + log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'."); + return $this->_failure; + } + + $ts = time() - $maxlifetime; + + $pattern = ($this->_config['match_ip'] === TRUE) + ? '[0-9a-f]{32}' + : ''; + + $pattern = sprintf( + '#\A%s'.$pattern.$this->_sid_regexp.'\z#', + preg_quote($this->_config['cookie_name']) + ); + + while (($file = readdir($directory)) !== FALSE) + { + // If the filename doesn't match this pattern, it's either not a session file or is not ours + if ( ! preg_match($pattern, $file) + OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file) + OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE + OR $mtime > $ts) + { + continue; + } + + unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file); + } + + closedir($directory); + + return $this->_success; + } + + // -------------------------------------------------------------------- + + /** + * Validate ID + * + * Checks whether a session ID record exists server-side, + * to enforce session.use_strict_mode. + * + * @param string $id + * @return bool + */ + public function validateSessionId($id) + { + $result = is_file($this->_file_path.$id); + clearstatcache(TRUE, $this->_file_path.$id); + return $result; + } + + // -------------------------------------------------------------------- + + /** + * Byte-safe strlen() + * + * @param string $str + * @return int + */ + protected static function strlen($str) + { + return (self::$func_overload) + ? mb_strlen($str, '8bit') + : strlen($str); + } +} diff --git a/system/libraries/Session/drivers/Session_memcached_driver.php b/system/libraries/Session/drivers/Session_memcached_driver.php new file mode 100644 index 0000000..ab54f02 --- /dev/null +++ b/system/libraries/Session/drivers/Session_memcached_driver.php @@ -0,0 +1,397 @@ +_config['save_path'])) + { + log_message('error', 'Session: No Memcached save path configured.'); + } + + if ($this->_config['match_ip'] === TRUE) + { + $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':'; + } + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Sanitizes save_path and initializes connections. + * + * @param string $save_path Server path(s) + * @param string $name Session cookie name, unused + * @return bool + */ + public function open($save_path, $name) + { + $this->_memcached = new Memcached(); + $this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE); // required for touch() usage + $server_list = array(); + foreach ($this->_memcached->getServerList() as $server) + { + $server_list[] = $server['host'].':'.$server['port']; + } + + if ( ! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->_config['save_path'], $matches, PREG_SET_ORDER)) + { + $this->_memcached = NULL; + log_message('error', 'Session: Invalid Memcached save path format: '.$this->_config['save_path']); + return $this->_fail(); + } + + foreach ($matches as $match) + { + // If Memcached already has this server (or if the port is invalid), skip it + if (in_array($match[1].':'.$match[2], $server_list, TRUE)) + { + log_message('debug', 'Session: Memcached server pool already has '.$match[1].':'.$match[2]); + continue; + } + + if ( ! $this->_memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0)) + { + log_message('error', 'Could not add '.$match[1].':'.$match[2].' to Memcached server pool.'); + } + else + { + $server_list[] = $match[1].':'.$match[2]; + } + } + + if (empty($server_list)) + { + log_message('error', 'Session: Memcached server pool is empty.'); + return $this->_fail(); + } + + $this->php5_validate_id(); + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + if (isset($this->_memcached) && $this->_get_lock($session_id)) + { + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + $session_data = (string) $this->_memcached->get($this->_key_prefix.$session_id); + $this->_fingerprint = md5($session_data); + return $session_data; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + if ( ! isset($this->_memcached, $this->_lock_key)) + { + return $this->_fail(); + } + // Was the ID regenerated? + elseif ($session_id !== $this->_session_id) + { + if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id)) + { + return $this->_fail(); + } + + $this->_fingerprint = md5(''); + $this->_session_id = $session_id; + } + + $key = $this->_key_prefix.$session_id; + + $this->_memcached->replace($this->_lock_key, time(), 300); + if ($this->_fingerprint !== ($fingerprint = md5($session_data))) + { + if ($this->_memcached->set($key, $session_data, $this->_config['expiration'])) + { + $this->_fingerprint = $fingerprint; + return $this->_success; + } + + return $this->_fail(); + } + elseif ( + $this->_memcached->touch($key, $this->_config['expiration']) + OR ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND && $this->_memcached->set($key, $session_data, $this->_config['expiration'])) + ) + { + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks and closes connection. + * + * @return bool + */ + public function close() + { + if (isset($this->_memcached)) + { + $this->_release_lock(); + if ( ! $this->_memcached->quit()) + { + return $this->_fail(); + } + + $this->_memcached = NULL; + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if (isset($this->_memcached, $this->_lock_key)) + { + $this->_memcached->delete($this->_key_prefix.$session_id); + $this->_cookie_destroy(); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + // Not necessary, Memcached takes care of that. + return $this->_success; + } + + // -------------------------------------------------------------------- + + /** + * Validate ID + * + * Checks whether a session ID record exists server-side, + * to enforce session.use_strict_mode. + * + * @param string $id + * @return bool + */ + public function validateSessionId($id) + { + $this->_memcached->get($this->_key_prefix.$id); + return ($this->_memcached->getResultCode() === Memcached::RES_SUCCESS); + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * Acquires an (emulated) lock. + * + * @param string $session_id Session ID + * @return bool + */ + protected function _get_lock($session_id) + { + // PHP 7 reuses the SessionHandler object on regeneration, + // so we need to check here if the lock key is for the + // correct session ID. + if ($this->_lock_key === $this->_key_prefix.$session_id.':lock') + { + if ( ! $this->_memcached->replace($this->_lock_key, time(), 300)) + { + return ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND) + ? $this->_memcached->add($this->_lock_key, time(), 300) + : FALSE; + } + + return TRUE; + } + + // 30 attempts to obtain a lock, in case another request already has it + $lock_key = $this->_key_prefix.$session_id.':lock'; + $attempt = 0; + do + { + if ($this->_memcached->get($lock_key)) + { + sleep(1); + continue; + } + + $method = ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND) ? 'add' : 'set'; + if ( ! $this->_memcached->$method($lock_key, time(), 300)) + { + log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id); + return FALSE; + } + + $this->_lock_key = $lock_key; + break; + } + while (++$attempt < 30); + + if ($attempt === 30) + { + log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.'); + return FALSE; + } + + $this->_lock = TRUE; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * Releases a previously acquired lock + * + * @return bool + */ + protected function _release_lock() + { + if (isset($this->_memcached, $this->_lock_key) && $this->_lock) + { + if ( ! $this->_memcached->delete($this->_lock_key) && $this->_memcached->getResultCode() !== Memcached::RES_NOTFOUND) + { + log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key); + return FALSE; + } + + $this->_lock_key = NULL; + $this->_lock = FALSE; + } + + return TRUE; + } +} diff --git a/system/libraries/Session/drivers/Session_redis_driver.php b/system/libraries/Session/drivers/Session_redis_driver.php new file mode 100644 index 0000000..434b11e --- /dev/null +++ b/system/libraries/Session/drivers/Session_redis_driver.php @@ -0,0 +1,417 @@ +_config['save_path'])) + { + log_message('error', 'Session: No Redis save path configured.'); + } + elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches)) + { + isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below + $this->_config['save_path'] = array( + 'host' => $matches[1], + 'port' => empty($matches[2]) ? NULL : $matches[2], + 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL, + 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL, + 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL + ); + + preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1]; + } + else + { + log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']); + } + + if ($this->_config['match_ip'] === TRUE) + { + $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':'; + } + } + + // ------------------------------------------------------------------------ + + /** + * Open + * + * Sanitizes save_path and initializes connection. + * + * @param string $save_path Server path + * @param string $name Session cookie name, unused + * @return bool + */ + public function open($save_path, $name) + { + if (empty($this->_config['save_path'])) + { + return $this->_fail(); + } + + $redis = new Redis(); + if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout'])) + { + log_message('error', 'Session: Unable to connect to Redis with the configured settings.'); + } + elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password'])) + { + log_message('error', 'Session: Unable to authenticate to Redis instance.'); + } + elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database'])) + { + log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']); + } + else + { + $this->_redis = $redis; + return $this->_success; + } + + $this->php5_validate_id(); + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Read + * + * Reads session data and acquires a lock + * + * @param string $session_id Session ID + * @return string Serialized session data + */ + public function read($session_id) + { + if (isset($this->_redis) && $this->_get_lock($session_id)) + { + // Needed by write() to detect session_regenerate_id() calls + $this->_session_id = $session_id; + + $session_data = $this->_redis->get($this->_key_prefix.$session_id); + + is_string($session_data) + ? $this->_key_exists = TRUE + : $session_data = ''; + + $this->_fingerprint = md5($session_data); + return $session_data; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Write + * + * Writes (create / update) session data + * + * @param string $session_id Session ID + * @param string $session_data Serialized session data + * @return bool + */ + public function write($session_id, $session_data) + { + if ( ! isset($this->_redis, $this->_lock_key)) + { + return $this->_fail(); + } + // Was the ID regenerated? + elseif ($session_id !== $this->_session_id) + { + if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id)) + { + return $this->_fail(); + } + + $this->_key_exists = FALSE; + $this->_session_id = $session_id; + } + + $this->_redis->setTimeout($this->_lock_key, 300); + if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE) + { + if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration'])) + { + $this->_fingerprint = $fingerprint; + $this->_key_exists = TRUE; + return $this->_success; + } + + return $this->_fail(); + } + + return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration'])) + ? $this->_success + : $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Close + * + * Releases locks and closes connection. + * + * @return bool + */ + public function close() + { + if (isset($this->_redis)) + { + try { + if ($this->_redis->ping() === '+PONG') + { + $this->_release_lock(); + if ($this->_redis->close() === FALSE) + { + return $this->_fail(); + } + } + } + catch (RedisException $e) + { + log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage()); + } + + $this->_redis = NULL; + return $this->_success; + } + + return $this->_success; + } + + // ------------------------------------------------------------------------ + + /** + * Destroy + * + * Destroys the current session. + * + * @param string $session_id Session ID + * @return bool + */ + public function destroy($session_id) + { + if (isset($this->_redis, $this->_lock_key)) + { + if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1) + { + log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.'); + } + + $this->_cookie_destroy(); + return $this->_success; + } + + return $this->_fail(); + } + + // ------------------------------------------------------------------------ + + /** + * Garbage Collector + * + * Deletes expired sessions + * + * @param int $maxlifetime Maximum lifetime of sessions + * @return bool + */ + public function gc($maxlifetime) + { + // Not necessary, Redis takes care of that. + return $this->_success; + } + + // -------------------------------------------------------------------- + + /** + * Validate ID + * + * Checks whether a session ID record exists server-side, + * to enforce session.use_strict_mode. + * + * @param string $id + * @return bool + */ + public function validateSessionId($id) + { + return (bool) $this->_redis->exists($this->_key_prefix.$id); + } + + // ------------------------------------------------------------------------ + + /** + * Get lock + * + * Acquires an (emulated) lock. + * + * @param string $session_id Session ID + * @return bool + */ + protected function _get_lock($session_id) + { + // PHP 7 reuses the SessionHandler object on regeneration, + // so we need to check here if the lock key is for the + // correct session ID. + if ($this->_lock_key === $this->_key_prefix.$session_id.':lock') + { + return $this->_redis->setTimeout($this->_lock_key, 300); + } + + // 30 attempts to obtain a lock, in case another request already has it + $lock_key = $this->_key_prefix.$session_id.':lock'; + $attempt = 0; + do + { + if (($ttl = $this->_redis->ttl($lock_key)) > 0) + { + sleep(1); + continue; + } + + $result = ($ttl === -2) + ? $this->_redis->set($lock_key, time(), array('nx', 'ex' => 300)) + : $this->_redis->setex($lock_key, 300, time()); + + if ( ! $result) + { + log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id); + return FALSE; + } + + $this->_lock_key = $lock_key; + break; + } + while (++$attempt < 30); + + if ($attempt === 30) + { + log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.'); + return FALSE; + } + elseif ($ttl === -1) + { + log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.'); + } + + $this->_lock = TRUE; + return TRUE; + } + + // ------------------------------------------------------------------------ + + /** + * Release lock + * + * Releases a previously acquired lock + * + * @return bool + */ + protected function _release_lock() + { + if (isset($this->_redis, $this->_lock_key) && $this->_lock) + { + if ( ! $this->_redis->delete($this->_lock_key)) + { + log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key); + return FALSE; + } + + $this->_lock_key = NULL; + $this->_lock = FALSE; + } + + return TRUE; + } + +} diff --git a/system/libraries/Session/drivers/index.html b/system/libraries/Session/drivers/index.html new file mode 100644 index 0000000..b702fbc --- /dev/null +++ b/system/libraries/Session/drivers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

    Directory access is forbidden.

    + + + diff --git a/system/libraries/Session/index.html b/system/libraries/Session/index.html new file mode 100644 index 0000000..b702fbc --- /dev/null +++ b/system/libraries/Session/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

    Directory access is forbidden.

    + + + diff --git a/system/libraries/Sha1.php b/system/libraries/Sha1.php deleted file mode 100755 index 33778f9..0000000 --- a/system/libraries/Sha1.php +++ /dev/null @@ -1,251 +0,0 @@ -> 6) + 1; - - for ($i = 0; $i < $n * 16; $i++) - { - $x[$i] = 0; - } - - for ($i = 0; $i < strlen($str); $i++) - { - $x[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8); - } - - $x[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8); - - $x[$n * 16 - 1] = strlen($str) * 8; - - $a = 1732584193; - $b = -271733879; - $c = -1732584194; - $d = 271733878; - $e = -1009589776; - - for ($i = 0; $i < count($x); $i += 16) - { - $olda = $a; - $oldb = $b; - $oldc = $c; - $oldd = $d; - $olde = $e; - - for ($j = 0; $j < 80; $j++) - { - if ($j < 16) - { - $w[$j] = $x[$i + $j]; - } - else - { - $w[$j] = $this->_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1); - } - - $t = $this->_safe_add($this->_safe_add($this->_rol($a, 5), $this->_ft($j, $b, $c, $d)), $this->_safe_add($this->_safe_add($e, $w[$j]), $this->_kt($j))); - - $e = $d; - $d = $c; - $c = $this->_rol($b, 30); - $b = $a; - $a = $t; - } - - $a = $this->_safe_add($a, $olda); - $b = $this->_safe_add($b, $oldb); - $c = $this->_safe_add($c, $oldc); - $d = $this->_safe_add($d, $oldd); - $e = $this->_safe_add($e, $olde); - } - - return $this->_hex($a).$this->_hex($b).$this->_hex($c).$this->_hex($d).$this->_hex($e); - } - - // -------------------------------------------------------------------- - - /** - * Convert a decimal to hex - * - * @access private - * @param string - * @return string - */ - function _hex($str) - { - $str = dechex($str); - - if (strlen($str) == 7) - { - $str = '0'.$str; - } - - return $str; - } - - // -------------------------------------------------------------------- - - /** - * Return result based on iteration - * - * @access private - * @return string - */ - function _ft($t, $b, $c, $d) - { - if ($t < 20) - return ($b & $c) | ((~$b) & $d); - if ($t < 40) - return $b ^ $c ^ $d; - if ($t < 60) - return ($b & $c) | ($b & $d) | ($c & $d); - - return $b ^ $c ^ $d; - } - - // -------------------------------------------------------------------- - - /** - * Determine the additive constant - * - * @access private - * @return string - */ - function _kt($t) - { - if ($t < 20) - { - return 1518500249; - } - else if ($t < 40) - { - return 1859775393; - } - else if ($t < 60) - { - return -1894007588; - } - else - { - return -899497514; - } - } - - // -------------------------------------------------------------------- - - /** - * Add integers, wrapping at 2^32 - * - * @access private - * @return string - */ - function _safe_add($x, $y) - { - $lsw = ($x & 0xFFFF) + ($y & 0xFFFF); - $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16); - - return ($msw << 16) | ($lsw & 0xFFFF); - } - - // -------------------------------------------------------------------- - - /** - * Bitwise rotate a 32-bit number - * - * @access private - * @return integer - */ - function _rol($num, $cnt) - { - return ($num << $cnt) | $this->_zero_fill($num, 32 - $cnt); - } - - // -------------------------------------------------------------------- - - /** - * Pad string with zero - * - * @access private - * @return string - */ - function _zero_fill($a, $b) - { - $bin = decbin($a); - - if (strlen($bin) < $b) - { - $bin = 0; - } - else - { - $bin = substr($bin, 0, strlen($bin) - $b); - } - - for ($i=0; $i < $b; $i++) - { - $bin = "0".$bin; - } - - return bindec($bin); - } -} -// END CI_SHA - -/* End of file Sha1.php */ -/* Location: ./system/libraries/Sha1.php */ \ No newline at end of file diff --git a/system/libraries/Table.php b/system/libraries/Table.php old mode 100755 new mode 100644 index a2353d1..06e8d70 --- a/system/libraries/Table.php +++ b/system/libraries/Table.php @@ -1,19 +1,41 @@ - $val) + { + $this->template[$key] = $val; + } + + log_message('info', 'Table Class Initialized'); } // -------------------------------------------------------------------- @@ -47,11 +128,10 @@ class CI_Table { /** * Set the template * - * @access public - * @param array - * @return void + * @param array $template + * @return bool */ - function set_template($template) + public function set_template($template) { if ( ! is_array($template)) { @@ -59,6 +139,7 @@ class CI_Table { } $this->template = $template; + return TRUE; } // -------------------------------------------------------------------- @@ -68,32 +149,30 @@ class CI_Table { * * Can be passed as an array or discreet params * - * @access public * @param mixed - * @return void + * @return CI_Table */ - function set_heading() + public function set_heading($args = array()) { - $args = func_get_args(); - $this->heading = $this->_prep_args($args); + $this->heading = $this->_prep_args(func_get_args()); + return $this; } // -------------------------------------------------------------------- /** - * Set columns. Takes a one-dimensional array as input and creates + * Set columns. Takes a one-dimensional array as input and creates * a multi-dimensional array with a depth equal to the number of - * columns. This allows a single array with many elements to be + * columns. This allows a single array with many elements to be * displayed in a table that has a fixed column count. * - * @access public - * @param array - * @param int - * @return void + * @param array $array + * @param int $col_limit + * @return array */ - function make_columns($array = array(), $col_limit = 0) + public function make_columns($array = array(), $col_limit = 0) { - if ( ! is_array($array) OR count($array) == 0) + if ( ! is_array($array) OR count($array) === 0 OR ! is_int($col_limit)) { return FALSE; } @@ -102,13 +181,13 @@ class CI_Table { // will want headings from a one-dimensional array $this->auto_heading = FALSE; - if ($col_limit == 0) + if ($col_limit === 0) { return $array; } $new = array(); - while (count($array) > 0) + do { $temp = array_splice($array, 0, $col_limit); @@ -122,6 +201,7 @@ class CI_Table { $new[] = $temp; } + while (count($array) > 0); return $new; } @@ -133,13 +213,13 @@ class CI_Table { * * Can be passed as an array or discreet params * - * @access public - * @param mixed - * @return void + * @param mixed $value + * @return CI_Table */ - function set_empty($value) + public function set_empty($value) { $this->empty_cells = $value; + return $this; } // -------------------------------------------------------------------- @@ -149,14 +229,13 @@ class CI_Table { * * Can be passed as an array or discreet params * - * @access public * @param mixed - * @return void + * @return CI_Table */ - function add_row() + public function add_row($args = array()) { - $args = func_get_args(); - $this->rows[] = $this->_prep_args($args); + $this->rows[] = $this->_prep_args(func_get_args()); + return $this; } // -------------------------------------------------------------------- @@ -166,42 +245,22 @@ class CI_Table { * * Ensures a standard associative array format for all cell data * - * @access public - * @param type - * @return type + * @param array + * @return array */ - function _prep_args($args) + protected function _prep_args($args) { // If there is no $args[0], skip this and treat as an associative array // This can happen if there is only a single key, for example this is passed to table->generate // array(array('foo'=>'bar')) - if (isset($args[0]) AND (count($args) == 1 && is_array($args[0]))) + if (isset($args[0]) && count($args) === 1 && is_array($args[0]) && ! isset($args[0]['data'])) { - // args sent as indexed array - if ( ! isset($args[0]['data'])) - { - foreach ($args[0] as $key => $val) - { - if (is_array($val) && isset($val['data'])) - { - $args[$key] = $val; - } - else - { - $args[$key] = array('data' => $val); - } - } - } + $args = $args[0]; } - else + + foreach ($args as $key => $val) { - foreach ($args as $key => $val) - { - if ( ! is_array($val)) - { - $args[$key] = array('data' => $val); - } - } + is_array($val) OR $args[$key] = array('data' => $val); } return $args; @@ -212,13 +271,13 @@ class CI_Table { /** * Add a table caption * - * @access public - * @param string - * @return void + * @param string $caption + * @return CI_Table */ - function set_caption($caption) + public function set_caption($caption) { $this->caption = $caption; + return $this; } // -------------------------------------------------------------------- @@ -226,29 +285,27 @@ class CI_Table { /** * Generate the table * - * @access public - * @param mixed + * @param mixed $table_data * @return string */ - function generate($table_data = NULL) + public function generate($table_data = NULL) { // The table data can optionally be passed to this function // either as a database result object or an array - if ( ! is_null($table_data)) + if ( ! empty($table_data)) { - if (is_object($table_data)) + if ($table_data instanceof CI_DB_result) { - $this->_set_from_object($table_data); + $this->_set_from_db_result($table_data); } elseif (is_array($table_data)) { - $set_heading = (count($this->heading) == 0 AND $this->auto_heading == FALSE) ? FALSE : TRUE; - $this->_set_from_array($table_data, $set_heading); + $this->_set_from_array($table_data); } } - // Is there anything to display? No? Smite them! - if (count($this->heading) == 0 AND count($this->rows) == 0) + // Is there anything to display? No? Smite them! + if (empty($this->heading) && empty($this->rows)) { return 'Undefined table data'; } @@ -256,29 +313,26 @@ class CI_Table { // Compile and validate the template date $this->_compile_template(); - // set a custom cell manipulation function to a locally scoped variable so its callable - $function = $this->function; + // Validate a possibly existing custom cell manipulation function + if (isset($this->function) && ! is_callable($this->function)) + { + $this->function = NULL; + } // Build the table! - $out = $this->template['table_open']; - $out .= $this->newline; + $out = $this->template['table_open'].$this->newline; // Add any caption here if ($this->caption) { - $out .= $this->newline; - $out .= '' . $this->caption . ''; - $out .= $this->newline; + $out .= ''.$this->caption.''.$this->newline; } // Is there a table heading to display? - if (count($this->heading) > 0) + if ( ! empty($this->heading)) { - $out .= $this->template['thead_open']; - $out .= $this->newline; - $out .= $this->template['heading_row_start']; - $out .= $this->newline; + $out .= $this->template['thead_open'].$this->newline.$this->template['heading_row_start'].$this->newline; foreach ($this->heading as $heading) { @@ -286,28 +340,22 @@ class CI_Table { foreach ($heading as $key => $val) { - if ($key != 'data') + if ($key !== 'data') { - $temp = str_replace('template['heading_cell_end']; + $out .= $temp.(isset($heading['data']) ? $heading['data'] : '').$this->template['heading_cell_end']; } - $out .= $this->template['heading_row_end']; - $out .= $this->newline; - $out .= $this->template['thead_close']; - $out .= $this->newline; + $out .= $this->template['heading_row_end'].$this->newline.$this->template['thead_close'].$this->newline; } // Build the table rows - if (count($this->rows) > 0) + if ( ! empty($this->rows)) { - $out .= $this->template['tbody_open']; - $out .= $this->newline; + $out .= $this->template['tbody_open'].$this->newline; $i = 1; foreach ($this->rows as $row) @@ -318,10 +366,9 @@ class CI_Table { } // We use modulus to alternate the row colors - $name = (fmod($i++, 2)) ? '' : 'alt_'; + $name = fmod($i++, 2) ? '' : 'alt_'; - $out .= $this->template['row_'.$name.'start']; - $out .= $this->newline; + $out .= $this->template['row_'.$name.'start'].$this->newline; foreach ($row as $cell) { @@ -329,40 +376,35 @@ class CI_Table { foreach ($cell as $key => $val) { - if ($key != 'data') + if ($key !== 'data') { - $temp = str_replace('empty_cells; } + elseif (isset($this->function)) + { + $out .= call_user_func($this->function, $cell); + } else { - if ($function !== FALSE && is_callable($function)) - { - $out .= call_user_func($function, $cell); - } - else - { - $out .= $cell; - } + $out .= $cell; } $out .= $this->template['cell_'.$name.'end']; } - $out .= $this->template['row_'.$name.'end']; - $out .= $this->newline; + $out .= $this->template['row_'.$name.'end'].$this->newline; } - $out .= $this->template['tbody_close']; - $out .= $this->newline; + $out .= $this->template['tbody_close'].$this->newline; } $out .= $this->template['table_close']; @@ -378,14 +420,14 @@ class CI_Table { /** * Clears the table arrays. Useful if multiple tables are being generated * - * @access public - * @return void + * @return CI_Table */ - function clear() + public function clear() { - $this->rows = array(); - $this->heading = array(); - $this->auto_heading = TRUE; + $this->rows = array(); + $this->heading = array(); + $this->auto_heading = TRUE; + return $this; } // -------------------------------------------------------------------- @@ -393,36 +435,20 @@ class CI_Table { /** * Set table data from a database result object * - * @access public - * @param object + * @param CI_DB_result $object Database result object * @return void */ - function _set_from_object($query) + protected function _set_from_db_result($object) { - if ( ! is_object($query)) - { - return FALSE; - } - // First generate the headings from the table column names - if (count($this->heading) == 0) + if ($this->auto_heading === TRUE && empty($this->heading)) { - if ( ! method_exists($query, 'list_fields')) - { - return FALSE; - } - - $this->heading = $this->_prep_args($query->list_fields()); + $this->heading = $this->_prep_args($object->list_fields()); } - // Next blast through the result array and build out the rows - - if ($query->num_rows() > 0) + foreach ($object->result_array() as $row) { - foreach ($query->result_array() as $row) - { - $this->rows[] = $this->_prep_args($row); - } + $this->rows[] = $this->_prep_args($row); } } @@ -431,31 +457,19 @@ class CI_Table { /** * Set table data from an array * - * @access public - * @param array + * @param array $data * @return void */ - function _set_from_array($data, $set_heading = TRUE) + protected function _set_from_array($data) { - if ( ! is_array($data) OR count($data) == 0) + if ($this->auto_heading === TRUE && empty($this->heading)) { - return FALSE; + $this->heading = $this->_prep_args(array_shift($data)); } - $i = 0; - foreach ($data as $row) + foreach ($data as &$row) { - // If a heading hasn't already been set we'll use the first row of the array as the heading - if ($i == 0 AND count($data) > 1 AND count($this->heading) == 0 AND $set_heading == TRUE) - { - $this->heading = $this->_prep_args($row); - } - else - { - $this->rows[] = $this->_prep_args($row); - } - - $i++; + $this->rows[] = $this->_prep_args($row); } } @@ -464,12 +478,11 @@ class CI_Table { /** * Compile Template * - * @access private * @return void */ - function _compile_template() + protected function _compile_template() { - if ($this->template == NULL) + if ($this->template === NULL) { $this->template = $this->_default_template(); return; @@ -490,42 +503,36 @@ class CI_Table { /** * Default Template * - * @access private - * @return void + * @return array */ - function _default_template() + protected function _default_template() { - return array ( - 'table_open' => '', + return array( + 'table_open' => '
    ', - 'thead_open' => '', - 'thead_close' => '', + 'thead_open' => '', + 'thead_close' => '', - 'heading_row_start' => '', - 'heading_row_end' => '', - 'heading_cell_start' => '', + 'heading_row_start' => '', + 'heading_row_end' => '', + 'heading_cell_start' => '', - 'tbody_open' => '', - 'tbody_close' => '', + 'tbody_open' => '', + 'tbody_close' => '', - 'row_start' => '', - 'row_end' => '', - 'cell_start' => '', + 'row_start' => '', + 'row_end' => '', + 'cell_start' => '', - 'row_alt_start' => '', - 'row_alt_end' => '', - 'cell_alt_start' => '', + 'row_alt_start' => '', + 'row_alt_end' => '', + 'cell_alt_start' => '', - 'table_close' => '
    ', - 'heading_cell_end' => '
    ', + 'heading_cell_end' => '
    ', - 'cell_end' => '
    ', + 'cell_end' => '
    ', - 'cell_alt_end' => '
    ', + 'cell_alt_end' => '
    ' - ); + 'table_close' => '' + ); } - } - - -/* End of file Table.php */ -/* Location: ./system/libraries/Table.php */ \ No newline at end of file diff --git a/system/libraries/Trackback.php b/system/libraries/Trackback.php old mode 100755 new mode 100644 index 898553c..07f066d --- a/system/libraries/Trackback.php +++ b/system/libraries/Trackback.php @@ -1,19 +1,41 @@ - '', 'title' => '', 'excerpt' => '', 'blog_name' => '', 'charset' => ''); - var $convert_ascii = TRUE; - var $response = ''; - var $error_msg = array(); + /** + * Character set + * + * @var string + */ + public $charset = 'UTF-8'; + + /** + * Trackback data + * + * @var array + */ + public $data = array( + 'url' => '', + 'title' => '', + 'excerpt' => '', + 'blog_name' => '', + 'charset' => '' + ); + + /** + * Convert ASCII flag + * + * Whether to convert high-ASCII and MS Word + * characters to HTML entities. + * + * @var bool + */ + public $convert_ascii = TRUE; + + /** + * Response + * + * @var string + */ + public $response = ''; + + /** + * Error messages list + * + * @var string[] + */ + public $error_msg = array(); + + // -------------------------------------------------------------------- /** * Constructor * - * @access public + * @return void */ public function __construct() { - log_message('debug', "Trackback Class Initialized"); + log_message('info', 'Trackback Class Initialized'); } // -------------------------------------------------------------------- @@ -50,11 +111,10 @@ class CI_Trackback { /** * Send Trackback * - * @access public * @param array * @return bool */ - function send($tb_data) + public function send($tb_data) { if ( ! is_array($tb_data)) { @@ -73,38 +133,32 @@ class CI_Trackback { switch ($item) { - case 'ping_url' : $$item = $this->extract_urls($tb_data[$item]); + case 'ping_url': + $$item = $this->extract_urls($tb_data[$item]); break; - case 'excerpt' : $$item = $this->limit_characters($this->convert_xml(strip_tags(stripslashes($tb_data[$item])))); + case 'excerpt': + $$item = $this->limit_characters($this->convert_xml(strip_tags(stripslashes($tb_data[$item])))); break; - case 'url' : $$item = str_replace('-', '-', $this->convert_xml(strip_tags(stripslashes($tb_data[$item])))); + case 'url': + $$item = str_replace('-', '-', $this->convert_xml(strip_tags(stripslashes($tb_data[$item])))); break; - default : $$item = $this->convert_xml(strip_tags(stripslashes($tb_data[$item]))); + default: + $$item = $this->convert_xml(strip_tags(stripslashes($tb_data[$item]))); break; } // Convert High ASCII Characters - if ($this->convert_ascii == TRUE) + if ($this->convert_ascii === TRUE && in_array($item, array('excerpt', 'title', 'blog_name'), TRUE)) { - if ($item == 'excerpt') - { - $$item = $this->convert_ascii($$item); - } - elseif ($item == 'title') - { - $$item = $this->convert_ascii($$item); - } - elseif ($item == 'blog_name') - { - $$item = $this->convert_ascii($$item); - } + $$item = $this->convert_ascii($$item); } } // Build the Trackback data string - $charset = ( ! isset($tb_data['charset'])) ? $this->charset : $tb_data['charset']; + $charset = isset($tb_data['charset']) ? $tb_data['charset'] : $this->charset; - $data = "url=".rawurlencode($url)."&title=".rawurlencode($title)."&blog_name=".rawurlencode($blog_name)."&excerpt=".rawurlencode($excerpt)."&charset=".rawurlencode($charset); + $data = 'url='.rawurlencode($url).'&title='.rawurlencode($title).'&blog_name='.rawurlencode($blog_name) + .'&excerpt='.rawurlencode($excerpt).'&charset='.rawurlencode($charset); // Send Trackback(s) $return = TRUE; @@ -112,7 +166,7 @@ class CI_Trackback { { foreach ($ping_url as $url) { - if ($this->process($url, $data) == FALSE) + if ($this->process($url, $data) === FALSE) { $return = FALSE; } @@ -132,29 +186,35 @@ class CI_Trackback { * If the data is valid it is set to the $this->data array * so that it can be inserted into a database. * - * @access public * @return bool */ - function receive() + public function receive() { foreach (array('url', 'title', 'blog_name', 'excerpt') as $val) { - if ( ! isset($_POST[$val]) OR $_POST[$val] == '') + if (empty($_POST[$val])) { $this->set_error('The following required POST variable is missing: '.$val); return FALSE; } - $this->data['charset'] = ( ! isset($_POST['charset'])) ? 'auto' : strtoupper(trim($_POST['charset'])); + $this->data['charset'] = isset($_POST['charset']) ? strtoupper(trim($_POST['charset'])) : 'auto'; - if ($val != 'url' && function_exists('mb_convert_encoding')) + if ($val !== 'url' && MB_ENABLED === TRUE) { - $_POST[$val] = mb_convert_encoding($_POST[$val], $this->charset, $this->data['charset']); + if (MB_ENABLED === TRUE) + { + $_POST[$val] = mb_convert_encoding($_POST[$val], $this->charset, $this->data['charset']); + } + elseif (ICONV_ENABLED === TRUE) + { + $_POST[$val] = @iconv($this->data['charset'], $this->charset.'//IGNORE', $_POST[$val]); + } } - $_POST[$val] = ($val != 'url') ? $this->convert_xml(strip_tags($_POST[$val])) : strip_tags($_POST[$val]); + $_POST[$val] = ($val !== 'url') ? $this->convert_xml(strip_tags($_POST[$val])) : strip_tags($_POST[$val]); - if ($val == 'excerpt') + if ($val === 'excerpt') { $_POST['excerpt'] = $this->limit_characters($_POST['excerpt']); } @@ -170,18 +230,16 @@ class CI_Trackback { /** * Send Trackback Error Message * - * Allows custom errors to be set. By default it + * Allows custom errors to be set. By default it * sends the "incomplete information" error, as that's * the most common one. * - * @access public * @param string * @return void */ - function send_error($message = 'Incomplete Information') + public function send_error($message = 'Incomplete Information') { - echo "\n\n1\n".$message."\n"; - exit; + exit('\n\n1\n".$message."\n"); } // -------------------------------------------------------------------- @@ -192,13 +250,11 @@ class CI_Trackback { * This should be called when a trackback has been * successfully received and inserted. * - * @access public * @return void */ - function send_success() + public function send_success() { - echo "\n\n0\n"; - exit; + exit('\n\n0\n"); } // -------------------------------------------------------------------- @@ -206,13 +262,12 @@ class CI_Trackback { /** * Fetch a particular item * - * @access public * @param string * @return string */ - function data($item) + public function data($item) { - return ( ! isset($this->data[$item])) ? '' : $this->data[$item]; + return isset($this->data[$item]) ? $this->data[$item] : ''; } // -------------------------------------------------------------------- @@ -221,14 +276,13 @@ class CI_Trackback { * Process Trackback * * Opens a socket connection and passes the data to - * the server. Returns TRUE on success, FALSE on failure + * the server. Returns TRUE on success, FALSE on failure * - * @access public * @param string * @param string * @return bool */ - function process($url, $data) + public function process($url, $data) { $target = parse_url($url); @@ -240,43 +294,37 @@ class CI_Trackback { } // Build the path - $ppath = ( ! isset($target['path'])) ? $url : $target['path']; - - $path = (isset($target['query']) && $target['query'] != "") ? $ppath.'?'.$target['query'] : $ppath; + $path = isset($target['path']) ? $target['path'] : $url; + empty($target['query']) OR $path .= '?'.$target['query']; // Add the Trackback ID to the data string if ($id = $this->get_id($url)) { - $data = "tb_id=".$id."&".$data; + $data = 'tb_id='.$id.'&'.$data; } // Transfer the data - fputs ($fp, "POST " . $path . " HTTP/1.0\r\n" ); - fputs ($fp, "Host: " . $target['host'] . "\r\n" ); - fputs ($fp, "Content-type: application/x-www-form-urlencoded\r\n" ); - fputs ($fp, "Content-length: " . strlen($data) . "\r\n" ); - fputs ($fp, "Connection: close\r\n\r\n" ); - fputs ($fp, $data); + fputs($fp, 'POST '.$path." HTTP/1.0\r\n"); + fputs($fp, 'Host: '.$target['host']."\r\n"); + fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); + fputs($fp, 'Content-length: '.strlen($data)."\r\n"); + fputs($fp, "Connection: close\r\n\r\n"); + fputs($fp, $data); // Was it successful? - $this->response = ""; + $this->response = ''; while ( ! feof($fp)) { $this->response .= fgets($fp, 128); } @fclose($fp); - - if (stristr($this->response, '0') === FALSE) + if (stripos($this->response, '0') === FALSE) { - $message = 'An unknown error was encountered'; - - if (preg_match("/(.*?)<\/message>/is", $this->response, $match)) - { - $message = trim($match['1']); - } - + $message = preg_match('/(.*?)<\/message>/is', $this->response, $match) + ? trim($match[1]) + : 'An unknown error was encountered'; $this->set_error($message); return FALSE; } @@ -293,32 +341,18 @@ class CI_Trackback { * It takes a string of URLs (separated by comma or * space) and puts each URL into an array * - * @access public * @param string * @return string */ - function extract_urls($urls) + public function extract_urls($urls) { - // Remove the pesky white space and replace with a comma. - $urls = preg_replace("/\s*(\S+)\s*/", "\\1,", $urls); + // Remove the pesky white space and replace with a comma, then replace doubles. + $urls = str_replace(',,', ',', preg_replace('/\s*(\S+)\s*/', '\\1,', $urls)); - // If they use commas get rid of the doubles. - $urls = str_replace(",,", ",", $urls); - - // Remove any comma that might be at the end - if (substr($urls, -1) == ",") - { - $urls = substr($urls, 0, -1); - } - - // Break into an array via commas - $urls = preg_split('/[,]/', $urls); - - // Removes duplicates - $urls = array_unique($urls); + // Break into an array via commas and remove duplicates + $urls = array_unique(preg_split('/[,]/', rtrim($urls, ','))); array_walk($urls, array($this, 'validate_url')); - return $urls; } @@ -329,17 +363,16 @@ class CI_Trackback { * * Simply adds "http://" if missing * - * @access public * @param string - * @return string + * @return void */ - function validate_url($url) + public function validate_url(&$url) { $url = trim($url); - if (substr($url, 0, 4) != "http") + if (stripos($url, 'http') !== 0) { - $url = "http://".$url; + $url = 'http://'.$url; } } @@ -348,13 +381,12 @@ class CI_Trackback { /** * Find the Trackback URL's ID * - * @access public * @param string * @return string */ - function get_id($url) + public function get_id($url) { - $tb_id = ""; + $tb_id = ''; if (strpos($url, '?') !== FALSE) { @@ -378,18 +410,11 @@ class CI_Trackback { if ( ! is_numeric($tb_id)) { - $tb_id = $tb_array[count($tb_array)-2]; + $tb_id = $tb_array[count($tb_array)-2]; } } - if ( ! preg_match ("/^([0-9]+)$/", $tb_id)) - { - return FALSE; - } - else - { - return $tb_id; - } + return ctype_digit((string) $tb_id) ? $tb_id : FALSE; } // -------------------------------------------------------------------- @@ -397,25 +422,20 @@ class CI_Trackback { /** * Convert Reserved XML characters to Entities * - * @access public * @param string * @return string */ - function convert_xml($str) + public function convert_xml($str) { $temp = '__TEMP_AMPERSANDS__'; - $str = preg_replace("/&#(\d+);/", "$temp\\1;", $str); - $str = preg_replace("/&(\w+);/", "$temp\\1;", $str); + $str = preg_replace(array('/&#(\d+);/', '/&(\w+);/'), $temp.'\\1;', $str); - $str = str_replace(array("&","<",">","\"", "'", "-"), - array("&", "<", ">", """, "'", "-"), - $str); + $str = str_replace(array('&', '<', '>', '"', "'", '-'), + array('&', '<', '>', '"', ''', '-'), + $str); - $str = preg_replace("/$temp(\d+);/","&#\\1;",$str); - $str = preg_replace("/$temp(\w+);/","&\\1;", $str); - - return $str; + return preg_replace(array('/'.$temp.'(\d+);/', '/'.$temp.'(\w+);/'), array('&#\\1;', '&\\1;'), $str); } // -------------------------------------------------------------------- @@ -425,33 +445,32 @@ class CI_Trackback { * * Limits the string based on the character count. Will preserve complete words. * - * @access public * @param string - * @param integer + * @param int * @param string * @return string */ - function limit_characters($str, $n = 500, $end_char = '…') + public function limit_characters($str, $n = 500, $end_char = '…') { if (strlen($str) < $n) { return $str; } - $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); + $str = preg_replace('/\s+/', ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); if (strlen($str) <= $n) { return $str; } - $out = ""; + $out = ''; foreach (explode(' ', trim($str)) as $val) { $out .= $val.' '; if (strlen($out) >= $n) { - return trim($out).$end_char; + return rtrim($out).$end_char; } } } @@ -464,11 +483,10 @@ class CI_Trackback { * Converts Hight ascii text and MS Word special chars * to character entities * - * @access public * @param string * @return string */ - function convert_ascii($str) + public function convert_ascii($str) { $count = 1; $out = ''; @@ -484,16 +502,18 @@ class CI_Trackback { } else { - if (count($temp) == 0) + if (count($temp) === 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; - if (count($temp) == $count) + if (count($temp) === $count) { - $number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); + $number = ($count === 3) + ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) + : (($temp[0] % 32) * 64) + ($temp[1] % 64); $out .= '&#'.$number.';'; $count = 1; @@ -510,11 +530,10 @@ class CI_Trackback { /** * Set error message * - * @access public * @param string * @return void */ - function set_error($msg) + public function set_error($msg) { log_message('error', $msg); $this->error_msg[] = $msg; @@ -525,24 +544,13 @@ class CI_Trackback { /** * Show error messages * - * @access public * @param string * @param string * @return string */ - function display_errors($open = '

    ', $close = '

    ') + public function display_errors($open = '

    ', $close = '

    ') { - $str = ''; - foreach ($this->error_msg as $val) - { - $str .= $open.$val.$close; - } - - return $str; + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; } } -// END Trackback Class - -/* End of file Trackback.php */ -/* Location: ./system/libraries/Trackback.php */ \ No newline at end of file diff --git a/system/libraries/Typography.php b/system/libraries/Typography.php old mode 100755 new mode 100644 index b30582d..e67138c --- a/system/libraries/Typography.php +++ b/system/libraries/Typography.php @@ -1,48 +1,94 @@ - tags - var $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul'; + /** + * Block level elements that should not be wrapped inside

    tags + * + * @var string + */ + public $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul'; - // Elements that should not have

    and
    tags within them. - var $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d'; + /** + * Elements that should not have

    and
    tags within them. + * + * @var string + */ + public $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d'; - // Tags we want the parser to completely ignore when splitting the string. - var $inline_elements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var'; + /** + * Tags we want the parser to completely ignore when splitting the string. + * + * @var string + */ + public $inline_elements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var'; - // array of block level elements that require inner content to be within another block level element - var $inner_block_required = array('blockquote'); + /** + * array of block level elements that require inner content to be within another block level element + * + * @var array + */ + public $inner_block_required = array('blockquote'); - // the last block element parsed - var $last_block_element = ''; + /** + * the last block element parsed + * + * @var string + */ + public $last_block_element = ''; - // whether or not to protect quotes within { curly braces } - var $protect_braced_quotes = FALSE; + /** + * whether or not to protect quotes within { curly braces } + * + * @var bool + */ + public $protect_braced_quotes = FALSE; /** * Auto Typography @@ -55,14 +101,13 @@ class CI_Typography { * - Converts double dashes into em-dashes. * - Converts two spaces into entities * - * @access public * @param string * @param bool whether to reduce more then two consecutive newlines to two * @return string */ - function auto_typography($str, $reduce_linebreaks = FALSE) + public function auto_typography($str, $reduce_linebreaks = FALSE) { - if ($str == '') + if ($str === '') { return ''; } @@ -82,15 +127,12 @@ class CI_Typography { // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed $html_comments = array(); - if (strpos($str, '", - "'", - "<", - ">", - '"', - '&', - '$', - '=', - ';', - '?', - '/', - "%20", - "%22", - "%3c", // < - "%253c", // < - "%3e", // > - "%0e", // > - "%28", // ( - "%29", // ) - "%2528", // ( - "%26", // & - "%24", // $ - "%3f", // ? - "%3b", // ; - "%3d" // = - ); - - $filename = str_replace($bad, '', $filename); - - return stripslashes($filename); + $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); + return '.'.$ext; } // -------------------------------------------------------------------- @@ -789,7 +1039,8 @@ class CI_Upload { /** * Limit the File Name Length * - * @param string + * @param string $filename + * @param int $length * @return string */ public function limit_filename_length($filename, $length) @@ -819,7 +1070,7 @@ class CI_Upload { * 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 void + * @return string */ public function do_xss_clean() { @@ -830,23 +1081,34 @@ class CI_Upload { return FALSE; } - if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '') + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) { - $current = ini_get('memory_limit') * 1024 * 1024; + $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; + } + } - // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output - // into scientific notation. number_format() ensures this number is an integer - // http://bugs.php.net/bug.php?id=43053 - - $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', ''); - - ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net + $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 + // 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. @@ -864,14 +1126,8 @@ class CI_Upload { // ]/i', $opening_bytes)) - { - return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good - } - else - { - return FALSE; - } + // if it's an image or no "triggers" detected in the first 256 bytes - we're good + return ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes); } if (($data = @file_get_contents($file)) === FALSE) @@ -879,8 +1135,7 @@ class CI_Upload { return FALSE; } - $CI =& get_instance(); - return $CI->security->xss_clean($data, TRUE); + return $this->_CI->security->xss_clean($data, TRUE); } // -------------------------------------------------------------------- @@ -888,29 +1143,22 @@ class CI_Upload { /** * Set an error message * - * @param string - * @return void + * @param string $msg + * @return CI_Upload */ - public function set_error($msg) + public function set_error($msg, $log_level = 'error') { - $CI =& get_instance(); - $CI->lang->load('upload'); + $this->_CI->lang->load('upload'); - if (is_array($msg)) + is_array($msg) OR $msg = array($msg); + foreach ($msg as $val) { - foreach ($msg as $val) - { - $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val); - $this->error_msg[] = $msg; - log_message('error', $msg); - } - } - else - { - $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg); + $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); $this->error_msg[] = $msg; - log_message('error', $msg); + log_message($log_level, $msg); } + + return $this; } // -------------------------------------------------------------------- @@ -918,56 +1166,13 @@ class CI_Upload { /** * Display the error message * - * @param string - * @param string + * @param string $open + * @param string $close * @return string */ public function display_errors($open = '

    ', $close = '

    ') { - $str = ''; - foreach ($this->error_msg as $val) - { - $str .= $open.$val.$close; - } - - return $str; - } - - // -------------------------------------------------------------------- - - /** - * List of Mime Types - * - * This is a list of mime types. We use it to validate - * the "allowed types" set by the developer - * - * @param string - * @return string - */ - public function mimes_types($mime) - { - global $mimes; - - if (count($this->mimes) == 0) - { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); - } - elseif (is_file(APPPATH.'config/mimes.php')) - { - include(APPPATH.'config//mimes.php'); - } - else - { - return FALSE; - } - - $this->mimes = $mimes; - unset($mimes); - } - - return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime]; + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; } // -------------------------------------------------------------------- @@ -975,38 +1180,24 @@ class CI_Upload { /** * Prep Filename * - * Prevents possible script execution from Apache's handling of files multiple extensions - * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * Prevents possible script execution from Apache's handling + * of files' multiple extensions. * - * @param string + * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext + * + * @param string $filename * @return string */ protected function _prep_filename($filename) { - if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*') + if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) { return $filename; } - $parts = explode('.', $filename); - $ext = array_pop($parts); - $filename = array_shift($parts); - - foreach ($parts as $part) - { - if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE) - { - $filename .= '.'.$part.'_'; - } - else - { - $filename .= '.'.$part; - } - } - - $filename .= '.'.$ext; - - return $filename; + $ext = substr($filename, $ext_pos); + $filename = substr($filename, 0, $ext_pos); + return str_replace('.', '_', $filename).$ext; } // -------------------------------------------------------------------- @@ -1017,7 +1208,7 @@ class CI_Upload { * Detects the (actual) MIME type of the uploaded file, if possible. * The input array is expected to be $_FILES[$field] * - * @param array + * @param array $file * @return void */ protected function _file_mime_type($file) @@ -1025,14 +1216,17 @@ class CI_Upload { // 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 + /** + * Fileinfo extension - most reliable method * - * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the - * more convenient FILEINFO_MIME_TYPE flag doesn't exist. + * 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); + $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']); @@ -1059,16 +1253,18 @@ class CI_Upload { * 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_exists() checks + * due to security concerns, hence the function_usable() checks */ if (DIRECTORY_SEPARATOR !== '\\') { - $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1'; + $cmd = function_exists('escapeshellarg') + ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1' + : 'file --brief --mime '.$file['tmp_name'].' 2>&1'; - if (function_exists('exec')) + 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 neeed the last line, which is the actual return value of exec(), and as such - it overwrites + * 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. */ @@ -1080,7 +1276,7 @@ class CI_Upload { } } - if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec')) + if ( ! ini_get('safe_mode') && function_usable('shell_exec')) { $mime = @shell_exec($cmd); if (strlen($mime) > 0) @@ -1094,7 +1290,7 @@ class CI_Upload { } } - if (function_exists('popen')) + if (function_usable('popen')) { $proc = @popen($cmd, 'r'); if (is_resource($proc)) @@ -1114,7 +1310,7 @@ class CI_Upload { } } - // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) + // 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']); @@ -1127,10 +1323,4 @@ class CI_Upload { $this->file_type = $file['type']; } - // -------------------------------------------------------------------- - } -// END Upload Class - -/* End of file Upload.php */ -/* Location: ./system/libraries/Upload.php */ diff --git a/system/libraries/User_agent.php b/system/libraries/User_agent.php old mode 100755 new mode 100644 index 9b0d871..a70511f --- a/system/libraries/User_agent.php +++ b/system/libraries/User_agent.php @@ -1,77 +1,187 @@ -_load_agent_file(); + if (isset($_SERVER['HTTP_USER_AGENT'])) { $this->agent = trim($_SERVER['HTTP_USER_AGENT']); + $this->_compile_data(); } - if ( ! is_null($this->agent)) - { - if ($this->_load_agent_file()) - { - $this->_compile_data(); - } - } - - log_message('debug', "User Agent Class Initialized"); + log_message('info', 'User Agent Class Initialized'); } // -------------------------------------------------------------------- @@ -79,20 +189,22 @@ class CI_User_agent { /** * Compile the User Agent Data * - * @access private * @return bool */ - private function _load_agent_file() + protected function _load_agent_file() { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php'); - } - elseif (is_file(APPPATH.'config/user_agents.php')) + if (($found = file_exists(APPPATH.'config/user_agents.php'))) { include(APPPATH.'config/user_agents.php'); } - else + + if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) + { + include(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php'); + $found = TRUE; + } + + if ($found !== TRUE) { return FALSE; } @@ -135,10 +247,9 @@ class CI_User_agent { /** * Compile the User Agent Data * - * @access private * @return bool */ - private function _compile_data() + protected function _compile_data() { $this->_set_platform(); @@ -156,23 +267,24 @@ class CI_User_agent { /** * Set the Platform * - * @access private - * @return mixed + * @return bool */ - private function _set_platform() + protected function _set_platform() { - if (is_array($this->platforms) AND count($this->platforms) > 0) + if (is_array($this->platforms) && count($this->platforms) > 0) { foreach ($this->platforms as $key => $val) { - if (preg_match("|".preg_quote($key)."|i", $this->agent)) + if (preg_match('|'.preg_quote($key).'|i', $this->agent)) { $this->platform = $val; return TRUE; } } } + $this->platform = 'Unknown Platform'; + return FALSE; } // -------------------------------------------------------------------- @@ -180,16 +292,15 @@ class CI_User_agent { /** * Set the Browser * - * @access private * @return bool */ - private function _set_browser() + protected function _set_browser() { - if (is_array($this->browsers) AND count($this->browsers) > 0) + if (is_array($this->browsers) && count($this->browsers) > 0) { foreach ($this->browsers as $key => $val) { - if (preg_match("|".preg_quote($key).".*?([0-9\.]+)|i", $this->agent, $match)) + if (preg_match('|'.$key.'.*?([0-9\.]+)|i', $this->agent, $match)) { $this->is_browser = TRUE; $this->version = $match[1]; @@ -199,6 +310,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -207,23 +319,24 @@ class CI_User_agent { /** * Set the Robot * - * @access private * @return bool */ - private function _set_robot() + protected function _set_robot() { - if (is_array($this->robots) AND count($this->robots) > 0) + if (is_array($this->robots) && count($this->robots) > 0) { foreach ($this->robots as $key => $val) { - if (preg_match("|".preg_quote($key)."|i", $this->agent)) + if (preg_match('|'.preg_quote($key).'|i', $this->agent)) { $this->is_robot = TRUE; $this->robot = $val; + $this->_set_mobile(); return TRUE; } } } + return FALSE; } @@ -232,16 +345,15 @@ class CI_User_agent { /** * Set the Mobile Device * - * @access private * @return bool */ - private function _set_mobile() + protected function _set_mobile() { - if (is_array($this->mobiles) AND count($this->mobiles) > 0) + if (is_array($this->mobiles) && count($this->mobiles) > 0) { foreach ($this->mobiles as $key => $val) { - if (FALSE !== (strpos(strtolower($this->agent), $key))) + if (FALSE !== (stripos($this->agent, $key))) { $this->is_mobile = TRUE; $this->mobile = $val; @@ -249,6 +361,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -257,19 +370,16 @@ class CI_User_agent { /** * Set the accepted languages * - * @access private * @return void */ - private function _set_languages() + protected function _set_languages() { - if ((count($this->languages) == 0) AND isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) AND $_SERVER['HTTP_ACCEPT_LANGUAGE'] != '') + if ((count($this->languages) === 0) && ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { - $languages = preg_replace('/(;q=[0-9\.]+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE']))); - - $this->languages = explode(',', $languages); + $this->languages = explode(',', preg_replace('/(;\s?q=[0-9\.]+)|\s/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])))); } - if (count($this->languages) == 0) + if (count($this->languages) === 0) { $this->languages = array('Undefined'); } @@ -280,19 +390,16 @@ class CI_User_agent { /** * Set the accepted character sets * - * @access private * @return void */ - private function _set_charsets() + protected function _set_charsets() { - if ((count($this->charsets) == 0) AND isset($_SERVER['HTTP_ACCEPT_CHARSET']) AND $_SERVER['HTTP_ACCEPT_CHARSET'] != '') + if ((count($this->charsets) === 0) && ! empty($_SERVER['HTTP_ACCEPT_CHARSET'])) { - $charsets = preg_replace('/(;q=.+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET']))); - - $this->charsets = explode(',', $charsets); + $this->charsets = explode(',', preg_replace('/(;\s?q=.+)|\s/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])))); } - if (count($this->charsets) == 0) + if (count($this->charsets) === 0) { $this->charsets = array('Undefined'); } @@ -303,7 +410,7 @@ class CI_User_agent { /** * Is Browser * - * @access public + * @param string $key * @return bool */ public function is_browser($key = NULL) @@ -320,7 +427,7 @@ class CI_User_agent { } // Check for a specific browser - return array_key_exists($key, $this->browsers) AND $this->browser === $this->browsers[$key]; + return (isset($this->browsers[$key]) && $this->browser === $this->browsers[$key]); } // -------------------------------------------------------------------- @@ -328,7 +435,7 @@ class CI_User_agent { /** * Is Robot * - * @access public + * @param string $key * @return bool */ public function is_robot($key = NULL) @@ -345,7 +452,7 @@ class CI_User_agent { } // Check for a specific robot - return array_key_exists($key, $this->robots) AND $this->robot === $this->robots[$key]; + return (isset($this->robots[$key]) && $this->robot === $this->robots[$key]); } // -------------------------------------------------------------------- @@ -353,7 +460,7 @@ class CI_User_agent { /** * Is Mobile * - * @access public + * @param string $key * @return bool */ public function is_mobile($key = NULL) @@ -370,7 +477,7 @@ class CI_User_agent { } // Check for a specific robot - return array_key_exists($key, $this->mobiles) AND $this->mobile === $this->mobiles[$key]; + return (isset($this->mobiles[$key]) && $this->mobile === $this->mobiles[$key]); } // -------------------------------------------------------------------- @@ -378,16 +485,26 @@ class CI_User_agent { /** * Is this a referral from another site? * - * @access public * @return bool */ public function is_referral() { - if ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') + if ( ! isset($this->referer)) { - return FALSE; + if (empty($_SERVER['HTTP_REFERER'])) + { + $this->referer = FALSE; + } + else + { + $referer_host = @parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST); + $own_host = parse_url(config_item('base_url'), PHP_URL_HOST); + + $this->referer = ($referer_host && $referer_host !== $own_host); + } } - return TRUE; + + return $this->referer; } // -------------------------------------------------------------------- @@ -395,7 +512,6 @@ class CI_User_agent { /** * Agent String * - * @access public * @return string */ public function agent_string() @@ -408,7 +524,6 @@ class CI_User_agent { /** * Get Platform * - * @access public * @return string */ public function platform() @@ -421,7 +536,6 @@ class CI_User_agent { /** * Get Browser Name * - * @access public * @return string */ public function browser() @@ -434,7 +548,6 @@ class CI_User_agent { /** * Get the Browser Version * - * @access public * @return string */ public function version() @@ -447,7 +560,6 @@ class CI_User_agent { /** * Get The Robot Name * - * @access public * @return string */ public function robot() @@ -459,7 +571,6 @@ class CI_User_agent { /** * Get the Mobile Device * - * @access public * @return string */ public function mobile() @@ -472,12 +583,11 @@ class CI_User_agent { /** * Get the referrer * - * @access public * @return bool */ public function referrer() { - return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? '' : trim($_SERVER['HTTP_REFERER']); + return empty($_SERVER['HTTP_REFERER']) ? '' : trim($_SERVER['HTTP_REFERER']); } // -------------------------------------------------------------------- @@ -485,12 +595,11 @@ class CI_User_agent { /** * Get the accepted languages * - * @access public * @return array */ public function languages() { - if (count($this->languages) == 0) + if (count($this->languages) === 0) { $this->_set_languages(); } @@ -503,12 +612,11 @@ class CI_User_agent { /** * Get the accepted Character Sets * - * @access public * @return array */ public function charsets() { - if (count($this->charsets) == 0) + if (count($this->charsets) === 0) { $this->_set_charsets(); } @@ -521,12 +629,12 @@ class CI_User_agent { /** * Test for a particular language * - * @access public + * @param string $lang * @return bool */ public function accept_lang($lang = 'en') { - return (in_array(strtolower($lang), $this->languages(), TRUE)); + return in_array(strtolower($lang), $this->languages(), TRUE); } // -------------------------------------------------------------------- @@ -534,16 +642,40 @@ class CI_User_agent { /** * Test for a particular character set * - * @access public + * @param string $charset * @return bool */ public function accept_charset($charset = 'utf-8') { - return (in_array(strtolower($charset), $this->charsets(), TRUE)); + return in_array(strtolower($charset), $this->charsets(), TRUE); + } + + // -------------------------------------------------------------------- + + /** + * Parse a custom user-agent string + * + * @param string $string + * @return void + */ + public function parse($string) + { + // Reset values + $this->is_browser = FALSE; + $this->is_robot = FALSE; + $this->is_mobile = FALSE; + $this->browser = ''; + $this->version = ''; + $this->mobile = ''; + $this->robot = ''; + + // Set the new user-agent string and parse it, unless empty + $this->agent = $string; + + if ( ! empty($string)) + { + $this->_compile_data(); + } } } - - -/* End of file User_agent.php */ -/* Location: ./system/libraries/User_agent.php */ \ No newline at end of file diff --git a/system/libraries/Xmlrpc.php b/system/libraries/Xmlrpc.php old mode 100755 new mode 100644 index f0f53ce..690b245 --- a/system/libraries/Xmlrpc.php +++ b/system/libraries/Xmlrpc.php @@ -1,24 +1,47 @@ -xmlrpcName = $this->xmlrpcName; $this->xmlrpc_backslash = chr(92).chr(92); // Types for info sent back and forth @@ -85,54 +276,56 @@ class CI_Xmlrpc { $this->xmlrpcBase64 => '1', $this->xmlrpcArray => '2', $this->xmlrpcStruct => '3' - ); + ); // Array of Valid Parents for Various XML-RPC elements - $this->valid_parents = array('BOOLEAN' => array('VALUE'), - 'I4' => array('VALUE'), - 'INT' => array('VALUE'), - 'STRING' => array('VALUE'), - 'DOUBLE' => array('VALUE'), - 'DATETIME.ISO8601' => array('VALUE'), - 'BASE64' => array('VALUE'), - 'ARRAY' => array('VALUE'), - 'STRUCT' => array('VALUE'), - 'PARAM' => array('PARAMS'), - 'METHODNAME' => array('METHODCALL'), - 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), - 'MEMBER' => array('STRUCT'), - 'NAME' => array('MEMBER'), - 'DATA' => array('ARRAY'), - 'FAULT' => array('METHODRESPONSE'), - 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT') - ); - + $this->valid_parents = array('BOOLEAN' => array('VALUE'), + 'I4' => array('VALUE'), + 'INT' => array('VALUE'), + 'STRING' => array('VALUE'), + 'DOUBLE' => array('VALUE'), + 'DATETIME.ISO8601' => array('VALUE'), + 'BASE64' => array('VALUE'), + 'ARRAY' => array('VALUE'), + 'STRUCT' => array('VALUE'), + 'PARAM' => array('PARAMS'), + 'METHODNAME' => array('METHODCALL'), + 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), + 'MEMBER' => array('STRUCT'), + 'NAME' => array('MEMBER'), + 'DATA' => array('ARRAY'), + 'FAULT' => array('METHODRESPONSE'), + 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT') + ); // XML-RPC Responses $this->xmlrpcerr['unknown_method'] = '1'; $this->xmlrpcstr['unknown_method'] = 'This is not a known method for this XML-RPC Server'; $this->xmlrpcerr['invalid_return'] = '2'; - $this->xmlrpcstr['invalid_return'] = 'The XML data received was either invalid or not in the correct form for XML-RPC. Turn on debugging to examine the XML data further.'; + $this->xmlrpcstr['invalid_return'] = 'The XML data received was either invalid or not in the correct form for XML-RPC. Turn on debugging to examine the XML data further.'; $this->xmlrpcerr['incorrect_params'] = '3'; $this->xmlrpcstr['incorrect_params'] = 'Incorrect parameters were passed to method'; $this->xmlrpcerr['introspect_unknown'] = '4'; - $this->xmlrpcstr['introspect_unknown'] = "Cannot inspect signature for request: method unknown"; + $this->xmlrpcstr['introspect_unknown'] = 'Cannot inspect signature for request: method unknown'; $this->xmlrpcerr['http_error'] = '5'; $this->xmlrpcstr['http_error'] = "Did not receive a '200 OK' response from remote server."; $this->xmlrpcerr['no_data'] = '6'; - $this->xmlrpcstr['no_data'] ='No data received from server.'; + $this->xmlrpcstr['no_data'] = 'No data received from server.'; $this->initialize($config); - log_message('debug', "XML-RPC Class Initialized"); + log_message('info', 'XML-RPC Class Initialized'); } + // -------------------------------------------------------------------- - //------------------------------------- - // Initialize Prefs - //------------------------------------- - - function initialize($config = array()) + /** + * Initialize + * + * @param array $config + * @return void + */ + public function initialize($config = array()) { if (count($config) > 0) { @@ -145,64 +338,85 @@ class CI_Xmlrpc { } } } - // END - //------------------------------------- - // Take URL and parse it - //------------------------------------- + // -------------------------------------------------------------------- - function server($url, $port=80) + /** + * Parse server URL + * + * @param string $url + * @param int $port + * @param string $proxy + * @param int $proxy_port + * @return void + */ + public function server($url, $port = 80, $proxy = FALSE, $proxy_port = 8080) { - if (substr($url, 0, 4) != "http") + if (stripos($url, 'http') !== 0) { - $url = "http://".$url; + $url = 'http://'.$url; } $parts = parse_url($url); - $path = ( ! isset($parts['path'])) ? '/' : $parts['path']; + if (isset($parts['user'], $parts['pass'])) + { + $parts['host'] = $parts['user'].':'.$parts['pass'].'@'.$parts['host']; + } - if (isset($parts['query']) && $parts['query'] != '') + $path = isset($parts['path']) ? $parts['path'] : '/'; + + if ( ! empty($parts['query'])) { $path .= '?'.$parts['query']; } - $this->client = new XML_RPC_Client($path, $parts['host'], $port); + $this->client = new XML_RPC_Client($path, $parts['host'], $port, $proxy, $proxy_port); } - // END - //------------------------------------- - // Set Timeout - //------------------------------------- + // -------------------------------------------------------------------- - function timeout($seconds=5) + /** + * Set Timeout + * + * @param int $seconds + * @return void + */ + public function timeout($seconds = 5) { - if ( ! is_null($this->client) && is_int($seconds)) + if ($this->client !== NULL && is_int($seconds)) { $this->client->timeout = $seconds; } } - // END - //------------------------------------- - // Set Methods - //------------------------------------- + // -------------------------------------------------------------------- - function method($function) + /** + * Set Methods + * + * @param string $function Method name + * @return void + */ + public function method($function) { $this->method = $function; } - // END - //------------------------------------- - // Take Array of Data and Create Objects - //------------------------------------- + // -------------------------------------------------------------------- - function request($incoming) + /** + * Take Array of Data and Create Objects + * + * @param array $incoming + * @return void + */ + public function request($incoming) { if ( ! is_array($incoming)) { // Send Error + return; } $this->data = array(); @@ -212,49 +426,47 @@ class CI_Xmlrpc { $this->data[$key] = $this->values_parsing($value); } } - // END + // -------------------------------------------------------------------- - //------------------------------------- - // Set Debug - //------------------------------------- - - function set_debug($flag = TRUE) + /** + * Set Debug + * + * @param bool $flag + * @return void + */ + public function set_debug($flag = TRUE) { - $this->debug = ($flag == TRUE) ? TRUE : FALSE; + $this->debug = ($flag === TRUE); } - //------------------------------------- - // Values Parsing - //------------------------------------- + // -------------------------------------------------------------------- - function values_parsing($value, $return = FALSE) + /** + * Values Parsing + * + * @param mixed $value + * @return object + */ + public function values_parsing($value) { if (is_array($value) && array_key_exists(0, $value)) { - if ( ! isset($value['1']) OR ( ! isset($this->xmlrpcTypes[$value['1']]))) + if ( ! isset($value[1], $this->xmlrpcTypes[$value[1]])) { - if (is_array($value[0])) - { - $temp = new XML_RPC_Values($value['0'], 'array'); - } - else - { - $temp = new XML_RPC_Values($value['0'], 'string'); - } - } - elseif (is_array($value['0']) && ($value['1'] == 'struct' OR $value['1'] == 'array')) - { - while (list($k) = each($value['0'])) - { - $value['0'][$k] = $this->values_parsing($value['0'][$k], TRUE); - } - - $temp = new XML_RPC_Values($value['0'], $value['1']); + $temp = new XML_RPC_Values($value[0], (is_array($value[0]) ? 'array' : 'string')); } else { - $temp = new XML_RPC_Values($value['0'], $value['1']); + if (is_array($value[0]) && ($value[1] === 'struct' OR $value[1] === 'array')) + { + foreach (array_keys($value[0]) as $k) + { + $value[0][$k] = $this->values_parsing($value[0][$k]); + } + } + + $temp = new XML_RPC_Values($value[0], $value[1]); } } else @@ -264,132 +476,248 @@ class CI_Xmlrpc { return $temp; } - // END + // -------------------------------------------------------------------- - //------------------------------------- - // Sends XML-RPC Request - //------------------------------------- - - function send_request() + /** + * Sends XML-RPC Request + * + * @return bool + */ + public function send_request() { - $this->message = new XML_RPC_Message($this->method,$this->data); + $this->message = new XML_RPC_Message($this->method, $this->data); $this->message->debug = $this->debug; - if ( ! $this->result = $this->client->send($this->message)) - { - $this->error = $this->result->errstr; - return FALSE; - } - elseif ( ! is_object($this->result->val)) + if ( ! $this->result = $this->client->send($this->message) OR ! is_object($this->result->val)) { $this->error = $this->result->errstr; return FALSE; } $this->response = $this->result->decode(); - return TRUE; } - // END - //------------------------------------- - // Returns Error - //------------------------------------- + // -------------------------------------------------------------------- - function display_error() + /** + * Returns Error + * + * @return string + */ + public function display_error() { return $this->error; } - // END - //------------------------------------- - // Returns Remote Server Response - //------------------------------------- + // -------------------------------------------------------------------- - function display_response() + /** + * Returns Remote Server Response + * + * @return string + */ + public function display_response() { return $this->response; } - // END - //------------------------------------- - // Sends an Error Message for Server Request - //------------------------------------- + // -------------------------------------------------------------------- - function send_error_message($number, $message) + /** + * Sends an Error Message for Server Request + * + * @param int $number + * @param string $message + * @return object + */ + public function send_error_message($number, $message) { - return new XML_RPC_Response('0',$number, $message); + return new XML_RPC_Response(0, $number, $message); } - // END + // -------------------------------------------------------------------- - //------------------------------------- - // Send Response for Server Request - //------------------------------------- - - function send_response($response) + /** + * Send Response for Server Request + * + * @param array $response + * @return object + */ + public function send_response($response) { // $response should be array of values, which will be parsed // based on their data and type into a valid group of XML-RPC values - - $response = $this->values_parsing($response); - - return new XML_RPC_Response($response); + return new XML_RPC_Response($this->values_parsing($response)); } - // END } // END XML_RPC Class - - /** * XML-RPC Client class * * @category XML-RPC - * @author ExpressionEngine Dev Team - * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Client extends CI_Xmlrpc { - var $path = ''; - var $server = ''; - var $port = 80; - var $errno = ''; - var $errstring = ''; - var $timeout = 5; - var $no_multicall = FALSE; + /** + * Path + * + * @var string + */ + public $path = ''; - public function __construct($path, $server, $port=80) + /** + * Server hostname + * + * @var string + */ + public $server = ''; + + /** + * Server port + * + * @var int + */ + public $port = 80; + + /** + * + * Server username + * + * @var string + */ + public $username; + + /** + * Server password + * + * @var string + */ + public $password; + + /** + * Proxy hostname + * + * @var string + */ + public $proxy = FALSE; + + /** + * Proxy port + * + * @var int + */ + public $proxy_port = 8080; + + /** + * Error number + * + * @var string + */ + public $errno = ''; + + /** + * Error message + * + * @var string + */ + public $errstring = ''; + + /** + * Timeout in seconds + * + * @var int + */ + public $timeout = 5; + + /** + * No Multicall flag + * + * @var bool + */ + public $no_multicall = FALSE; + + // -------------------------------------------------------------------- + + /** + * Constructor + * + * @param string $path + * @param object $server + * @param int $port + * @param string $proxy + * @param int $proxy_port + * @return void + */ + public function __construct($path, $server, $port = 80, $proxy = FALSE, $proxy_port = 8080) { parent::__construct(); + $url = parse_url('http://'.$server); + + if (isset($url['user'], $url['pass'])) + { + $this->username = $url['user']; + $this->password = $url['pass']; + } + $this->port = $port; - $this->server = $server; + $this->server = $url['host']; $this->path = $path; + $this->proxy = $proxy; + $this->proxy_port = $proxy_port; } - function send($msg) + // -------------------------------------------------------------------- + + /** + * Send message + * + * @param mixed $msg + * @return object + */ + public function send($msg) { if (is_array($msg)) { // Multi-call disabled - $r = new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'],$this->xmlrpcstr['multicall_recursion']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'], $this->xmlrpcstr['multicall_recursion']); } return $this->sendPayload($msg); } - function sendPayload($msg) + // -------------------------------------------------------------------- + + /** + * Send payload + * + * @param object $msg + * @return object + */ + public function sendPayload($msg) { - $fp = @fsockopen($this->server, $this->port,$this->errno, $this->errstr, $this->timeout); + if ($this->proxy === FALSE) + { + $server = $this->server; + $port = $this->port; + } + else + { + $server = $this->proxy; + $port = $this->proxy_port; + } + + $fp = @fsockopen($server, $port, $this->errno, $this->errstring, $this->timeout); if ( ! is_resource($fp)) { error_log($this->xmlrpcstr['http_error']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'],$this->xmlrpcstr['http_error']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } if (empty($msg->payload)) @@ -399,55 +727,123 @@ class XML_RPC_Client extends CI_Xmlrpc } $r = "\r\n"; - $op = "POST {$this->path} HTTP/1.0$r"; - $op .= "Host: {$this->server}$r"; - $op .= "Content-Type: text/xml$r"; - $op .= "User-Agent: {$this->xmlrpcName}$r"; - $op .= "Content-Length: ".strlen($msg->payload). "$r$r"; - $op .= $msg->payload; + $op = 'POST '.$this->path.' HTTP/1.0'.$r + .'Host: '.$this->server.$r + .'Content-Type: text/xml'.$r + .(isset($this->username, $this->password) ? 'Authorization: Basic '.base64_encode($this->username.':'.$this->password).$r : '') + .'User-Agent: '.$this->xmlrpcName.$r + .'Content-Length: '.strlen($msg->payload).$r.$r + .$msg->payload; + stream_set_timeout($fp, $this->timeout); // set timeout for subsequent operations - if ( ! fputs($fp, $op, strlen($op))) + for ($written = $timestamp = 0, $length = strlen($op); $written < $length; $written += $result) + { + if (($result = fwrite($fp, substr($op, $written))) === FALSE) + { + break; + } + // See https://bugs.php.net/bug.php?id=39598 and http://php.net/manual/en/function.fwrite.php#96951 + elseif ($result === 0) + { + if ($timestamp === 0) + { + $timestamp = time(); + } + elseif ($timestamp < (time() - $this->timeout)) + { + $result = FALSE; + break; + } + } + else + { + $timestamp = 0; + } + } + + if ($result === FALSE) { error_log($this->xmlrpcstr['http_error']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } + $resp = $msg->parseResponse($fp); fclose($fp); return $resp; } -} // end class XML_RPC_Client - +} // END XML_RPC_Client Class /** * XML-RPC Response class * * @category XML-RPC - * @author ExpressionEngine Dev Team - * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Response { - var $val = 0; - var $errno = 0; - var $errstr = ''; - var $headers = array(); - var $xss_clean = TRUE; + /** + * Value + * + * @var mixed + */ + public $val = 0; + + /** + * Error number + * + * @var int + */ + public $errno = 0; + + /** + * Error message + * + * @var string + */ + public $errstr = ''; + + /** + * Headers list + * + * @var array + */ + public $headers = array(); + + /** + * XSS Filter flag + * + * @var bool + */ + public $xss_clean = TRUE; + + // -------------------------------------------------------------------- + + /** + * Constructor + * + * @param mixed $val + * @param int $code + * @param string $fstr + * @return void + */ public function __construct($val, $code = 0, $fstr = '') { - if ($code != 0) + if ($code !== 0) { // error $this->errno = $code; - $this->errstr = htmlentities($fstr); + $this->errstr = htmlspecialchars($fstr, + (is_php('5.4') ? ENT_XML1 | ENT_NOQUOTES : ENT_NOQUOTES), + 'UTF-8'); } - else if ( ! is_object($val)) + elseif ( ! is_object($val)) { // programmer error, not an object - error_log("Invalid type '" . gettype($val) . "' (value: $val) passed to XML_RPC_Response. Defaulting to empty value."); + error_log("Invalid type '".gettype($val)."' (value: ".$val.') passed to XML_RPC_Response. Defaulting to empty value.'); $this->val = new XML_RPC_Values(); } else @@ -456,172 +852,234 @@ class XML_RPC_Response } } - function faultCode() + // -------------------------------------------------------------------- + + /** + * Fault code + * + * @return int + */ + public function faultCode() { return $this->errno; } - function faultString() + // -------------------------------------------------------------------- + + /** + * Fault string + * + * @return string + */ + public function faultString() { return $this->errstr; } - function value() + // -------------------------------------------------------------------- + + /** + * Value + * + * @return mixed + */ + public function value() { return $this->val; } - function prepare_response() + // -------------------------------------------------------------------- + + /** + * Prepare response + * + * @return string xml + */ + public function prepare_response() { - $result = "\n"; - if ($this->errno) - { - $result .= ' + return "\n" + .($this->errno + ? ' faultCode - ' . $this->errno . ' + '.$this->errno.' faultString - ' . $this->errstr . ' + '.$this->errstr.' -'; - } - else - { - $result .= "\n\n" . - $this->val->serialize_class() . - "\n"; - } - $result .= "\n"; - return $result; +' + : "\n\n".$this->val->serialize_class()."\n") + ."\n"; } - function decode($array=FALSE) + // -------------------------------------------------------------------- + + /** + * Decode + * + * @param mixed $array + * @return array + */ + public function decode($array = NULL) { $CI =& get_instance(); - - if ($array !== FALSE && is_array($array)) + + if (is_array($array)) { - while (list($key) = each($array)) + foreach ($array as $key => &$value) { - if (is_array($array[$key])) + if (is_array($value)) { - $array[$key] = $this->decode($array[$key]); + $array[$key] = $this->decode($value); } - else + elseif ($this->xss_clean) { - $array[$key] = ($this->xss_clean) ? $CI->security->xss_clean($array[$key]) : $array[$key]; + $array[$key] = $CI->security->xss_clean($value); } } - $result = $array; + return $array; } - else - { - $result = $this->xmlrpc_decoder($this->val); - if (is_array($result)) - { - $result = $this->decode($result); - } - else - { - $result = ($this->xss_clean) ? $CI->security->xss_clean($result) : $result; - } + $result = $this->xmlrpc_decoder($this->val); + + if (is_array($result)) + { + $result = $this->decode($result); + } + elseif ($this->xss_clean) + { + $result = $CI->security->xss_clean($result); } return $result; } + // -------------------------------------------------------------------- - - //------------------------------------- - // XML-RPC Object to PHP Types - //------------------------------------- - - function xmlrpc_decoder($xmlrpc_val) + /** + * XML-RPC Object to PHP Types + * + * @param object + * @return array + */ + public function xmlrpc_decoder($xmlrpc_val) { $kind = $xmlrpc_val->kindOf(); - if ($kind == 'scalar') + if ($kind === 'scalar') { return $xmlrpc_val->scalarval(); } - elseif ($kind == 'array') + elseif ($kind === 'array') { reset($xmlrpc_val->me); - list($a,$b) = each($xmlrpc_val->me); - $size = count($b); - + $b = current($xmlrpc_val->me); $arr = array(); - for ($i = 0; $i < $size; $i++) + for ($i = 0, $size = count($b); $i < $size; $i++) { $arr[] = $this->xmlrpc_decoder($xmlrpc_val->me['array'][$i]); } return $arr; } - elseif ($kind == 'struct') + elseif ($kind === 'struct') { reset($xmlrpc_val->me['struct']); $arr = array(); - while (list($key,$value) = each($xmlrpc_val->me['struct'])) + foreach ($xmlrpc_val->me['struct'] as $key => &$value) { $arr[$key] = $this->xmlrpc_decoder($value); } + return $arr; } } + // -------------------------------------------------------------------- - //------------------------------------- - // ISO-8601 time to server or UTC time - //------------------------------------- - - function iso8601_decode($time, $utc=0) + /** + * ISO-8601 time to server or UTC time + * + * @param string + * @param bool + * @return int unix timestamp + */ + public function iso8601_decode($time, $utc = FALSE) { - // return a timet in the localtime, or UTC + // Return a time in the localtime, or UTC $t = 0; if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $time, $regs)) { - $fnc = ($utc == 1) ? 'gmmktime' : 'mktime'; + $fnc = ($utc === TRUE) ? 'gmmktime' : 'mktime'; $t = $fnc($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } return $t; } -} // End Response Class - - +} // END XML_RPC_Response Class /** * XML-RPC Message class * * @category XML-RPC - * @author ExpressionEngine Dev Team - * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Message extends CI_Xmlrpc { - var $payload; - var $method_name; - var $params = array(); - var $xh = array(); - public function __construct($method, $pars=0) + /** + * Payload + * + * @var string + */ + public $payload; + + /** + * Method name + * + * @var string + */ + public $method_name; + + /** + * Parameter list + * + * @var array + */ + public $params = array(); + + /** + * XH? + * + * @var array + */ + public $xh = array(); + + // -------------------------------------------------------------------- + + /** + * Constructor + * + * @param string $method + * @param array $pars + * @return void + */ + public function __construct($method, $pars = FALSE) { parent::__construct(); $this->method_name = $method; if (is_array($pars) && count($pars) > 0) { - for ($i=0; $iparams[] = $pars[$i]; @@ -629,17 +1087,20 @@ class XML_RPC_Message extends CI_Xmlrpc } } - //------------------------------------- - // Create Payload to Send - //------------------------------------- + // -------------------------------------------------------------------- - function createPayload() + /** + * Create Payload to Send + * + * @return void + */ + public function createPayload() { - $this->payload = "\r\n\r\n"; - $this->payload .= '' . $this->method_name . "\r\n"; - $this->payload .= "\r\n"; + $this->payload = '\r\n\r\n" + .''.$this->method_name."\r\n" + ."\r\n"; - for ($i=0; $iparams); $i++) + for ($i = 0, $c = count($this->params); $i < $c; $i++) { // $p = XML_RPC_Values $p = $this->params[$i]; @@ -649,11 +1110,15 @@ class XML_RPC_Message extends CI_Xmlrpc $this->payload .= "\r\n\r\n"; } - //------------------------------------- - // Parse External XML-RPC Server's Response - //------------------------------------- + // -------------------------------------------------------------------- - function parseResponse($fp) + /** + * Parse External XML-RPC Server's Response + * + * @param resource + * @return object + */ + public function parseResponse($fp) { $data = ''; @@ -662,65 +1127,48 @@ class XML_RPC_Message extends CI_Xmlrpc $data .= $datum; } - //------------------------------------- - // DISPLAY HTTP CONTENT for DEBUGGING - //------------------------------------- - + // Display HTTP content for debugging if ($this->debug === TRUE) { - echo "
    ";
    -			echo "---DATA---\n" . htmlspecialchars($data) . "\n---END DATA---\n\n";
    -			echo "
    "; + echo "
    ---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n
    "; } - //------------------------------------- - // Check for data - //------------------------------------- - - if ($data == "") + // Check for data + if ($data === '') { error_log($this->xmlrpcstr['no_data']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); } - - //------------------------------------- - // Check for HTTP 200 Response - //------------------------------------- - - if (strncmp($data, 'HTTP', 4) == 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data)) + // Check for HTTP 200 Response + if (strpos($data, 'HTTP') === 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data)) { - $errstr= substr($data, 0, strpos($data, "\n")-1); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']. ' (' . $errstr . ')'); - return $r; + $errstr = substr($data, 0, strpos($data, "\n")-1); + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error'].' ('.$errstr.')'); } //------------------------------------- - // Create and Set Up XML Parser + // Create and Set Up XML Parser //------------------------------------- $parser = xml_parser_create($this->xmlrpc_defencoding); - - $this->xh[$parser] = array(); - $this->xh[$parser]['isf'] = 0; - $this->xh[$parser]['ac'] = ''; - $this->xh[$parser]['headers'] = array(); - $this->xh[$parser]['stack'] = array(); - $this->xh[$parser]['valuestack'] = array(); - $this->xh[$parser]['isf_reason'] = 0; + $pname = (string) $parser; + $this->xh[$pname] = array( + 'isf' => 0, + 'ac' => '', + 'headers' => array(), + 'stack' => array(), + 'valuestack' => array(), + 'isf_reason' => 0 + ); xml_set_object($parser, $this); - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); - - //------------------------------------- - // GET HEADERS - //------------------------------------- - + // Get headers $lines = explode("\r\n", $data); while (($line = array_shift($lines))) { @@ -728,87 +1176,67 @@ class XML_RPC_Message extends CI_Xmlrpc { break; } - $this->xh[$parser]['headers'][] = $line; + $this->xh[$pname]['headers'][] = $line; } $data = implode("\r\n", $lines); - - //------------------------------------- - // PARSE XML DATA - //------------------------------------- - - if ( ! xml_parse($parser, $data, count($data))) + // Parse XML data + if ( ! xml_parse($parser, $data, TRUE)) { $errstr = sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser)), - xml_get_current_line_number($parser)); - //error_log($errstr); + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser)); + $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); xml_parser_free($parser); return $r; } xml_parser_free($parser); - // --------------------------------------- - // Got Ourselves Some Badness, It Seems - // --------------------------------------- - - if ($this->xh[$parser]['isf'] > 1) + // Got ourselves some badness, it seems + if ($this->xh[$pname]['isf'] > 1) { if ($this->debug === TRUE) { - echo "---Invalid Return---\n"; - echo $this->xh[$parser]['isf_reason']; - echo "---Invalid Return---\n\n"; + echo "---Invalid Return---\n".$this->xh[$pname]['isf_reason']."---Invalid Return---\n\n"; } - $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$pname]['isf_reason']); } - elseif ( ! is_object($this->xh[$parser]['value'])) + elseif ( ! is_object($this->xh[$pname]['value'])) { - $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$pname]['isf_reason']); } - //------------------------------------- - // DISPLAY XML CONTENT for DEBUGGING - //------------------------------------- - + // Display XML content for debugging if ($this->debug === TRUE) { - echo "
    ";
    +			echo '
    ';
     
    -			if (count($this->xh[$parser]['headers'] > 0))
    +			if (count($this->xh[$pname]['headers']) > 0)
     			{
     				echo "---HEADERS---\n";
    -				foreach ($this->xh[$parser]['headers'] as $header)
    +				foreach ($this->xh[$pname]['headers'] as $header)
     				{
    -					echo "$header\n";
    +					echo $header."\n";
     				}
     				echo "---END HEADERS---\n\n";
     			}
     
    -			echo "---DATA---\n" . htmlspecialchars($data) . "\n---END DATA---\n\n";
    -
    -			echo "---PARSED---\n" ;
    -			var_dump($this->xh[$parser]['value']);
    +			echo "---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n---PARSED---\n";
    +			var_dump($this->xh[$pname]['value']);
     			echo "\n---END PARSED---
    "; } - //------------------------------------- - // SEND RESPONSE - //------------------------------------- - - $v = $this->xh[$parser]['value']; - - if ($this->xh[$parser]['isf']) + // Send response + $v = $this->xh[$pname]['value']; + if ($this->xh[$pname]['isf']) { $errno_v = $v->me['struct']['faultCode']; $errstr_v = $v->me['struct']['faultString']; $errno = $errno_v->scalarval(); - if ($errno == 0) + if ($errno === 0) { // FAULT returned, errno needs to reflect that $errno = -1; @@ -821,10 +1249,12 @@ class XML_RPC_Message extends CI_Xmlrpc $r = new XML_RPC_Response($v); } - $r->headers = $this->xh[$parser]['headers']; + $r->headers = $this->xh[$pname]['headers']; return $r; } + // -------------------------------------------------------------------- + // ------------------------------------ // Begin Return Message Parsing section // ------------------------------------ @@ -839,63 +1269,63 @@ class XML_RPC_Message extends CI_Xmlrpc // stack - array with parent tree of the xml element, // used to validate the nesting of elements - //------------------------------------- - // Start Element Handler - //------------------------------------- + // -------------------------------------------------------------------- - function open_tag($the_parser, $name, $attrs) + /** + * Start Element Handler + * + * @param string + * @param string + * @return void + */ + public function open_tag($the_parser, $name) { + $the_parser = (string) $the_parser; + // If invalid nesting, then return if ($this->xh[$the_parser]['isf'] > 1) return; // Evaluate and check for correct nesting of XML elements - - if (count($this->xh[$the_parser]['stack']) == 0) + if (count($this->xh[$the_parser]['stack']) === 0) { - if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') + if ($name !== 'METHODRESPONSE' && $name !== 'METHODCALL') { $this->xh[$the_parser]['isf'] = 2; $this->xh[$the_parser]['isf_reason'] = 'Top level XML-RPC element is missing'; return; } } - else + // not top level element: see if parent is OK + elseif ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) { - // not top level element: see if parent is OK - if ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) - { - $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "XML-RPC element $name cannot be child of ".$this->xh[$the_parser]['stack'][0]; - return; - } + $this->xh[$the_parser]['isf'] = 2; + $this->xh[$the_parser]['isf_reason'] = 'XML-RPC element '.$name.' cannot be child of '.$this->xh[$the_parser]['stack'][0]; + return; } - switch($name) + switch ($name) { case 'STRUCT': case 'ARRAY': // Creates array for child elements - - $cur_val = array('value' => array(), - 'type' => $name); - + $cur_val = array('value' => array(), 'type' => $name); array_unshift($this->xh[$the_parser]['valuestack'], $cur_val); - break; + break; case 'METHODNAME': case 'NAME': $this->xh[$the_parser]['ac'] = ''; - break; + break; case 'FAULT': $this->xh[$the_parser]['isf'] = 1; - break; + break; case 'PARAM': $this->xh[$the_parser]['value'] = NULL; - break; + break; case 'VALUE': $this->xh[$the_parser]['vt'] = 'value'; $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 1; - break; + break; case 'I4': case 'INT': case 'STRING': @@ -903,70 +1333,76 @@ class XML_RPC_Message extends CI_Xmlrpc case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': - if ($this->xh[$the_parser]['vt'] != 'value') + if ($this->xh[$the_parser]['vt'] !== 'value') { //two data elements inside a value: an error occurred! $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "'Twas a $name element following a ".$this->xh[$the_parser]['vt']." element inside a single value"; + $this->xh[$the_parser]['isf_reason'] = 'There is a '.$name.' element following a ' + .$this->xh[$the_parser]['vt'].' element inside a single value'; return; } $this->xh[$the_parser]['ac'] = ''; - break; + break; case 'MEMBER': // Set name of to nothing to prevent errors later if no is found $this->xh[$the_parser]['valuestack'][0]['name'] = ''; // Set NULL value to check to see if value passed for this param/member $this->xh[$the_parser]['value'] = NULL; - break; + break; case 'DATA': case 'METHODCALL': case 'METHODRESPONSE': case 'PARAMS': // valid elements that add little to processing - break; + break; default: /// An Invalid Element is Found, so we have trouble $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "Invalid XML-RPC element found: $name"; - break; + $this->xh[$the_parser]['isf_reason'] = 'Invalid XML-RPC element found: '.$name; + break; } // Add current element name to stack, to allow validation of nesting array_unshift($this->xh[$the_parser]['stack'], $name); - if ($name != 'VALUE') $this->xh[$the_parser]['lv'] = 0; + $name === 'VALUE' OR $this->xh[$the_parser]['lv'] = 0; } - // END + // -------------------------------------------------------------------- - //------------------------------------- - // End Element Handler - //------------------------------------- - - function closing_tag($the_parser, $name) + /** + * End Element Handler + * + * @param string + * @param string + * @return void + */ + public function closing_tag($the_parser, $name) { + $the_parser = (string) $the_parser; + if ($this->xh[$the_parser]['isf'] > 1) return; // Remove current element from stack and set variable // NOTE: If the XML validates, then we do not have to worry about - // the opening and closing of elements. Nesting is checked on the opening + // the opening and closing of elements. Nesting is checked on the opening // tag so we be safe there as well. $curr_elem = array_shift($this->xh[$the_parser]['stack']); - switch($name) + switch ($name) { case 'STRUCT': case 'ARRAY': $cur_val = array_shift($this->xh[$the_parser]['valuestack']); - $this->xh[$the_parser]['value'] = ( ! isset($cur_val['values'])) ? array() : $cur_val['values']; + $this->xh[$the_parser]['value'] = isset($cur_val['values']) ? $cur_val['values'] : array(); $this->xh[$the_parser]['vt'] = strtolower($name); - break; + break; case 'NAME': $this->xh[$the_parser]['valuestack'][0]['name'] = $this->xh[$the_parser]['ac']; - break; + break; case 'BOOLEAN': case 'I4': case 'INT': @@ -976,63 +1412,46 @@ class XML_RPC_Message extends CI_Xmlrpc case 'BASE64': $this->xh[$the_parser]['vt'] = strtolower($name); - if ($name == 'STRING') + if ($name === 'STRING') { $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } - elseif ($name=='DATETIME.ISO8601') + elseif ($name === 'DATETIME.ISO8601') { $this->xh[$the_parser]['vt'] = $this->xmlrpcDateTime; $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } - elseif ($name=='BASE64') + elseif ($name === 'BASE64') { $this->xh[$the_parser]['value'] = base64_decode($this->xh[$the_parser]['ac']); } - elseif ($name=='BOOLEAN') + elseif ($name === 'BOOLEAN') { // Translated BOOLEAN values to TRUE AND FALSE - if ($this->xh[$the_parser]['ac'] == '1') - { - $this->xh[$the_parser]['value'] = TRUE; - } - else - { - $this->xh[$the_parser]['value'] = FALSE; - } + $this->xh[$the_parser]['value'] = (bool) $this->xh[$the_parser]['ac']; } elseif ($name=='DOUBLE') { // we have a DOUBLE // we must check that only 0123456789-. are characters here - if ( ! preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac'])) - { - $this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND'; - } - else - { - $this->xh[$the_parser]['value'] = (double)$this->xh[$the_parser]['ac']; - } + $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac']) + ? (float) $this->xh[$the_parser]['ac'] + : 'ERROR_NON_NUMERIC_FOUND'; } else { // we have an I4/INT // we must check that only 0123456789- are characters here - if ( ! preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac'])) - { - $this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND'; - } - else - { - $this->xh[$the_parser]['value'] = (int)$this->xh[$the_parser]['ac']; - } + $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac']) + ? (int) $this->xh[$the_parser]['ac'] + : 'ERROR_NON_NUMERIC_FOUND'; } $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 3; // indicate we've found a value - break; + break; case 'VALUE': // This if() detects if no scalar was inside - if ($this->xh[$the_parser]['vt']=='value') + if ($this->xh[$the_parser]['vt'] == 'value') { $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; $this->xh[$the_parser]['vt'] = $this->xmlrpcString; @@ -1041,7 +1460,7 @@ class XML_RPC_Message extends CI_Xmlrpc // build the XML-RPC value out of the data received, and substitute it $temp = new XML_RPC_Values($this->xh[$the_parser]['value'], $this->xh[$the_parser]['vt']); - if (count($this->xh[$the_parser]['valuestack']) && $this->xh[$the_parser]['valuestack'][0]['type'] == 'ARRAY') + if (count($this->xh[$the_parser]['valuestack']) && $this->xh[$the_parser]['valuestack'][0]['type'] === 'ARRAY') { // Array $this->xh[$the_parser]['valuestack'][0]['values'][] = $temp; @@ -1051,57 +1470,64 @@ class XML_RPC_Message extends CI_Xmlrpc // Struct $this->xh[$the_parser]['value'] = $temp; } - break; + break; case 'MEMBER': - $this->xh[$the_parser]['ac']=''; + $this->xh[$the_parser]['ac'] = ''; // If value add to array in the stack for the last element built if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['valuestack'][0]['values'][$this->xh[$the_parser]['valuestack'][0]['name']] = $this->xh[$the_parser]['value']; } - break; + break; case 'DATA': - $this->xh[$the_parser]['ac']=''; - break; + $this->xh[$the_parser]['ac'] = ''; + break; case 'PARAM': if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['params'][] = $this->xh[$the_parser]['value']; } - break; + break; case 'METHODNAME': $this->xh[$the_parser]['method'] = ltrim($this->xh[$the_parser]['ac']); - break; + break; case 'PARAMS': case 'FAULT': case 'METHODCALL': case 'METHORESPONSE': // We're all good kids with nuthin' to do - break; + break; default: - // End of an Invalid Element. Taken care of during the opening tag though - break; + // End of an Invalid Element. Taken care of during the opening tag though + break; } } - //------------------------------------- - // Parses Character Data - //------------------------------------- + // -------------------------------------------------------------------- - function character_data($the_parser, $data) + /** + * Parse character data + * + * @param string + * @param string + * @return void + */ + public function character_data($the_parser, $data) { + $the_parser = (string) $the_parser; + if ($this->xh[$the_parser]['isf'] > 1) return; // XML Fault found already // If a value has not been found - if ($this->xh[$the_parser]['lv'] != 3) + if ($this->xh[$the_parser]['lv'] !== 3) { - if ($this->xh[$the_parser]['lv'] == 1) + if ($this->xh[$the_parser]['lv'] === 1) { $this->xh[$the_parser]['lv'] = 2; // Found a value } - if ( ! @isset($this->xh[$the_parser]['ac'])) + if ( ! isset($this->xh[$the_parser]['ac'])) { $this->xh[$the_parser]['ac'] = ''; } @@ -1110,83 +1536,104 @@ class XML_RPC_Message extends CI_Xmlrpc } } + // -------------------------------------------------------------------- - function addParam($par) { $this->params[]=$par; } + /** + * Add parameter + * + * @param mixed + * @return void + */ + public function addParam($par) + { + $this->params[] = $par; + } - function output_parameters($array=FALSE) + // -------------------------------------------------------------------- + + /** + * Output parameters + * + * @param array $array + * @return array + */ + public function output_parameters(array $array = array()) { $CI =& get_instance(); - - if ($array !== FALSE && is_array($array)) + + if ( ! empty($array)) { - while (list($key) = each($array)) + foreach ($array as $key => &$value) { - if (is_array($array[$key])) + if (is_array($value)) { - $array[$key] = $this->output_parameters($array[$key]); + $array[$key] = $this->output_parameters($value); } - else + elseif ($key !== 'bits' && $this->xss_clean) { // 'bits' is for the MetaWeblog API image bits // @todo - this needs to be made more general purpose - $array[$key] = ($key == 'bits' OR $this->xss_clean == FALSE) ? $array[$key] : $CI->security->xss_clean($array[$key]); + $array[$key] = $CI->security->xss_clean($value); } } - $parameters = $array; + return $array; } - else + + $parameters = array(); + + for ($i = 0, $c = count($this->params); $i < $c; $i++) { - $parameters = array(); + $a_param = $this->decode_message($this->params[$i]); - for ($i = 0; $i < count($this->params); $i++) + if (is_array($a_param)) { - $a_param = $this->decode_message($this->params[$i]); - - if (is_array($a_param)) - { - $parameters[] = $this->output_parameters($a_param); - } - else - { - $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; - } + $parameters[] = $this->output_parameters($a_param); + } + else + { + $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; } } return $parameters; } + // -------------------------------------------------------------------- - function decode_message($param) + /** + * Decode message + * + * @param object + * @return mixed + */ + public function decode_message($param) { $kind = $param->kindOf(); - if ($kind == 'scalar') + if ($kind === 'scalar') { return $param->scalarval(); } - elseif ($kind == 'array') + elseif ($kind === 'array') { reset($param->me); - list($a,$b) = each($param->me); - + $b = current($param->me); $arr = array(); - for($i = 0; $i < count($b); $i++) + for ($i = 0, $c = count($b); $i < $c; $i++) { $arr[] = $this->decode_message($param->me['array'][$i]); } return $arr; } - elseif ($kind == 'struct') + elseif ($kind === 'struct') { reset($param->me['struct']); - $arr = array(); - while (list($key,$value) = each($param->me['struct'])) + foreach ($param->me['struct'] as $key => &$value) { $arr[$key] = $this->decode_message($value); } @@ -1195,33 +1642,51 @@ class XML_RPC_Message extends CI_Xmlrpc } } -} // End XML_RPC_Messages class - - +} // END XML_RPC_Message Class /** * XML-RPC Values class * * @category XML-RPC - * @author ExpressionEngine Dev Team - * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html + * @author EllisLab Dev Team + * @link https://codeigniter.com/user_guide/libraries/xmlrpc.html */ class XML_RPC_Values extends CI_Xmlrpc { - var $me = array(); - var $mytype = 0; + /** + * Value data + * + * @var array + */ + public $me = array(); - public function __construct($val=-1, $type='') + /** + * Value type + * + * @var int + */ + public $mytype = 0; + + // -------------------------------------------------------------------- + + /** + * Constructor + * + * @param mixed $val + * @param string $type + * @return void + */ + public function __construct($val = -1, $type = '') { parent::__construct(); - if ($val != -1 OR $type != '') + if ($val !== -1 OR $type !== '') { - $type = $type == '' ? 'string' : $type; + $type = $type === '' ? 'string' : $type; if ($this->xmlrpcTypes[$type] == 1) { - $this->addScalar($val,$type); + $this->addScalar($val, $type); } elseif ($this->xmlrpcTypes[$type] == 2) { @@ -1234,11 +1699,20 @@ class XML_RPC_Values extends CI_Xmlrpc } } - function addScalar($val, $type='string') + // -------------------------------------------------------------------- + + /** + * Add scalar value + * + * @param scalar + * @param string + * @return int + */ + public function addScalar($val, $type = 'string') { $typeof = $this->xmlrpcTypes[$type]; - if ($this->mytype==1) + if ($this->mytype === 1) { echo 'XML_RPC_Values: scalar can have only one value
    '; return 0; @@ -1250,19 +1724,12 @@ class XML_RPC_Values extends CI_Xmlrpc return 0; } - if ($type == $this->xmlrpcBoolean) + if ($type === $this->xmlrpcBoolean) { - if (strcasecmp($val,'true')==0 OR $val==1 OR ($val==true && strcasecmp($val,'false'))) - { - $val = 1; - } - else - { - $val=0; - } + $val = (int) (strcasecmp($val, 'true') === 0 OR $val === 1 OR ($val === TRUE && strcasecmp($val, 'false'))); } - if ($this->mytype == 2) + if ($this->mytype === 2) { // adding to an array here $ar = $this->me['array']; @@ -1275,14 +1742,23 @@ class XML_RPC_Values extends CI_Xmlrpc $this->me[$type] = $val; $this->mytype = $typeof; } + return 1; } - function addArray($vals) + // -------------------------------------------------------------------- + + /** + * Add array value + * + * @param array + * @return int + */ + public function addArray($vals) { - if ($this->mytype != 0) + if ($this->mytype !== 0) { - echo 'XML_RPC_Values: already initialized as a [' . $this->kindOf() . ']
    '; + echo 'XML_RPC_Values: already initialized as a ['.$this->kindOf().']
    '; return 0; } @@ -1291,11 +1767,19 @@ class XML_RPC_Values extends CI_Xmlrpc return 1; } - function addStruct($vals) + // -------------------------------------------------------------------- + + /** + * Add struct value + * + * @param object + * @return int + */ + public function addStruct($vals) { - if ($this->mytype != 0) + if ($this->mytype !== 0) { - echo 'XML_RPC_Values: already initialized as a [' . $this->kindOf() . ']
    '; + echo 'XML_RPC_Values: already initialized as a ['.$this->kindOf().']
    '; return 0; } $this->mytype = $this->xmlrpcTypes['struct']; @@ -1303,121 +1787,134 @@ class XML_RPC_Values extends CI_Xmlrpc return 1; } - function kindOf() + // -------------------------------------------------------------------- + + /** + * Get value type + * + * @return string + */ + public function kindOf() { - switch($this->mytype) + switch ($this->mytype) { - case 3: - return 'struct'; - break; - case 2: - return 'array'; - break; - case 1: - return 'scalar'; - break; - default: - return 'undef'; + case 3: return 'struct'; + case 2: return 'array'; + case 1: return 'scalar'; + default: return 'undef'; } } - function serializedata($typ, $val) + // -------------------------------------------------------------------- + + /** + * Serialize data + * + * @param string + * @param mixed + * @return string + */ + public function serializedata($typ, $val) { $rs = ''; - switch($this->xmlrpcTypes[$typ]) + switch ($this->xmlrpcTypes[$typ]) { case 3: // struct $rs .= "\n"; reset($val); - while (list($key2, $val2) = each($val)) + foreach ($val as $key2 => &$val2) { - $rs .= "\n{$key2}\n"; - $rs .= $this->serializeval($val2); - $rs .= "\n"; + $rs .= "\n{$key2}\n".$this->serializeval($val2)."\n"; } $rs .= ''; - break; + break; case 2: // array $rs .= "\n\n"; - for($i=0; $i < count($val); $i++) + for ($i = 0, $c = count($val); $i < $c; $i++) { $rs .= $this->serializeval($val[$i]); } - $rs.="\n\n"; + $rs .= "\n\n"; break; case 1: // others switch ($typ) { case $this->xmlrpcBase64: - $rs .= "<{$typ}>" . base64_encode((string)$val) . "\n"; - break; + $rs .= '<'.$typ.'>'.base64_encode( (string) $val).'\n"; + break; case $this->xmlrpcBoolean: - $rs .= "<{$typ}>" . ((bool)$val ? '1' : '0') . "\n"; - break; + $rs .= '<'.$typ.'>'.( (bool) $val ? '1' : '0').'\n"; + break; case $this->xmlrpcString: - $rs .= "<{$typ}>" . htmlspecialchars((string)$val). "\n"; - break; + $rs .= '<'.$typ.'>'.htmlspecialchars( (string) $val).'\n"; + break; default: - $rs .= "<{$typ}>{$val}\n"; - break; + $rs .= '<'.$typ.'>'.$val.'\n"; + break; } default: - break; + break; } + return $rs; } - function serialize_class() + // -------------------------------------------------------------------- + + /** + * Serialize class + * + * @return string + */ + public function serialize_class() { return $this->serializeval($this); } - function serializeval($o) - { - $ar = $o->me; - reset($ar); + // -------------------------------------------------------------------- - list($typ, $val) = each($ar); - $rs = "\n".$this->serializedata($typ, $val)."\n"; - return $rs; + /** + * Serialize value + * + * @param object + * @return string + */ + public function serializeval($o) + { + $array = $o->me; + list($value, $type) = array(reset($array), key($array)); + return "\n".$this->serializedata($type, $value)."\n"; } - function scalarval() + // -------------------------------------------------------------------- + + /** + * Scalar value + * + * @return mixed + */ + public function scalarval() { - reset($this->me); - list($a,$b) = each($this->me); - return $b; + return reset($this->me); } + // -------------------------------------------------------------------- - //------------------------------------- - // Encode time in ISO-8601 form. - //------------------------------------- - - // Useful for sending time in XML-RPC - - function iso8601_encode($time, $utc=0) + /** + * Encode time in ISO-8601 form. + * Useful for sending time in XML-RPC + * + * @param int unix timestamp + * @param bool + * @return string + */ + public function iso8601_encode($time, $utc = FALSE) { - if ($utc == 1) - { - $t = strftime("%Y%m%dT%H:%i:%s", $time); - } - else - { - if (function_exists('gmstrftime')) - $t = gmstrftime("%Y%m%dT%H:%i:%s", $time); - else - $t = strftime("%Y%m%dT%H:%i:%s", $time - date('Z')); - } - return $t; + return ($utc) ? strftime('%Y%m%dT%H:%i:%s', $time) : gmstrftime('%Y%m%dT%H:%i:%s', $time); } -} -// END XML_RPC_Values Class - -/* End of file Xmlrpc.php */ -/* Location: ./system/libraries/Xmlrpc.php */ \ No newline at end of file +} // END XML_RPC_Values Class diff --git a/system/libraries/Xmlrpcs.php b/system/libraries/Xmlrpcs.php old mode 100755 new mode 100644 index d9d53c8..e70b803 --- a/system/libraries/Xmlrpcs.php +++ b/system/libraries/Xmlrpcs.php @@ -1,24 +1,48 @@ -set_system_methods(); @@ -56,7 +104,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc $this->methods = array_merge($this->methods, $config['functions']); } - log_message('debug', "XML-RPC Server Class Initialized"); + log_message('info', 'XML-RPC Server Class Initialized'); } // -------------------------------------------------------------------- @@ -64,11 +112,10 @@ class CI_Xmlrpcs extends CI_Xmlrpc /** * Initialize Prefs and Serve * - * @access public * @param mixed * @return void */ - function initialize($config=array()) + public function initialize($config = array()) { if (isset($config['functions']) && is_array($config['functions'])) { @@ -96,29 +143,28 @@ class CI_Xmlrpcs extends CI_Xmlrpc /** * Setting of System Methods * - * @access public * @return void */ - function set_system_methods() + public function set_system_methods() { $this->methods = array( 'system.listMethods' => array( - 'function' => 'this.listMethods', - 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)), - 'docstring' => 'Returns an array of available methods on this server'), - 'system.methodHelp' => array( - 'function' => 'this.methodHelp', - 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)), - 'docstring' => 'Returns a documentation string for the specified method'), + 'function' => 'this.listMethods', + 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)), + 'docstring' => 'Returns an array of available methods on this server'), + 'system.methodHelp' => array( + 'function' => 'this.methodHelp', + 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)), + 'docstring' => 'Returns a documentation string for the specified method'), 'system.methodSignature' => array( - 'function' => 'this.methodSignature', - 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)), - 'docstring' => 'Returns an array describing the return type and required parameters of a method'), - 'system.multicall' => array( - 'function' => 'this.multicall', - 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)), - 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details') - ); + 'function' => 'this.methodSignature', + 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)), + 'docstring' => 'Returns an array describing the return type and required parameters of a method'), + 'system.multicall' => array( + 'function' => 'this.multicall', + 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)), + 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details') + ); } // -------------------------------------------------------------------- @@ -126,18 +172,15 @@ class CI_Xmlrpcs extends CI_Xmlrpc /** * Main Server Function * - * @access public * @return void */ - function serve() + public function serve() { $r = $this->parseRequest(); - $payload = 'xmlrpc_defencoding.'"?'.'>'."\n"; - $payload .= $this->debug_msg; - $payload .= $r->prepare_response(); + $payload = 'xmlrpc_defencoding.'"?'.'>'."\n".$this->debug_msg.$r->prepare_response(); - header("Content-Type: text/xml"); - header("Content-Length: ".strlen($payload)); + header('Content-Type: text/xml'); + header('Content-Length: '.strlen($payload)); exit($payload); } @@ -146,19 +189,18 @@ class CI_Xmlrpcs extends CI_Xmlrpc /** * Add Method to Class * - * @access public * @param string method name * @param string function * @param string signature * @param string docstring * @return void */ - function add_to_map($methodname, $function, $sig, $doc) + public function add_to_map($methodname, $function, $sig, $doc) { $this->methods[$methodname] = array( - 'function' => $function, - 'signature' => $sig, - 'docstring' => $doc + 'function' => $function, + 'signature' => $sig, + 'docstring' => $doc ); } @@ -167,21 +209,22 @@ class CI_Xmlrpcs extends CI_Xmlrpc /** * Parse Server Request * - * @access public * @param string data * @return object xmlrpc response */ - function parseRequest($data='') + public function parseRequest($data = '') { - global $HTTP_RAW_POST_DATA; - //------------------------------------- // Get Data //------------------------------------- - if ($data == '') + if ($data === '') { - $data = $HTTP_RAW_POST_DATA; + $CI =& get_instance(); + if ($CI->input->method() === 'post') + { + $data = $CI->input->raw_input_stream; + } } //------------------------------------- @@ -189,38 +232,39 @@ class CI_Xmlrpcs extends CI_Xmlrpc //------------------------------------- $parser = xml_parser_create($this->xmlrpc_defencoding); - $parser_object = new XML_RPC_Message("filler"); + $parser_object = new XML_RPC_Message('filler'); + $pname = (string) $parser; - $parser_object->xh[$parser] = array(); - $parser_object->xh[$parser]['isf'] = 0; - $parser_object->xh[$parser]['isf_reason'] = ''; - $parser_object->xh[$parser]['params'] = array(); - $parser_object->xh[$parser]['stack'] = array(); - $parser_object->xh[$parser]['valuestack'] = array(); - $parser_object->xh[$parser]['method'] = ''; + $parser_object->xh[$pname] = array( + 'isf' => 0, + 'isf_reason' => '', + 'params' => array(), + 'stack' => array(), + 'valuestack' => array(), + 'method' => '' + ); xml_set_object($parser, $parser_object); - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); - //------------------------------------- - // PARSE + PROCESS XML DATA + // PARSE + PROCESS XML DATA //------------------------------------- if ( ! xml_parse($parser, $data, 1)) { - // return XML error as a faultCode + // Return XML error as a faultCode $r = new XML_RPC_Response(0, - $this->xmlrpcerrxml + xml_get_error_code($parser), - sprintf('XML error: %s at line %d', + $this->xmlrpcerrxml + xml_get_error_code($parser), + sprintf('XML error: %s at line %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); xml_parser_free($parser); } - elseif ($parser_object->xh[$parser]['isf']) + elseif ($parser_object->xh[$pname]['isf']) { return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); } @@ -228,31 +272,29 @@ class CI_Xmlrpcs extends CI_Xmlrpc { xml_parser_free($parser); - $m = new XML_RPC_Message($parser_object->xh[$parser]['method']); - $plist=''; + $m = new XML_RPC_Message($parser_object->xh[$pname]['method']); + $plist = ''; - for ($i=0; $i < count($parser_object->xh[$parser]['params']); $i++) + for ($i = 0, $c = count($parser_object->xh[$pname]['params']); $i < $c; $i++) { if ($this->debug === TRUE) { - $plist .= "$i - " . print_r(get_object_vars($parser_object->xh[$parser]['params'][$i]), TRUE). ";\n"; + $plist .= $i.' - '.print_r(get_object_vars($parser_object->xh[$pname]['params'][$i]), TRUE).";\n"; } - $m->addParam($parser_object->xh[$parser]['params'][$i]); + $m->addParam($parser_object->xh[$pname]['params'][$i]); } if ($this->debug === TRUE) { - echo "
    ";
    -				echo "---PLIST---\n" . $plist . "\n---PLIST END---\n\n";
    -				echo "
    "; + echo "
    ---PLIST---\n".$plist."\n---PLIST END---\n\n
    "; } $r = $this->_execute($m); } //------------------------------------- - // SET DEBUGGING MESSAGE + // SET DEBUGGING MESSAGE //------------------------------------- if ($this->debug === TRUE) @@ -268,24 +310,23 @@ class CI_Xmlrpcs extends CI_Xmlrpc /** * Executes the Method * - * @access protected * @param object * @return mixed */ - function _execute($m) + protected function _execute($m) { $methName = $m->method_name; // Check to see if it is a system call - $system_call = (strncmp($methName, 'system', 5) == 0) ? TRUE : FALSE; + $system_call = (strpos($methName, 'system') === 0); - if ($this->xss_clean == FALSE) + if ($this->xss_clean === FALSE) { $m->xss_clean = FALSE; } //------------------------------------- - // Valid Method + // Valid Method //------------------------------------- if ( ! isset($this->methods[$methName]['function'])) @@ -294,50 +335,45 @@ class CI_Xmlrpcs extends CI_Xmlrpc } //------------------------------------- - // Check for Method (and Object) + // Check for Method (and Object) //------------------------------------- - $method_parts = explode(".", $this->methods[$methName]['function']); - $objectCall = (isset($method_parts['1']) && $method_parts['1'] != "") ? TRUE : FALSE; + $method_parts = explode('.', $this->methods[$methName]['function']); + $objectCall = ! empty($method_parts[1]); if ($system_call === TRUE) { - if ( ! is_callable(array($this,$method_parts['1']))) + if ( ! is_callable(array($this, $method_parts[1]))) { return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } } - else + elseif (($objectCall && ! is_callable(array($method_parts[0], $method_parts[1]))) + OR ( ! $objectCall && ! is_callable($this->methods[$methName]['function'])) + ) { - if ($objectCall && ! is_callable(array($method_parts['0'],$method_parts['1']))) - { - return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); - } - elseif ( ! $objectCall && ! is_callable($this->methods[$methName]['function'])) - { - return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); - } + return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); } //------------------------------------- - // Checking Methods Signature + // Checking Methods Signature //------------------------------------- if (isset($this->methods[$methName]['signature'])) { $sig = $this->methods[$methName]['signature']; - for ($i=0; $iparams)+1) + if (count($current_sig) === count($m->params)+1) { - for ($n=0; $n < count($m->params); $n++) + for ($n = 0, $mc = count($m->params); $n < $mc; $n++) { $p = $m->params[$n]; - $pt = ($p->kindOf() == 'scalar') ? $p->scalarval() : $p->kindOf(); + $pt = ($p->kindOf() === 'scalar') ? $p->scalarval() : $p->kindOf(); - if ($pt != $current_sig[$n+1]) + if ($pt !== $current_sig[$n+1]) { $pno = $n+1; $wanted = $current_sig[$n+1]; @@ -345,7 +381,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc return new XML_RPC_Response(0, $this->xmlrpcerr['incorrect_params'], $this->xmlrpcstr['incorrect_params'] . - ": Wanted {$wanted}, got {$pt} at param {$pno})"); + ': Wanted '.$wanted.', got '.$pt.' at param '.$pno.')'); } } } @@ -353,45 +389,35 @@ class CI_Xmlrpcs extends CI_Xmlrpc } //------------------------------------- - // Calls the Function + // Calls the Function //------------------------------------- if ($objectCall === TRUE) { - if ($method_parts[0] == "this" && $system_call == TRUE) + if ($method_parts[0] === 'this' && $system_call === TRUE) { return call_user_func(array($this, $method_parts[1]), $m); } - else + elseif ($this->object === FALSE) { - if ($this->object === FALSE) - { - $CI =& get_instance(); - return $CI->$method_parts['1']($m); - } - else - { - return $this->object->$method_parts['1']($m); - //return call_user_func(array(&$method_parts['0'],$method_parts['1']), $m); - } + return get_instance()->{$method_parts[1]}($m); } + + return $this->object->{$method_parts[1]}($m); } - else - { - return call_user_func($this->methods[$methName]['function'], $m); - } + + return call_user_func($this->methods[$methName]['function'], $m); } - + // -------------------------------------------------------------------- /** - * Server Function: List Methods + * Server Function: List Methods * - * @access public * @param mixed * @return object */ - function listMethods($m) + public function listMethods($m) { $v = new XML_RPC_Values(); $output = array(); @@ -403,23 +429,22 @@ class CI_Xmlrpcs extends CI_Xmlrpc foreach ($this->system_methods as $key => $value) { - $output[]= new XML_RPC_Values($key, 'string'); + $output[] = new XML_RPC_Values($key, 'string'); } $v->addArray($output); return new XML_RPC_Response($v); } - + // -------------------------------------------------------------------- /** - * Server Function: Return Signature for Method + * Server Function: Return Signature for Method * - * @access public * @param mixed * @return object */ - function methodSignature($m) + public function methodSignature($m) { $parameters = $m->output_parameters(); $method_name = $parameters[0]; @@ -431,40 +456,35 @@ class CI_Xmlrpcs extends CI_Xmlrpc $sigs = array(); $signature = $this->methods[$method_name]['signature']; - for ($i=0; $i < count($signature); $i++) + for ($i = 0, $c = count($signature); $i < $c; $i++) { $cursig = array(); $inSig = $signature[$i]; - for ($j=0; $jxmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); - } - return $r; + + return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); } // -------------------------------------------------------------------- /** - * Server Function: Doc String for Method + * Server Function: Doc String for Method * - * @access public * @param mixed * @return object */ - function methodHelp($m) + public function methodHelp($m) { $parameters = $m->output_parameters(); $method_name = $parameters[0]; @@ -475,22 +495,19 @@ class CI_Xmlrpcs extends CI_Xmlrpc return new XML_RPC_Response(new XML_RPC_Values($docstring, 'string')); } - else - { - return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); - } + + return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']); } - + // -------------------------------------------------------------------- /** - * Server Function: Multi-call + * Server Function: Multi-call * - * @access public * @param mixed * @return object */ - function multicall($m) + public function multicall($m) { // Disabled return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']); @@ -502,19 +519,17 @@ class CI_Xmlrpcs extends CI_Xmlrpc foreach ($calls as $value) { - //$attempt = $this->_execute(new XML_RPC_Message($value[0], $value[1])); - $m = new XML_RPC_Message($value[0]); - $plist=''; + $plist = ''; - for ($i=0; $i < count($value[1]); $i++) + for ($i = 0, $c = count($value[1]); $i < $c; $i++) { $m->addParam(new XML_RPC_Values($value[1][$i], 'string')); } $attempt = $this->_execute($m); - if ($attempt->faultCode() != 0) + if ($attempt->faultCode() !== 0) { return $attempt; } @@ -528,15 +543,14 @@ class CI_Xmlrpcs extends CI_Xmlrpc // -------------------------------------------------------------------- /** - * Multi-call Function: Error Handling + * Multi-call Function: Error Handling * - * @access public * @param mixed * @return object */ - function multicall_error($err) + public function multicall_error($err) { - $str = is_string($err) ? $this->xmlrpcstr["multicall_${err}"] : $err->faultString(); + $str = is_string($err) ? $this->xmlrpcstr["multicall_${err}"] : $err->faultString(); $code = is_string($err) ? $this->xmlrpcerr["multicall_${err}"] : $err->faultCode(); $struct['faultCode'] = new XML_RPC_Values($code, 'int'); @@ -548,15 +562,14 @@ class CI_Xmlrpcs extends CI_Xmlrpc // -------------------------------------------------------------------- /** - * Multi-call Function: Processes method + * Multi-call Function: Processes method * - * @access public * @param mixed * @return object */ - function do_multicall($call) + public function do_multicall($call) { - if ($call->kindOf() != 'struct') + if ($call->kindOf() !== 'struct') { return $this->multicall_error('notstruct'); } @@ -565,14 +578,14 @@ class CI_Xmlrpcs extends CI_Xmlrpc return $this->multicall_error('nomethod'); } - list($scalar_type,$scalar_value)=each($methName->me); - $scalar_type = $scalar_type == $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type; + list($scalar_value, $scalar_type) = array(reset($methName->me), key($methName->me)); + $scalar_type = $scalar_type === $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type; - if ($methName->kindOf() != 'scalar' OR $scalar_type != 'string') + if ($methName->kindOf() !== 'scalar' OR $scalar_type !== 'string') { return $this->multicall_error('notstring'); } - elseif ($scalar_value == 'system.multicall') + elseif ($scalar_value === 'system.multicall') { return $this->multicall_error('recursion'); } @@ -580,23 +593,22 @@ class CI_Xmlrpcs extends CI_Xmlrpc { return $this->multicall_error('noparams'); } - elseif ($params->kindOf() != 'array') + elseif ($params->kindOf() !== 'array') { return $this->multicall_error('notarray'); } - list($a,$b)=each($params->me); - $numParams = count($b); + list($b, $a) = array(reset($params->me), key($params->me)); $msg = new XML_RPC_Message($scalar_value); - for ($i = 0; $i < $numParams; $i++) + for ($i = 0, $numParams = count($b); $i < $numParams; $i++) { $msg->params[] = $params->me['array'][$i]; } $result = $this->_execute($msg); - if ($result->faultCode() != 0) + if ($result->faultCode() !== 0) { return $this->multicall_error($result); } @@ -605,8 +617,3 @@ class CI_Xmlrpcs extends CI_Xmlrpc } } -// END XML_RPC_Server class - - -/* End of file Xmlrpcs.php */ -/* Location: ./system/libraries/Xmlrpcs.php */ \ No newline at end of file diff --git a/system/libraries/Zip.php b/system/libraries/Zip.php old mode 100755 new mode 100644 index ffff3f3..c0a1402 --- a/system/libraries/Zip.php +++ b/system/libraries/Zip.php @@ -1,19 +1,41 @@ -now = time(); + log_message('info', 'Zip Compression Class Initialized'); } // -------------------------------------------------------------------- @@ -56,21 +132,19 @@ class CI_Zip { * * Lets you add a virtual directory into which you can place files. * - * @access public - * @param mixed the directory name. Can be string or array + * @param mixed $directory the directory name. Can be string or array * @return void */ - function add_dir($directory) + public function add_dir($directory) { - foreach ((array)$directory as $dir) + foreach ((array) $directory as $dir) { - if ( ! preg_match("|.+/$|", $dir)) + if ( ! preg_match('|.+/$|', $dir)) { $dir .= '/'; } $dir_time = $this->_get_mod_time($dir); - $this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']); } } @@ -78,22 +152,22 @@ class CI_Zip { // -------------------------------------------------------------------- /** - * Get file/directory modification time + * Get file/directory modification time * - * If this is a newly created file/dir, we will set the time to 'now' + * If this is a newly created file/dir, we will set the time to 'now' * - * @param string path to file - * @return array filemtime/filemdate + * @param string $dir path to file + * @return array filemtime/filemdate */ - function _get_mod_time($dir) + protected function _get_mod_time($dir) { - // filemtime() will return false, but it does raise an error. - $date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now); + // filemtime() may return false, but raises an error for non-existing files + $date = file_exists($dir) ? getdate(filemtime($dir)) : getdate($this->now); - $time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2; - $time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday']; - - return $time; + return array( + 'file_mtime' => ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2, + 'file_mdate' => (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday'] + ); } // -------------------------------------------------------------------- @@ -101,13 +175,14 @@ class CI_Zip { /** * Add Directory * - * @access private - * @param string the directory name + * @param string $dir the directory name + * @param int $file_mtime + * @param int $file_mdate * @return void */ - function _add_dir($dir, $file_mtime, $file_mdate) + protected function _add_dir($dir, $file_mtime, $file_mdate) { - $dir = str_replace("\\", "/", $dir); + $dir = str_replace('\\', '/', $dir); $this->zipdata .= "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00" @@ -116,7 +191,7 @@ class CI_Zip { .pack('V', 0) // crc32 .pack('V', 0) // compressed filesize .pack('V', 0) // uncompressed filesize - .pack('v', strlen($dir)) // length of pathname + .pack('v', self::strlen($dir)) // length of pathname .pack('v', 0) // extra field length .$dir // below is "data descriptor" segment @@ -131,7 +206,7 @@ class CI_Zip { .pack('V',0) // crc32 .pack('V',0) // compressed filesize .pack('V',0) // uncompressed filesize - .pack('v', strlen($dir)) // length of pathname + .pack('v', self::strlen($dir)) // length of pathname .pack('v', 0) // extra field length .pack('v', 0) // file comment length .pack('v', 0) // disk number start @@ -140,7 +215,7 @@ class CI_Zip { .pack('V', $this->offset) // relative offset of local header .$dir; - $this->offset = strlen($this->zipdata); + $this->offset = self::strlen($this->zipdata); $this->entries++; } @@ -150,29 +225,26 @@ class CI_Zip { * Add Data to Zip * * Lets you add files to the archive. If the path is included - * in the filename it will be placed within a directory. Make + * in the filename it will be placed within a directory. Make * sure you use add_dir() first to create the folder. * - * @access public - * @param mixed - * @param string + * @param mixed $filepath A single filepath or an array of file => data pairs + * @param string $data Single file contents * @return void */ - function add_data($filepath, $data = NULL) + public function add_data($filepath, $data = NULL) { if (is_array($filepath)) { foreach ($filepath as $path => $data) { $file_data = $this->_get_mod_time($path); - $this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']); } } else { $file_data = $this->_get_mod_time($filepath); - $this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']); } } @@ -182,21 +254,20 @@ class CI_Zip { /** * Add Data to Zip * - * @access private - * @param string the file name/path - * @param string the data to be encoded + * @param string $filepath the file name/path + * @param string $data the data to be encoded + * @param int $file_mtime + * @param int $file_mdate * @return void */ - function _add_data($filepath, $data, $file_mtime, $file_mdate) + protected function _add_data($filepath, $data, $file_mtime, $file_mdate) { - $filepath = str_replace("\\", "/", $filepath); + $filepath = str_replace('\\', '/', $filepath); - $uncompressed_size = strlen($data); + $uncompressed_size = self::strlen($data); $crc32 = crc32($data); - - $gzdata = gzcompress($data); - $gzdata = substr($gzdata, 2, -4); - $compressed_size = strlen($gzdata); + $gzdata = self::substr(gzcompress($data, $this->compression_level), 2, -4); + $compressed_size = self::strlen($gzdata); $this->zipdata .= "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00" @@ -205,7 +276,7 @@ class CI_Zip { .pack('V', $crc32) .pack('V', $compressed_size) .pack('V', $uncompressed_size) - .pack('v', strlen($filepath)) // length of filename + .pack('v', self::strlen($filepath)) // length of filename .pack('v', 0) // extra field length .$filepath .$gzdata; // "file data" segment @@ -217,7 +288,7 @@ class CI_Zip { .pack('V', $crc32) .pack('V', $compressed_size) .pack('V', $uncompressed_size) - .pack('v', strlen($filepath)) // length of filename + .pack('v', self::strlen($filepath)) // length of filename .pack('v', 0) // extra field length .pack('v', 0) // file comment length .pack('v', 0) // disk number start @@ -226,7 +297,7 @@ class CI_Zip { .pack('V', $this->offset) // relative offset of local header .$filepath; - $this->offset = strlen($this->zipdata); + $this->offset = self::strlen($this->zipdata); $this->entries++; $this->file_num++; } @@ -236,28 +307,32 @@ class CI_Zip { /** * Read the contents of a file and add it to the zip * - * @access public + * @param string $path + * @param bool $archive_filepath * @return bool */ - function read_file($path, $preserve_filepath = FALSE) + public function read_file($path, $archive_filepath = FALSE) { - if ( ! file_exists($path)) + if (file_exists($path) && FALSE !== ($data = file_get_contents($path))) { - return FALSE; - } - - if (FALSE !== ($data = file_get_contents($path))) - { - $name = str_replace("\\", "/", $path); - - if ($preserve_filepath === FALSE) + if (is_string($archive_filepath)) { - $name = preg_replace("|.*/(.+)|", "\\1", $name); + $name = str_replace('\\', '/', $archive_filepath); + } + else + { + $name = str_replace('\\', '/', $path); + + if ($archive_filepath === FALSE) + { + $name = preg_replace('|.*/(.+)|', '\\1', $name); + } } $this->add_data($name, $data); return TRUE; } + return FALSE; } @@ -267,15 +342,17 @@ class CI_Zip { * Read a directory and add it to the zip. * * This function recursively reads a folder and everything it contains (including - * sub-folders) and creates a zip based on it. Whatever directory structure + * sub-folders) and creates a zip based on it. Whatever directory structure * is in the original file path will be recreated in the zip file. * - * @access public - * @param string path to source + * @param string $path path to source directory + * @param bool $preserve_filepath + * @param string $root_path * @return bool */ - function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL) + public function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL) { + $path = rtrim($path, '/\\').DIRECTORY_SEPARATOR; if ( ! $fp = @opendir($path)) { return FALSE; @@ -284,36 +361,33 @@ class CI_Zip { // Set the original directory root for child dir's to use as relative if ($root_path === NULL) { - $root_path = dirname($path).'/'; + $root_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, dirname($path)).DIRECTORY_SEPARATOR; } while (FALSE !== ($file = readdir($fp))) { - if (substr($file, 0, 1) == '.') + if ($file[0] === '.') { continue; } - if (@is_dir($path.$file)) + if (is_dir($path.$file)) { - $this->read_dir($path.$file."/", $preserve_filepath, $root_path); + $this->read_dir($path.$file.DIRECTORY_SEPARATOR, $preserve_filepath, $root_path); } - else + elseif (FALSE !== ($data = file_get_contents($path.$file))) { - if (FALSE !== ($data = file_get_contents($path.$file))) + $name = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $path); + if ($preserve_filepath === FALSE) { - $name = str_replace("\\", "/", $path); - - if ($preserve_filepath === FALSE) - { - $name = str_replace($root_path, '', $name); - } - - $this->add_data($name.$file, $data); + $name = str_replace($root_path, '', $name); } + + $this->add_data($name.$file, $data); } } + closedir($fp); return TRUE; } @@ -322,26 +396,23 @@ class CI_Zip { /** * Get the Zip file * - * @access public - * @return binary string + * @return string (binary encoded) */ - function get_zip() + public function get_zip() { // Is there any data to return? - if ($this->entries == 0) + if ($this->entries === 0) { return FALSE; } - $zip_data = $this->zipdata; - $zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00"; - $zip_data .= pack('v', $this->entries); // total # of entries "on this disk" - $zip_data .= pack('v', $this->entries); // total # of entries overall - $zip_data .= pack('V', strlen($this->directory)); // size of central dir - $zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir - $zip_data .= "\x00\x00"; // .zip file comment length - - return $zip_data; + return $this->zipdata + .$this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00" + .pack('v', $this->entries) // total # of entries "on this disk" + .pack('v', $this->entries) // total # of entries overall + .pack('V', self::strlen($this->directory)) // size of central dir + .pack('V', self::strlen($this->zipdata)) // offset to start of central dir + ."\x00\x00"; // .zip file comment length } // -------------------------------------------------------------------- @@ -351,23 +422,30 @@ class CI_Zip { * * Lets you write a file * - * @access public - * @param string the file name + * @param string $filepath the file name * @return bool */ - function archive($filepath) + public function archive($filepath) { - if ( ! ($fp = @fopen($filepath, FOPEN_WRITE_CREATE_DESTRUCTIVE))) + if ( ! ($fp = @fopen($filepath, 'w+b'))) { return FALSE; } flock($fp, LOCK_EX); - fwrite($fp, $this->get_zip()); + + for ($result = $written = 0, $data = $this->get_zip(), $length = self::strlen($data); $written < $length; $written += $result) + { + if (($result = fwrite($fp, self::substr($data, $written))) === FALSE) + { + break; + } + } + flock($fp, LOCK_UN); fclose($fp); - return TRUE; + return is_int($result); } // -------------------------------------------------------------------- @@ -375,23 +453,18 @@ class CI_Zip { /** * Download * - * @access public - * @param string the file name - * @param string the data to be encoded - * @return bool + * @param string $filename the file name + * @return void */ - function download($filename = 'backup.zip') + public function download($filename = 'backup.zip') { - if ( ! preg_match("|.+?\.zip$|", $filename)) + if ( ! preg_match('|.+?\.zip$|', $filename)) { $filename .= '.zip'; } - $CI =& get_instance(); - $CI->load->helper('download'); - + get_instance()->load->helper('download'); $get_zip = $this->get_zip(); - $zip_content =& $get_zip; force_download($filename, $zip_content); @@ -402,22 +475,58 @@ class CI_Zip { /** * Initialize Data * - * Lets you clear current zip data. Useful if you need to create + * Lets you clear current zip data. Useful if you need to create * multiple zips with different data. * - * @access public - * @return void + * @return CI_Zip */ - function clear_data() + public function clear_data() { - $this->zipdata = ''; - $this->directory = ''; - $this->entries = 0; - $this->file_num = 0; - $this->offset = 0; + $this->zipdata = ''; + $this->directory = ''; + $this->entries = 0; + $this->file_num = 0; + $this->offset = 0; + return $this; } -} + // -------------------------------------------------------------------- -/* End of file Zip.php */ -/* Location: ./system/libraries/Zip.php */ \ No newline at end of file + /** + * 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/libraries/index.html b/system/libraries/index.html old mode 100755 new mode 100644 index c942a79..b702fbc --- a/system/libraries/index.html +++ b/system/libraries/index.html @@ -1,3 +1,4 @@ + 403 Forbidden @@ -7,4 +8,4 @@

    Directory access is forbidden.

    - \ No newline at end of file +