From b6e9961846848e02102324736614af056c28fc9b Mon Sep 17 00:00:00 2001 From: Deon George Date: Fri, 14 Jan 2011 01:49:56 +1100 Subject: [PATCH] Added Kohana v3.0.9 --- .htaccess | 21 + application/bootstrap.php | 110 + application/classes/controller/welcome.php | 10 + includes/kohana/DEVELOPERS.md | 147 + includes/kohana/LICENSE.md | 14 + includes/kohana/README.md | 3 + includes/kohana/build.xml | 233 ++ includes/kohana/example.htaccess | 21 + includes/kohana/install.php | 217 ++ includes/kohana/modules/auth/classes/auth.php | 3 + .../kohana/modules/auth/classes/auth/file.php | 3 + .../kohana/modules/auth/classes/auth/orm.php | 3 + .../modules/auth/classes/kohana/auth.php | 241 ++ .../modules/auth/classes/kohana/auth/file.php | 88 + .../modules/auth/classes/kohana/auth/orm.php | 322 ++ .../modules/auth/classes/model/auth/role.php | 27 + .../modules/auth/classes/model/auth/user.php | 244 ++ .../auth/classes/model/auth/user/token.php | 101 + .../modules/auth/classes/model/role.php | 7 + .../modules/auth/classes/model/user.php | 7 + .../modules/auth/classes/model/user/token.php | 7 + includes/kohana/modules/auth/config/auth.php | 18 + .../kohana/modules/auth/config/userguide.php | 23 + .../kohana/modules/auth/guide/auth/config.md | 0 .../kohana/modules/auth/guide/auth/edit.md | 0 .../kohana/modules/auth/guide/auth/index.md | 0 .../kohana/modules/auth/guide/auth/login.md | 0 .../kohana/modules/auth/guide/auth/menu.md | 7 + .../modules/auth/guide/auth/register.md | 0 .../kohana/modules/auth/guide/auth/roles.md | 0 .../kohana/modules/auth/guide/auth/user.md | 0 includes/kohana/modules/auth/mysql.sql | 48 + includes/kohana/modules/auth/postgresql.sql | 53 + includes/kohana/modules/cache/README.md | 61 + .../kohana/modules/cache/classes/cache.php | 3 + .../modules/cache/classes/cache/apc.php | 3 + .../cache/classes/cache/eaccelerator.php | 3 + .../modules/cache/classes/cache/file.php | 3 + .../modules/cache/classes/cache/memcache.php | 3 + .../cache/classes/cache/memcachetag.php | 3 + .../modules/cache/classes/cache/sqlite.php | 3 + .../modules/cache/classes/cache/wincache.php | 3 + .../modules/cache/classes/cache/xcache.php | 3 + .../modules/cache/classes/kohana/cache.php | 256 ++ .../cache/classes/kohana/cache/apc.php | 133 + .../classes/kohana/cache/eaccelerator.php | 133 + .../cache/classes/kohana/cache/exception.php | 11 + .../cache/classes/kohana/cache/file.php | 463 +++ .../classes/kohana/cache/garbagecollect.php | 23 + .../cache/classes/kohana/cache/memcache.php | 324 ++ .../classes/kohana/cache/memcachetag.php | 76 + .../cache/classes/kohana/cache/sqlite.php | 336 ++ .../cache/classes/kohana/cache/tagging.php | 42 + .../cache/classes/kohana/cache/wincache.php | 140 + .../cache/classes/kohana/cache/xcache.php | 84 + .../kohana/modules/cache/config/cache.php | 76 + .../kohana/modules/cache/config/userguide.php | 23 + .../kohana/modules/cache/guide/cache.usage.md | 219 ++ .../modules/cache/guide/cache/config.md | 168 + .../modules/cache/guide/cache/examples.md | 0 .../kohana/modules/cache/guide/cache/index.md | 59 + .../kohana/modules/cache/guide/cache/menu.md | 3 + .../kohana/modules/cache/guide/cache/usage.md | 219 ++ .../cache/tests/cache/KohanaCacheTest.php | 91 + .../kohana/modules/cache/tests/phpunit.xml | 16 + .../codebench/classes/bench/arrcallback.php | 57 + .../classes/bench/autolinkemails.php | 70 + .../codebench/classes/bench/datespan.php | 186 ++ .../codebench/classes/bench/explodelimit.php | 34 + .../codebench/classes/bench/gruberurl.php | 61 + .../codebench/classes/bench/ltrimdigits.php | 28 + .../codebench/classes/bench/mddobaseurl.php | 66 + .../codebench/classes/bench/mddoimageurl.php | 66 + .../classes/bench/mddoincludeviews.php | 50 + .../classes/bench/stripnullbytes.php | 37 + .../codebench/classes/bench/transliterate.php | 65 + .../codebench/classes/bench/urlsite.php | 123 + .../codebench/classes/bench/userfuncarray.php | 58 + .../codebench/classes/bench/validcolor.php | 116 + .../codebench/classes/bench/validurl.php | 105 + .../modules/codebench/classes/codebench.php | 3 + .../classes/controller/codebench.php | 32 + .../codebench/classes/kohana/codebench.php | 217 ++ .../modules/codebench/config/codebench.php | 16 + .../modules/codebench/config/userguide.php | 23 + .../codebench/guide/codebench/index.md | 76 + .../modules/codebench/guide/codebench/menu.md | 1 + includes/kohana/modules/codebench/init.php | 8 + .../guide/codebench/codebench_screenshot1.png | Bin 0 -> 15827 bytes .../guide/codebench/codebench_screenshot2.png | Bin 0 -> 13575 bytes .../modules/codebench/views/codebench.php | 258 ++ .../modules/database/classes/database.php | 3 + .../database/classes/database/exception.php | 3 + .../database/classes/database/expression.php | 3 + .../database/classes/database/mysql.php | 3 + .../classes/database/mysql/result.php | 3 + .../modules/database/classes/database/pdo.php | 3 + .../database/classes/database/query.php | 3 + .../classes/database/query/builder.php | 3 + .../classes/database/query/builder/delete.php | 3 + .../classes/database/query/builder/insert.php | 3 + .../classes/database/query/builder/join.php | 3 + .../classes/database/query/builder/select.php | 3 + .../classes/database/query/builder/update.php | 3 + .../classes/database/query/builder/where.php | 3 + .../database/classes/database/result.php | 3 + .../classes/database/result/cached.php | 3 + .../kohana/modules/database/classes/db.php | 3 + .../classes/kohana/config/database.php | 97 + .../database/classes/kohana/database.php | 600 ++++ .../classes/kohana/database/exception.php | 11 + .../classes/kohana/database/expression.php | 62 + .../classes/kohana/database/mysql.php | 379 +++ .../classes/kohana/database/mysql/result.php | 71 + .../database/classes/kohana/database/pdo.php | 186 ++ .../classes/kohana/database/query.php | 236 ++ .../classes/kohana/database/query/builder.php | 211 ++ .../kohana/database/query/builder/delete.php | 89 + .../kohana/database/query/builder/insert.php | 171 + .../kohana/database/query/builder/join.php | 107 + .../kohana/database/query/builder/select.php | 388 +++ .../kohana/database/query/builder/update.php | 130 + .../kohana/database/query/builder/where.php | 160 + .../classes/kohana/database/result.php | 331 ++ .../classes/kohana/database/result/cached.php | 51 + .../modules/database/classes/kohana/db.php | 139 + .../classes/kohana/session/database.php | 229 ++ .../database/classes/session/database.php | 3 + .../modules/database/config/database.php | 57 + .../modules/database/config/session.php | 27 + .../modules/database/config/userguide.php | 23 + .../modules/database/guide/database/config.md | 118 + .../database/guide/database/examples.md | 52 + .../modules/database/guide/database/index.md | 17 + .../modules/database/guide/database/menu.md | 7 + .../modules/database/guide/database/query.md | 5 + .../database/guide/database/query/builder.md | 253 ++ .../database/guide/database/query/prepared.md | 67 + .../database/guide/database/results.md | 105 + includes/kohana/modules/image/README.markdown | 0 .../kohana/modules/image/classes/image.php | 3 + .../kohana/modules/image/classes/image/gd.php | 3 + .../modules/image/classes/kohana/image.php | 742 +++++ .../modules/image/classes/kohana/image/gd.php | 582 ++++ .../kohana/modules/image/config/userguide.php | 23 + .../modules/image/guide/image/examples.md | 0 .../kohana/modules/image/guide/image/index.md | 0 .../kohana/modules/image/guide/image/menu.md | 3 + .../kohana/modules/image/guide/image/using.md | 0 includes/kohana/modules/oauth/README.md | 5 + .../modules/oauth/classes/kohana/oauth.php | 217 ++ .../oauth/classes/kohana/oauth/consumer.php | 99 + .../oauth/classes/kohana/oauth/exception.php | 12 + .../oauth/classes/kohana/oauth/provider.php | 215 ++ .../classes/kohana/oauth/provider/google.php | 55 + .../classes/kohana/oauth/provider/twitter.php | 39 + .../oauth/classes/kohana/oauth/request.php | 509 +++ .../classes/kohana/oauth/request/access.php | 32 + .../kohana/oauth/request/authorize.php | 26 + .../kohana/oauth/request/credentials.php | 16 + .../classes/kohana/oauth/request/resource.php | 27 + .../classes/kohana/oauth/request/token.php | 32 + .../oauth/classes/kohana/oauth/response.php | 51 + .../oauth/classes/kohana/oauth/server.php | 14 + .../oauth/classes/kohana/oauth/signature.php | 77 + .../kohana/oauth/signature/hmac/sha1.php | 68 + .../kohana/oauth/signature/plaintext.php | 57 + .../oauth/classes/kohana/oauth/token.php | 94 + .../classes/kohana/oauth/token/access.php | 16 + .../classes/kohana/oauth/token/request.php | 36 + .../kohana/modules/oauth/classes/oauth.php | 3 + .../modules/oauth/classes/oauth/consumer.php | 3 + .../modules/oauth/classes/oauth/provider.php | 3 + .../oauth/classes/oauth/provider/google.php | 3 + .../oauth/classes/oauth/provider/twitter.php | 3 + .../modules/oauth/classes/oauth/request.php | 3 + .../oauth/classes/oauth/request/access.php | 3 + .../oauth/classes/oauth/request/authorize.php | 3 + .../classes/oauth/request/credentials.php | 3 + .../oauth/classes/oauth/request/resource.php | 3 + .../oauth/classes/oauth/request/token.php | 3 + .../modules/oauth/classes/oauth/response.php | 3 + .../modules/oauth/classes/oauth/signature.php | 3 + .../classes/oauth/signature/hmac/sha1.php | 3 + .../classes/oauth/signature/plaintext.php | 3 + .../modules/oauth/classes/oauth/token.php | 3 + .../oauth/classes/oauth/token/access.php | 3 + .../oauth/classes/oauth/token/request.php | 3 + .../kohana/modules/oauth/config/oauth.php | 15 + .../kohana/modules/oauth/config/userguide.php | 23 + .../modules/oauth/guide/oauth/config.md | 24 + .../kohana/modules/oauth/guide/oauth/index.md | 14 + .../kohana/modules/oauth/guide/oauth/menu.md | 3 + .../kohana/modules/oauth/guide/oauth/usage.md | 3 + .../oauth/views/oauth/twitter/tweet.php | 15 + .../kohana/modules/orm/classes/kohana/orm.php | 1369 ++++++++ includes/kohana/modules/orm/classes/orm.php | 3 + .../kohana/modules/orm/config/userguide.php | 23 + .../kohana/modules/orm/guide/orm/examples.md | 8 + .../modules/orm/guide/orm/examples/simple.md | 120 + .../kohana/modules/orm/guide/orm/index.md | 22 + includes/kohana/modules/orm/guide/orm/menu.md | 7 + .../kohana/modules/orm/guide/orm/models.md | 36 + .../modules/orm/guide/orm/relationships.md | 89 + .../kohana/modules/orm/guide/orm/tutorials.md | 0 .../kohana/modules/orm/guide/orm/using.md | 78 + .../modules/orm/guide/orm/validation.md | 0 .../pagination/classes/kohana/pagination.php | 285 ++ .../modules/pagination/classes/pagination.php | 3 + .../modules/pagination/config/pagination.php | 15 + .../modules/pagination/config/userguide.php | 23 + .../pagination/guide/pagination/config.md | 94 + .../pagination/guide/pagination/examples.md | 0 .../pagination/guide/pagination/index.md | 0 .../pagination/guide/pagination/menu.md | 4 + .../pagination/guide/pagination/usage.md | 0 .../pagination/views/pagination/basic.php | 37 + .../pagination/views/pagination/floating.php | 94 + .../kohana/modules/unittest/README.markdown | 70 + .../kohana/modules/unittest/bootstrap.php | 115 + .../unittest/classes/controller/unittest.php | 359 ++ .../modules/unittest/classes/kohana/tests.php | 335 ++ .../kohana/unittest/database/testcase.php | 301 ++ .../classes/kohana/unittest/helpers.php | 176 + .../classes/kohana/unittest/runner.php | 304 ++ .../classes/kohana/unittest/testcase.php | 261 ++ .../modules/unittest/config/unittest.php | 53 + .../modules/unittest/config/userguide.php | 23 + .../modules/unittest/example.phpunit.xml | 16 + .../modules/unittest/guide/unittest/index.md | 13 + .../unittest/guide/unittest/installing.md | 41 + .../modules/unittest/guide/unittest/menu.md | 6 + .../unittest/guide/unittest/mockobjects.md | 265 ++ .../unittest/guide/unittest/testing.md | 107 + .../guide/unittest/troubleshooting.md | 21 + .../unittest/guide/unittest/workflows.md | 51 + includes/kohana/modules/unittest/init.php | 16 + includes/kohana/modules/unittest/tests.php | 20 + .../modules/unittest/views/unittest/index.php | 66 + .../unittest/views/unittest/layout.php | 255 ++ .../unittest/views/unittest/results.php | 83 + includes/kohana/modules/userguide/README.md | 118 + .../classes/controller/userguide.php | 391 +++ .../modules/userguide/classes/kodoc.php | 3 + .../modules/userguide/classes/kodoc/class.php | 3 + .../userguide/classes/kodoc/markdown.php | 3 + .../userguide/classes/kodoc/method.php | 3 + .../userguide/classes/kodoc/method/param.php | 3 + .../userguide/classes/kodoc/missing.php | 3 + .../userguide/classes/kodoc/property.php | 3 + .../userguide/classes/kohana/kodoc.php | 354 ++ .../userguide/classes/kohana/kodoc/class.php | 216 ++ .../classes/kohana/kodoc/markdown.php | 264 ++ .../userguide/classes/kohana/kodoc/method.php | 141 + .../classes/kohana/kodoc/method/param.php | 101 + .../classes/kohana/kodoc/missing.php | 36 + .../classes/kohana/kodoc/property.php | 83 + .../modules/userguide/config/userguide.php | 31 + .../guide/de-de/about.conventions.md | 300 ++ .../userguide/guide/de-de/about.kohana.md | 15 + .../userguide/guide/userguide/adding.md | 41 + .../userguide/guide/userguide/config.md | 35 + .../userguide/guide/userguide/contributing.md | 79 + .../userguide/guide/userguide/index.md | 3 + .../userguide/guide/userguide/markdown.md | 235 ++ .../modules/userguide/guide/userguide/menu.md | 7 + .../userguide/guide/userguide/modules.md | 0 .../userguide/guide/userguide/using.md | 1 + .../userguide/guide/userguide/works.md | 25 + includes/kohana/modules/userguide/i18n/de.php | 6 + includes/kohana/modules/userguide/i18n/es.php | 6 + includes/kohana/modules/userguide/i18n/fr.php | 7 + includes/kohana/modules/userguide/i18n/he.php | 6 + includes/kohana/modules/userguide/i18n/nl.php | 6 + includes/kohana/modules/userguide/i18n/ru.php | 7 + includes/kohana/modules/userguide/i18n/zh.php | 28 + includes/kohana/modules/userguide/init.php | 30 + .../modules/userguide/media/guide/css/api.css | 34 + .../userguide/media/guide/css/kodoc.css | 141 + .../userguide/media/guide/css/print.css | 50 + .../userguide/media/guide/css/screen.css | 267 ++ .../userguide/media/guide/css/shCore.css | 226 ++ .../media/guide/css/shThemeDefault.css | 117 + .../media/guide/css/shThemeKodoc.css | 183 ++ .../userguide/media/guide/img/arrows.png | Bin 0 -> 357 bytes .../userguide/media/guide/img/breadcrumbs.png | Bin 0 -> 195 bytes .../userguide/media/guide/img/content.png | Bin 0 -> 2983 bytes .../userguide/media/guide/img/ext_link.png | Bin 0 -> 144 bytes .../userguide/media/guide/img/h2_line.png | Bin 0 -> 184 bytes .../userguide/media/guide/img/h3_line.png | Bin 0 -> 184 bytes .../userguide/media/guide/img/header.png | Bin 0 -> 2998 bytes .../userguide/media/guide/img/kohana.png | Bin 0 -> 8678 bytes .../media/guide/img/lightbulb_48.png | Bin 0 -> 4843 bytes .../userguide/media/guide/img/lines.png | Bin 0 -> 181 bytes .../userguide/media/guide/img/orange-tab.png | Bin 0 -> 215 bytes .../userguide/media/guide/img/wrapper.png | Bin 0 -> 12347 bytes .../userguide/media/guide/js/jquery.cookie.js | 96 + .../userguide/media/guide/js/jquery.min.js | 154 + .../modules/userguide/media/guide/js/kodoc.js | 97 + .../userguide/media/guide/js/shBrushPhp.js | 88 + .../userguide/media/guide/js/shCore.js | 17 + .../userguide/media/guide/js/sizzle.js | 1068 ++++++ .../guide/userguide/contrib-github-edit.png | Bin 0 -> 9681 bytes .../guide/userguide/contrib-github-fork.png | Bin 0 -> 8278 bytes .../guide/userguide/contrib-github-pull.png | Bin 0 -> 8839 bytes .../modules/userguide/messages/userguide.php | 14 + .../userguide/vendor/markdown/License.text | 36 + .../userguide/vendor/markdown/markdown.php | 2909 +++++++++++++++++ .../userguide/views/userguide/api/class.php | 103 + .../userguide/views/userguide/api/menu.php | 18 + .../userguide/views/userguide/api/method.php | 45 + .../userguide/views/userguide/api/tags.php | 6 + .../userguide/views/userguide/api/toc.php | 75 + .../userguide/views/userguide/error.php | 3 + .../views/userguide/examples/error.php | 6 + .../userguide/examples/hello_world_error.php | 696 ++++ .../userguide/views/userguide/index.php | 20 + .../userguide/views/userguide/menu.php | 17 + .../userguide/views/userguide/page-toc.php | 10 + .../userguide/views/userguide/template.php | 108 + includes/kohana/system/base.php | 50 + includes/kohana/system/classes/arr.php | 3 + includes/kohana/system/classes/cli.php | 3 + includes/kohana/system/classes/controller.php | 3 + .../kohana/system/classes/controller/rest.php | 3 + .../system/classes/controller/template.php | 3 + includes/kohana/system/classes/cookie.php | 3 + includes/kohana/system/classes/date.php | 3 + includes/kohana/system/classes/encrypt.php | 3 + includes/kohana/system/classes/feed.php | 3 + includes/kohana/system/classes/file.php | 3 + includes/kohana/system/classes/form.php | 3 + includes/kohana/system/classes/fragment.php | 3 + includes/kohana/system/classes/html.php | 3 + includes/kohana/system/classes/i18n.php | 3 + includes/kohana/system/classes/inflector.php | 3 + includes/kohana/system/classes/kohana.php | 3 + includes/kohana/system/classes/kohana/arr.php | 547 ++++ includes/kohana/system/classes/kohana/cli.php | 75 + .../kohana/system/classes/kohana/config.php | 157 + .../system/classes/kohana/config/file.php | 60 + .../system/classes/kohana/config/reader.php | 115 + .../system/classes/kohana/controller.php | 66 + .../system/classes/kohana/controller/rest.php | 80 + .../classes/kohana/controller/template.php | 50 + .../kohana/system/classes/kohana/cookie.php | 155 + .../kohana/system/classes/kohana/core.php | 1637 ++++++++++ .../kohana/system/classes/kohana/date.php | 566 ++++ .../kohana/system/classes/kohana/encrypt.php | 213 ++ .../system/classes/kohana/exception.php | 46 + .../kohana/system/classes/kohana/feed.php | 176 + .../kohana/system/classes/kohana/file.php | 179 + .../kohana/system/classes/kohana/form.php | 434 +++ .../kohana/system/classes/kohana/fragment.php | 147 + .../kohana/system/classes/kohana/html.php | 380 +++ .../kohana/system/classes/kohana/i18n.php | 139 + .../system/classes/kohana/inflector.php | 269 ++ includes/kohana/system/classes/kohana/log.php | 189 ++ .../kohana/system/classes/kohana/log/file.php | 97 + .../system/classes/kohana/log/stderr.php | 31 + .../system/classes/kohana/log/stdout.php | 31 + .../system/classes/kohana/log/syslog.php | 70 + .../system/classes/kohana/log/writer.php | 35 + .../kohana/system/classes/kohana/model.php | 65 + includes/kohana/system/classes/kohana/num.php | 81 + .../kohana/system/classes/kohana/profiler.php | 385 +++ .../kohana/system/classes/kohana/remote.php | 154 + .../kohana/system/classes/kohana/request.php | 1305 ++++++++ .../classes/kohana/request/exception.php | 9 + .../kohana/system/classes/kohana/route.php | 418 +++ .../kohana/system/classes/kohana/security.php | 193 ++ .../kohana/system/classes/kohana/session.php | 427 +++ .../system/classes/kohana/session/cookie.php | 47 + .../system/classes/kohana/session/native.php | 93 + .../kohana/system/classes/kohana/text.php | 590 ++++ .../kohana/system/classes/kohana/upload.php | 213 ++ includes/kohana/system/classes/kohana/url.php | 186 ++ .../kohana/system/classes/kohana/utf8.php | 767 +++++ .../kohana/system/classes/kohana/validate.php | 1190 +++++++ .../classes/kohana/validate/exception.php | 29 + .../kohana/system/classes/kohana/view.php | 346 ++ .../system/classes/kohana/view/exception.php | 9 + includes/kohana/system/classes/model.php | 3 + includes/kohana/system/classes/num.php | 3 + includes/kohana/system/classes/profiler.php | 3 + includes/kohana/system/classes/remote.php | 3 + includes/kohana/system/classes/request.php | 3 + includes/kohana/system/classes/route.php | 3 + includes/kohana/system/classes/security.php | 3 + includes/kohana/system/classes/session.php | 3 + .../kohana/system/classes/session/cookie.php | 3 + .../kohana/system/classes/session/native.php | 3 + includes/kohana/system/classes/text.php | 3 + includes/kohana/system/classes/upload.php | 3 + includes/kohana/system/classes/url.php | 3 + includes/kohana/system/classes/utf8.php | 3 + includes/kohana/system/classes/validate.php | 3 + .../system/classes/validate/exception.php | 3 + includes/kohana/system/classes/view.php | 3 + .../kohana/system/config/credit_cards.php | 60 + includes/kohana/system/config/encrypt.php | 17 + includes/kohana/system/config/inflector.php | 65 + includes/kohana/system/config/mimes.php | 225 ++ includes/kohana/system/config/session.php | 7 + includes/kohana/system/config/user_agents.php | 104 + includes/kohana/system/config/userguide.php | 23 + .../kohana/system/guide/kohana/autoloading.md | 69 + .../kohana/system/guide/kohana/bootstrap.md | 164 + .../kohana/system/guide/kohana/controllers.md | 1 + .../kohana/system/guide/kohana/conventions.md | 306 ++ .../kohana/system/guide/kohana/cookies.md | 89 + .../kohana/system/guide/kohana/debugging.md | 20 + includes/kohana/system/guide/kohana/errors.md | 85 + .../kohana/system/guide/kohana/extension.md | 101 + includes/kohana/system/guide/kohana/files.md | 83 + .../system/guide/kohana/files/classes.md | 41 + .../system/guide/kohana/files/config.md | 95 + .../kohana/system/guide/kohana/files/i18n.md | 1 + .../system/guide/kohana/files/messages.md | 5 + includes/kohana/system/guide/kohana/flow.md | 26 + .../kohana/system/guide/kohana/fragments.md | 135 + .../kohana/system/guide/kohana/helpers.md | 53 + includes/kohana/system/guide/kohana/index.md | 19 + .../kohana/system/guide/kohana/install.md | 33 + includes/kohana/system/guide/kohana/menu.md | 48 + includes/kohana/system/guide/kohana/models.md | 1 + .../kohana/system/guide/kohana/modules.md | 38 + includes/kohana/system/guide/kohana/mvc.md | 3 + .../system/guide/kohana/mvc/controllers.md | 189 ++ .../kohana/system/guide/kohana/mvc/models.md | 1 + .../kohana/system/guide/kohana/mvc/views.md | 161 + .../kohana/system/guide/kohana/profiling.md | 54 + .../kohana/system/guide/kohana/requests.md | 15 + .../kohana/system/guide/kohana/routing.md | 240 ++ .../kohana/system/guide/kohana/security.md | 1 + .../system/guide/kohana/security/cookies.md | 3 + .../system/guide/kohana/security/database.md | 5 + .../system/guide/kohana/security/deploying.md | 81 + .../guide/kohana/security/encryption.md | 1 + .../guide/kohana/security/validation.md | 247 ++ .../system/guide/kohana/security/xss.md | 17 + .../kohana/system/guide/kohana/sessions.md | 167 + includes/kohana/system/guide/kohana/tips.md | 33 + .../kohana/system/guide/kohana/tutorials.md | 17 + .../guide/kohana/tutorials/clean-urls.md | 80 + .../guide/kohana/tutorials/error-pages.md | 168 + .../system/guide/kohana/tutorials/git.md | 129 + .../guide/kohana/tutorials/hello-world.md | 106 + .../kohana/tutorials/routes-and-links.md | 3 + .../guide/kohana/tutorials/sharing-kohana.md | 54 + .../guide/kohana/tutorials/simple-mvc.md | 1 + .../guide/kohana/tutorials/templates.md | 7 + .../guide/kohana/tutorials/translation.md | 5 + .../kohana/system/guide/kohana/upgrading.md | 292 ++ includes/kohana/system/i18n/en.php | 3 + includes/kohana/system/i18n/es.php | 7 + includes/kohana/system/i18n/fr.php | 7 + .../guide/kohana/cascading_filesystem.png | Bin 0 -> 61164 bytes .../media/guide/kohana/hello_world_1.png | Bin 0 -> 1423 bytes .../media/guide/kohana/hello_world_2.png | Bin 0 -> 6681 bytes .../guide/kohana/hello_world_2_error.png | Bin 0 -> 84148 bytes .../system/media/guide/kohana/install.png | Bin 0 -> 71146 bytes .../system/media/guide/kohana/welcome.png | Bin 0 -> 754 bytes includes/kohana/system/messages/validate.php | 27 + .../kohana/system/tests/kohana/ArrTest.php | 500 +++ .../kohana/system/tests/kohana/CLITest.php | 167 + .../kohana/system/tests/kohana/ConfigTest.php | 244 ++ .../kohana/system/tests/kohana/CookieTest.php | 130 + .../kohana/system/tests/kohana/CoreTest.php | 490 +++ .../kohana/system/tests/kohana/DateTest.php | 702 ++++ .../kohana/system/tests/kohana/FeedTest.php | 121 + .../kohana/system/tests/kohana/FileTest.php | 73 + .../kohana/system/tests/kohana/FormTest.php | 372 +++ .../kohana/system/tests/kohana/HTMLTest.php | 231 ++ .../kohana/system/tests/kohana/I18nTest.php | 79 + .../system/tests/kohana/InflectorTest.php | 181 + .../kohana/system/tests/kohana/LogTest.php | 87 + .../kohana/system/tests/kohana/ModelTest.php | 30 + .../kohana/system/tests/kohana/NumTest.php | 95 + .../kohana/system/tests/kohana/RemoteTest.php | 77 + .../system/tests/kohana/RequestTest.php | 191 ++ .../kohana/system/tests/kohana/RouteTest.php | 416 +++ .../system/tests/kohana/SecurityTest.php | 105 + .../system/tests/kohana/SessionTest.php | 497 +++ .../kohana/system/tests/kohana/TextTest.php | 596 ++++ .../kohana/system/tests/kohana/URLTest.php | 275 ++ .../kohana/system/tests/kohana/UTF8Test.php | 647 ++++ .../kohana/system/tests/kohana/UploadTest.php | 223 ++ .../system/tests/kohana/ValidateTest.php | 1317 ++++++++ .../kohana/system/tests/test_data/github.png | Bin 0 -> 5101 bytes includes/kohana/system/utf8/from_unicode.php | 68 + includes/kohana/system/utf8/ltrim.php | 22 + includes/kohana/system/utf8/ord.php | 76 + includes/kohana/system/utf8/rtrim.php | 22 + includes/kohana/system/utf8/str_ireplace.php | 70 + includes/kohana/system/utf8/str_pad.php | 50 + includes/kohana/system/utf8/str_split.php | 27 + includes/kohana/system/utf8/strcasecmp.php | 19 + includes/kohana/system/utf8/strcspn.php | 30 + includes/kohana/system/utf8/stristr.php | 28 + includes/kohana/system/utf8/strlen.php | 17 + includes/kohana/system/utf8/strpos.php | 27 + includes/kohana/system/utf8/strrev.php | 18 + includes/kohana/system/utf8/strrpos.php | 27 + includes/kohana/system/utf8/strspn.php | 30 + includes/kohana/system/utf8/strtolower.php | 81 + includes/kohana/system/utf8/strtoupper.php | 81 + includes/kohana/system/utf8/substr.php | 72 + .../kohana/system/utf8/substr_replace.php | 22 + includes/kohana/system/utf8/to_unicode.php | 144 + .../system/utf8/transliterate_to_ascii.php | 77 + includes/kohana/system/utf8/trim.php | 17 + includes/kohana/system/utf8/ucfirst.php | 18 + includes/kohana/system/utf8/ucwords.php | 23 + includes/kohana/system/views/kohana/error.php | 128 + .../system/views/kohana/generate_logo.php | 14 + includes/kohana/system/views/kohana/logo.php | 8 + .../kohana/system/views/profiler/stats.php | 74 + .../kohana/system/views/profiler/style.css | 27 + kh.php | 109 + 520 files changed, 54728 insertions(+) create mode 100644 .htaccess create mode 100644 application/bootstrap.php create mode 100644 application/classes/controller/welcome.php create mode 100644 includes/kohana/DEVELOPERS.md create mode 100644 includes/kohana/LICENSE.md create mode 100644 includes/kohana/README.md create mode 100644 includes/kohana/build.xml create mode 100644 includes/kohana/example.htaccess create mode 100644 includes/kohana/install.php create mode 100644 includes/kohana/modules/auth/classes/auth.php create mode 100644 includes/kohana/modules/auth/classes/auth/file.php create mode 100644 includes/kohana/modules/auth/classes/auth/orm.php create mode 100644 includes/kohana/modules/auth/classes/kohana/auth.php create mode 100644 includes/kohana/modules/auth/classes/kohana/auth/file.php create mode 100644 includes/kohana/modules/auth/classes/kohana/auth/orm.php create mode 100644 includes/kohana/modules/auth/classes/model/auth/role.php create mode 100644 includes/kohana/modules/auth/classes/model/auth/user.php create mode 100644 includes/kohana/modules/auth/classes/model/auth/user/token.php create mode 100644 includes/kohana/modules/auth/classes/model/role.php create mode 100644 includes/kohana/modules/auth/classes/model/user.php create mode 100644 includes/kohana/modules/auth/classes/model/user/token.php create mode 100644 includes/kohana/modules/auth/config/auth.php create mode 100644 includes/kohana/modules/auth/config/userguide.php create mode 100644 includes/kohana/modules/auth/guide/auth/config.md create mode 100644 includes/kohana/modules/auth/guide/auth/edit.md create mode 100644 includes/kohana/modules/auth/guide/auth/index.md create mode 100644 includes/kohana/modules/auth/guide/auth/login.md create mode 100644 includes/kohana/modules/auth/guide/auth/menu.md create mode 100644 includes/kohana/modules/auth/guide/auth/register.md create mode 100644 includes/kohana/modules/auth/guide/auth/roles.md create mode 100644 includes/kohana/modules/auth/guide/auth/user.md create mode 100644 includes/kohana/modules/auth/mysql.sql create mode 100644 includes/kohana/modules/auth/postgresql.sql create mode 100644 includes/kohana/modules/cache/README.md create mode 100644 includes/kohana/modules/cache/classes/cache.php create mode 100644 includes/kohana/modules/cache/classes/cache/apc.php create mode 100644 includes/kohana/modules/cache/classes/cache/eaccelerator.php create mode 100644 includes/kohana/modules/cache/classes/cache/file.php create mode 100644 includes/kohana/modules/cache/classes/cache/memcache.php create mode 100644 includes/kohana/modules/cache/classes/cache/memcachetag.php create mode 100644 includes/kohana/modules/cache/classes/cache/sqlite.php create mode 100644 includes/kohana/modules/cache/classes/cache/wincache.php create mode 100644 includes/kohana/modules/cache/classes/cache/xcache.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/apc.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/eaccelerator.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/exception.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/file.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/garbagecollect.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/memcache.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/memcachetag.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/sqlite.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/tagging.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/wincache.php create mode 100644 includes/kohana/modules/cache/classes/kohana/cache/xcache.php create mode 100644 includes/kohana/modules/cache/config/cache.php create mode 100644 includes/kohana/modules/cache/config/userguide.php create mode 100644 includes/kohana/modules/cache/guide/cache.usage.md create mode 100644 includes/kohana/modules/cache/guide/cache/config.md create mode 100644 includes/kohana/modules/cache/guide/cache/examples.md create mode 100644 includes/kohana/modules/cache/guide/cache/index.md create mode 100644 includes/kohana/modules/cache/guide/cache/menu.md create mode 100644 includes/kohana/modules/cache/guide/cache/usage.md create mode 100644 includes/kohana/modules/cache/tests/cache/KohanaCacheTest.php create mode 100644 includes/kohana/modules/cache/tests/phpunit.xml create mode 100644 includes/kohana/modules/codebench/classes/bench/arrcallback.php create mode 100644 includes/kohana/modules/codebench/classes/bench/autolinkemails.php create mode 100644 includes/kohana/modules/codebench/classes/bench/datespan.php create mode 100644 includes/kohana/modules/codebench/classes/bench/explodelimit.php create mode 100644 includes/kohana/modules/codebench/classes/bench/gruberurl.php create mode 100644 includes/kohana/modules/codebench/classes/bench/ltrimdigits.php create mode 100644 includes/kohana/modules/codebench/classes/bench/mddobaseurl.php create mode 100644 includes/kohana/modules/codebench/classes/bench/mddoimageurl.php create mode 100644 includes/kohana/modules/codebench/classes/bench/mddoincludeviews.php create mode 100644 includes/kohana/modules/codebench/classes/bench/stripnullbytes.php create mode 100644 includes/kohana/modules/codebench/classes/bench/transliterate.php create mode 100644 includes/kohana/modules/codebench/classes/bench/urlsite.php create mode 100644 includes/kohana/modules/codebench/classes/bench/userfuncarray.php create mode 100644 includes/kohana/modules/codebench/classes/bench/validcolor.php create mode 100644 includes/kohana/modules/codebench/classes/bench/validurl.php create mode 100644 includes/kohana/modules/codebench/classes/codebench.php create mode 100644 includes/kohana/modules/codebench/classes/controller/codebench.php create mode 100644 includes/kohana/modules/codebench/classes/kohana/codebench.php create mode 100644 includes/kohana/modules/codebench/config/codebench.php create mode 100644 includes/kohana/modules/codebench/config/userguide.php create mode 100644 includes/kohana/modules/codebench/guide/codebench/index.md create mode 100644 includes/kohana/modules/codebench/guide/codebench/menu.md create mode 100644 includes/kohana/modules/codebench/init.php create mode 100755 includes/kohana/modules/codebench/media/guide/codebench/codebench_screenshot1.png create mode 100755 includes/kohana/modules/codebench/media/guide/codebench/codebench_screenshot2.png create mode 100644 includes/kohana/modules/codebench/views/codebench.php create mode 100644 includes/kohana/modules/database/classes/database.php create mode 100644 includes/kohana/modules/database/classes/database/exception.php create mode 100644 includes/kohana/modules/database/classes/database/expression.php create mode 100644 includes/kohana/modules/database/classes/database/mysql.php create mode 100644 includes/kohana/modules/database/classes/database/mysql/result.php create mode 100644 includes/kohana/modules/database/classes/database/pdo.php create mode 100644 includes/kohana/modules/database/classes/database/query.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder/delete.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder/insert.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder/join.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder/select.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder/update.php create mode 100644 includes/kohana/modules/database/classes/database/query/builder/where.php create mode 100644 includes/kohana/modules/database/classes/database/result.php create mode 100644 includes/kohana/modules/database/classes/database/result/cached.php create mode 100644 includes/kohana/modules/database/classes/db.php create mode 100644 includes/kohana/modules/database/classes/kohana/config/database.php create mode 100644 includes/kohana/modules/database/classes/kohana/database.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/exception.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/expression.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/mysql.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/mysql/result.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/pdo.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder/delete.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder/insert.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder/join.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder/select.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder/update.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/query/builder/where.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/result.php create mode 100644 includes/kohana/modules/database/classes/kohana/database/result/cached.php create mode 100644 includes/kohana/modules/database/classes/kohana/db.php create mode 100644 includes/kohana/modules/database/classes/kohana/session/database.php create mode 100644 includes/kohana/modules/database/classes/session/database.php create mode 100644 includes/kohana/modules/database/config/database.php create mode 100644 includes/kohana/modules/database/config/session.php create mode 100644 includes/kohana/modules/database/config/userguide.php create mode 100644 includes/kohana/modules/database/guide/database/config.md create mode 100644 includes/kohana/modules/database/guide/database/examples.md create mode 100644 includes/kohana/modules/database/guide/database/index.md create mode 100644 includes/kohana/modules/database/guide/database/menu.md create mode 100644 includes/kohana/modules/database/guide/database/query.md create mode 100644 includes/kohana/modules/database/guide/database/query/builder.md create mode 100644 includes/kohana/modules/database/guide/database/query/prepared.md create mode 100644 includes/kohana/modules/database/guide/database/results.md create mode 100644 includes/kohana/modules/image/README.markdown create mode 100644 includes/kohana/modules/image/classes/image.php create mode 100644 includes/kohana/modules/image/classes/image/gd.php create mode 100644 includes/kohana/modules/image/classes/kohana/image.php create mode 100644 includes/kohana/modules/image/classes/kohana/image/gd.php create mode 100644 includes/kohana/modules/image/config/userguide.php create mode 100644 includes/kohana/modules/image/guide/image/examples.md create mode 100644 includes/kohana/modules/image/guide/image/index.md create mode 100644 includes/kohana/modules/image/guide/image/menu.md create mode 100644 includes/kohana/modules/image/guide/image/using.md create mode 100755 includes/kohana/modules/oauth/README.md create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/consumer.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/exception.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/provider.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/provider/google.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/provider/twitter.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/request.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/request/access.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/request/authorize.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/request/credentials.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/request/resource.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/request/token.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/response.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/server.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/signature.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/signature/hmac/sha1.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/signature/plaintext.php create mode 100755 includes/kohana/modules/oauth/classes/kohana/oauth/token.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/token/access.php create mode 100644 includes/kohana/modules/oauth/classes/kohana/oauth/token/request.php create mode 100644 includes/kohana/modules/oauth/classes/oauth.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/consumer.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/provider.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/provider/google.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/provider/twitter.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/request.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/request/access.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/request/authorize.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/request/credentials.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/request/resource.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/request/token.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/response.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/signature.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/signature/hmac/sha1.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/signature/plaintext.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/token.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/token/access.php create mode 100644 includes/kohana/modules/oauth/classes/oauth/token/request.php create mode 100644 includes/kohana/modules/oauth/config/oauth.php create mode 100644 includes/kohana/modules/oauth/config/userguide.php create mode 100644 includes/kohana/modules/oauth/guide/oauth/config.md create mode 100644 includes/kohana/modules/oauth/guide/oauth/index.md create mode 100644 includes/kohana/modules/oauth/guide/oauth/menu.md create mode 100644 includes/kohana/modules/oauth/guide/oauth/usage.md create mode 100644 includes/kohana/modules/oauth/views/oauth/twitter/tweet.php create mode 100644 includes/kohana/modules/orm/classes/kohana/orm.php create mode 100644 includes/kohana/modules/orm/classes/orm.php create mode 100644 includes/kohana/modules/orm/config/userguide.php create mode 100644 includes/kohana/modules/orm/guide/orm/examples.md create mode 100644 includes/kohana/modules/orm/guide/orm/examples/simple.md create mode 100644 includes/kohana/modules/orm/guide/orm/index.md create mode 100644 includes/kohana/modules/orm/guide/orm/menu.md create mode 100644 includes/kohana/modules/orm/guide/orm/models.md create mode 100644 includes/kohana/modules/orm/guide/orm/relationships.md create mode 100644 includes/kohana/modules/orm/guide/orm/tutorials.md create mode 100644 includes/kohana/modules/orm/guide/orm/using.md create mode 100644 includes/kohana/modules/orm/guide/orm/validation.md create mode 100644 includes/kohana/modules/pagination/classes/kohana/pagination.php create mode 100644 includes/kohana/modules/pagination/classes/pagination.php create mode 100644 includes/kohana/modules/pagination/config/pagination.php create mode 100644 includes/kohana/modules/pagination/config/userguide.php create mode 100644 includes/kohana/modules/pagination/guide/pagination/config.md create mode 100644 includes/kohana/modules/pagination/guide/pagination/examples.md create mode 100644 includes/kohana/modules/pagination/guide/pagination/index.md create mode 100644 includes/kohana/modules/pagination/guide/pagination/menu.md create mode 100644 includes/kohana/modules/pagination/guide/pagination/usage.md create mode 100644 includes/kohana/modules/pagination/views/pagination/basic.php create mode 100644 includes/kohana/modules/pagination/views/pagination/floating.php create mode 100644 includes/kohana/modules/unittest/README.markdown create mode 100644 includes/kohana/modules/unittest/bootstrap.php create mode 100644 includes/kohana/modules/unittest/classes/controller/unittest.php create mode 100644 includes/kohana/modules/unittest/classes/kohana/tests.php create mode 100644 includes/kohana/modules/unittest/classes/kohana/unittest/database/testcase.php create mode 100644 includes/kohana/modules/unittest/classes/kohana/unittest/helpers.php create mode 100644 includes/kohana/modules/unittest/classes/kohana/unittest/runner.php create mode 100644 includes/kohana/modules/unittest/classes/kohana/unittest/testcase.php create mode 100644 includes/kohana/modules/unittest/config/unittest.php create mode 100644 includes/kohana/modules/unittest/config/userguide.php create mode 100644 includes/kohana/modules/unittest/example.phpunit.xml create mode 100644 includes/kohana/modules/unittest/guide/unittest/index.md create mode 100644 includes/kohana/modules/unittest/guide/unittest/installing.md create mode 100644 includes/kohana/modules/unittest/guide/unittest/menu.md create mode 100644 includes/kohana/modules/unittest/guide/unittest/mockobjects.md create mode 100644 includes/kohana/modules/unittest/guide/unittest/testing.md create mode 100644 includes/kohana/modules/unittest/guide/unittest/troubleshooting.md create mode 100644 includes/kohana/modules/unittest/guide/unittest/workflows.md create mode 100644 includes/kohana/modules/unittest/init.php create mode 100644 includes/kohana/modules/unittest/tests.php create mode 100644 includes/kohana/modules/unittest/views/unittest/index.php create mode 100644 includes/kohana/modules/unittest/views/unittest/layout.php create mode 100644 includes/kohana/modules/unittest/views/unittest/results.php create mode 100644 includes/kohana/modules/userguide/README.md create mode 100644 includes/kohana/modules/userguide/classes/controller/userguide.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc/class.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc/markdown.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc/method.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc/method/param.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc/missing.php create mode 100644 includes/kohana/modules/userguide/classes/kodoc/property.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc/class.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc/markdown.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc/method.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc/method/param.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc/missing.php create mode 100644 includes/kohana/modules/userguide/classes/kohana/kodoc/property.php create mode 100644 includes/kohana/modules/userguide/config/userguide.php create mode 100644 includes/kohana/modules/userguide/guide/de-de/about.conventions.md create mode 100644 includes/kohana/modules/userguide/guide/de-de/about.kohana.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/adding.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/config.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/contributing.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/index.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/markdown.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/menu.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/modules.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/using.md create mode 100644 includes/kohana/modules/userguide/guide/userguide/works.md create mode 100644 includes/kohana/modules/userguide/i18n/de.php create mode 100644 includes/kohana/modules/userguide/i18n/es.php create mode 100644 includes/kohana/modules/userguide/i18n/fr.php create mode 100644 includes/kohana/modules/userguide/i18n/he.php create mode 100644 includes/kohana/modules/userguide/i18n/nl.php create mode 100644 includes/kohana/modules/userguide/i18n/ru.php create mode 100644 includes/kohana/modules/userguide/i18n/zh.php create mode 100644 includes/kohana/modules/userguide/init.php create mode 100644 includes/kohana/modules/userguide/media/guide/css/api.css create mode 100644 includes/kohana/modules/userguide/media/guide/css/kodoc.css create mode 100644 includes/kohana/modules/userguide/media/guide/css/print.css create mode 100644 includes/kohana/modules/userguide/media/guide/css/screen.css create mode 100644 includes/kohana/modules/userguide/media/guide/css/shCore.css create mode 100644 includes/kohana/modules/userguide/media/guide/css/shThemeDefault.css create mode 100644 includes/kohana/modules/userguide/media/guide/css/shThemeKodoc.css create mode 100755 includes/kohana/modules/userguide/media/guide/img/arrows.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/breadcrumbs.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/content.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/ext_link.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/h2_line.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/h3_line.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/header.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/kohana.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/lightbulb_48.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/lines.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/orange-tab.png create mode 100644 includes/kohana/modules/userguide/media/guide/img/wrapper.png create mode 100644 includes/kohana/modules/userguide/media/guide/js/jquery.cookie.js create mode 100644 includes/kohana/modules/userguide/media/guide/js/jquery.min.js create mode 100644 includes/kohana/modules/userguide/media/guide/js/kodoc.js create mode 100644 includes/kohana/modules/userguide/media/guide/js/shBrushPhp.js create mode 100644 includes/kohana/modules/userguide/media/guide/js/shCore.js create mode 100644 includes/kohana/modules/userguide/media/guide/js/sizzle.js create mode 100755 includes/kohana/modules/userguide/media/guide/userguide/contrib-github-edit.png create mode 100755 includes/kohana/modules/userguide/media/guide/userguide/contrib-github-fork.png create mode 100755 includes/kohana/modules/userguide/media/guide/userguide/contrib-github-pull.png create mode 100644 includes/kohana/modules/userguide/messages/userguide.php create mode 100755 includes/kohana/modules/userguide/vendor/markdown/License.text create mode 100755 includes/kohana/modules/userguide/vendor/markdown/markdown.php create mode 100644 includes/kohana/modules/userguide/views/userguide/api/class.php create mode 100644 includes/kohana/modules/userguide/views/userguide/api/menu.php create mode 100644 includes/kohana/modules/userguide/views/userguide/api/method.php create mode 100644 includes/kohana/modules/userguide/views/userguide/api/tags.php create mode 100644 includes/kohana/modules/userguide/views/userguide/api/toc.php create mode 100644 includes/kohana/modules/userguide/views/userguide/error.php create mode 100644 includes/kohana/modules/userguide/views/userguide/examples/error.php create mode 100644 includes/kohana/modules/userguide/views/userguide/examples/hello_world_error.php create mode 100644 includes/kohana/modules/userguide/views/userguide/index.php create mode 100644 includes/kohana/modules/userguide/views/userguide/menu.php create mode 100644 includes/kohana/modules/userguide/views/userguide/page-toc.php create mode 100644 includes/kohana/modules/userguide/views/userguide/template.php create mode 100644 includes/kohana/system/base.php create mode 100644 includes/kohana/system/classes/arr.php create mode 100644 includes/kohana/system/classes/cli.php create mode 100644 includes/kohana/system/classes/controller.php create mode 100644 includes/kohana/system/classes/controller/rest.php create mode 100644 includes/kohana/system/classes/controller/template.php create mode 100644 includes/kohana/system/classes/cookie.php create mode 100644 includes/kohana/system/classes/date.php create mode 100644 includes/kohana/system/classes/encrypt.php create mode 100644 includes/kohana/system/classes/feed.php create mode 100644 includes/kohana/system/classes/file.php create mode 100644 includes/kohana/system/classes/form.php create mode 100644 includes/kohana/system/classes/fragment.php create mode 100644 includes/kohana/system/classes/html.php create mode 100644 includes/kohana/system/classes/i18n.php create mode 100644 includes/kohana/system/classes/inflector.php create mode 100644 includes/kohana/system/classes/kohana.php create mode 100644 includes/kohana/system/classes/kohana/arr.php create mode 100644 includes/kohana/system/classes/kohana/cli.php create mode 100644 includes/kohana/system/classes/kohana/config.php create mode 100644 includes/kohana/system/classes/kohana/config/file.php create mode 100644 includes/kohana/system/classes/kohana/config/reader.php create mode 100644 includes/kohana/system/classes/kohana/controller.php create mode 100644 includes/kohana/system/classes/kohana/controller/rest.php create mode 100644 includes/kohana/system/classes/kohana/controller/template.php create mode 100644 includes/kohana/system/classes/kohana/cookie.php create mode 100644 includes/kohana/system/classes/kohana/core.php create mode 100644 includes/kohana/system/classes/kohana/date.php create mode 100644 includes/kohana/system/classes/kohana/encrypt.php create mode 100644 includes/kohana/system/classes/kohana/exception.php create mode 100644 includes/kohana/system/classes/kohana/feed.php create mode 100644 includes/kohana/system/classes/kohana/file.php create mode 100644 includes/kohana/system/classes/kohana/form.php create mode 100644 includes/kohana/system/classes/kohana/fragment.php create mode 100644 includes/kohana/system/classes/kohana/html.php create mode 100644 includes/kohana/system/classes/kohana/i18n.php create mode 100644 includes/kohana/system/classes/kohana/inflector.php create mode 100644 includes/kohana/system/classes/kohana/log.php create mode 100644 includes/kohana/system/classes/kohana/log/file.php create mode 100644 includes/kohana/system/classes/kohana/log/stderr.php create mode 100644 includes/kohana/system/classes/kohana/log/stdout.php create mode 100644 includes/kohana/system/classes/kohana/log/syslog.php create mode 100644 includes/kohana/system/classes/kohana/log/writer.php create mode 100644 includes/kohana/system/classes/kohana/model.php create mode 100644 includes/kohana/system/classes/kohana/num.php create mode 100644 includes/kohana/system/classes/kohana/profiler.php create mode 100644 includes/kohana/system/classes/kohana/remote.php create mode 100644 includes/kohana/system/classes/kohana/request.php create mode 100644 includes/kohana/system/classes/kohana/request/exception.php create mode 100644 includes/kohana/system/classes/kohana/route.php create mode 100644 includes/kohana/system/classes/kohana/security.php create mode 100644 includes/kohana/system/classes/kohana/session.php create mode 100644 includes/kohana/system/classes/kohana/session/cookie.php create mode 100644 includes/kohana/system/classes/kohana/session/native.php create mode 100644 includes/kohana/system/classes/kohana/text.php create mode 100644 includes/kohana/system/classes/kohana/upload.php create mode 100644 includes/kohana/system/classes/kohana/url.php create mode 100644 includes/kohana/system/classes/kohana/utf8.php create mode 100644 includes/kohana/system/classes/kohana/validate.php create mode 100644 includes/kohana/system/classes/kohana/validate/exception.php create mode 100644 includes/kohana/system/classes/kohana/view.php create mode 100644 includes/kohana/system/classes/kohana/view/exception.php create mode 100644 includes/kohana/system/classes/model.php create mode 100644 includes/kohana/system/classes/num.php create mode 100644 includes/kohana/system/classes/profiler.php create mode 100644 includes/kohana/system/classes/remote.php create mode 100644 includes/kohana/system/classes/request.php create mode 100644 includes/kohana/system/classes/route.php create mode 100644 includes/kohana/system/classes/security.php create mode 100644 includes/kohana/system/classes/session.php create mode 100644 includes/kohana/system/classes/session/cookie.php create mode 100644 includes/kohana/system/classes/session/native.php create mode 100644 includes/kohana/system/classes/text.php create mode 100644 includes/kohana/system/classes/upload.php create mode 100644 includes/kohana/system/classes/url.php create mode 100644 includes/kohana/system/classes/utf8.php create mode 100644 includes/kohana/system/classes/validate.php create mode 100644 includes/kohana/system/classes/validate/exception.php create mode 100644 includes/kohana/system/classes/view.php create mode 100644 includes/kohana/system/config/credit_cards.php create mode 100644 includes/kohana/system/config/encrypt.php create mode 100644 includes/kohana/system/config/inflector.php create mode 100644 includes/kohana/system/config/mimes.php create mode 100644 includes/kohana/system/config/session.php create mode 100644 includes/kohana/system/config/user_agents.php create mode 100644 includes/kohana/system/config/userguide.php create mode 100644 includes/kohana/system/guide/kohana/autoloading.md create mode 100644 includes/kohana/system/guide/kohana/bootstrap.md create mode 100644 includes/kohana/system/guide/kohana/controllers.md create mode 100644 includes/kohana/system/guide/kohana/conventions.md create mode 100644 includes/kohana/system/guide/kohana/cookies.md create mode 100644 includes/kohana/system/guide/kohana/debugging.md create mode 100644 includes/kohana/system/guide/kohana/errors.md create mode 100644 includes/kohana/system/guide/kohana/extension.md create mode 100644 includes/kohana/system/guide/kohana/files.md create mode 100644 includes/kohana/system/guide/kohana/files/classes.md create mode 100644 includes/kohana/system/guide/kohana/files/config.md create mode 100644 includes/kohana/system/guide/kohana/files/i18n.md create mode 100644 includes/kohana/system/guide/kohana/files/messages.md create mode 100644 includes/kohana/system/guide/kohana/flow.md create mode 100644 includes/kohana/system/guide/kohana/fragments.md create mode 100644 includes/kohana/system/guide/kohana/helpers.md create mode 100644 includes/kohana/system/guide/kohana/index.md create mode 100644 includes/kohana/system/guide/kohana/install.md create mode 100644 includes/kohana/system/guide/kohana/menu.md create mode 100644 includes/kohana/system/guide/kohana/models.md create mode 100644 includes/kohana/system/guide/kohana/modules.md create mode 100644 includes/kohana/system/guide/kohana/mvc.md create mode 100644 includes/kohana/system/guide/kohana/mvc/controllers.md create mode 100644 includes/kohana/system/guide/kohana/mvc/models.md create mode 100644 includes/kohana/system/guide/kohana/mvc/views.md create mode 100644 includes/kohana/system/guide/kohana/profiling.md create mode 100644 includes/kohana/system/guide/kohana/requests.md create mode 100644 includes/kohana/system/guide/kohana/routing.md create mode 100644 includes/kohana/system/guide/kohana/security.md create mode 100644 includes/kohana/system/guide/kohana/security/cookies.md create mode 100644 includes/kohana/system/guide/kohana/security/database.md create mode 100644 includes/kohana/system/guide/kohana/security/deploying.md create mode 100644 includes/kohana/system/guide/kohana/security/encryption.md create mode 100644 includes/kohana/system/guide/kohana/security/validation.md create mode 100644 includes/kohana/system/guide/kohana/security/xss.md create mode 100644 includes/kohana/system/guide/kohana/sessions.md create mode 100644 includes/kohana/system/guide/kohana/tips.md create mode 100644 includes/kohana/system/guide/kohana/tutorials.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/clean-urls.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/error-pages.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/git.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/hello-world.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/routes-and-links.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/sharing-kohana.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/simple-mvc.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/templates.md create mode 100644 includes/kohana/system/guide/kohana/tutorials/translation.md create mode 100644 includes/kohana/system/guide/kohana/upgrading.md create mode 100644 includes/kohana/system/i18n/en.php create mode 100644 includes/kohana/system/i18n/es.php create mode 100644 includes/kohana/system/i18n/fr.php create mode 100644 includes/kohana/system/media/guide/kohana/cascading_filesystem.png create mode 100644 includes/kohana/system/media/guide/kohana/hello_world_1.png create mode 100644 includes/kohana/system/media/guide/kohana/hello_world_2.png create mode 100644 includes/kohana/system/media/guide/kohana/hello_world_2_error.png create mode 100644 includes/kohana/system/media/guide/kohana/install.png create mode 100755 includes/kohana/system/media/guide/kohana/welcome.png create mode 100644 includes/kohana/system/messages/validate.php create mode 100644 includes/kohana/system/tests/kohana/ArrTest.php create mode 100644 includes/kohana/system/tests/kohana/CLITest.php create mode 100644 includes/kohana/system/tests/kohana/ConfigTest.php create mode 100644 includes/kohana/system/tests/kohana/CookieTest.php create mode 100644 includes/kohana/system/tests/kohana/CoreTest.php create mode 100644 includes/kohana/system/tests/kohana/DateTest.php create mode 100644 includes/kohana/system/tests/kohana/FeedTest.php create mode 100644 includes/kohana/system/tests/kohana/FileTest.php create mode 100644 includes/kohana/system/tests/kohana/FormTest.php create mode 100644 includes/kohana/system/tests/kohana/HTMLTest.php create mode 100644 includes/kohana/system/tests/kohana/I18nTest.php create mode 100644 includes/kohana/system/tests/kohana/InflectorTest.php create mode 100644 includes/kohana/system/tests/kohana/LogTest.php create mode 100644 includes/kohana/system/tests/kohana/ModelTest.php create mode 100644 includes/kohana/system/tests/kohana/NumTest.php create mode 100644 includes/kohana/system/tests/kohana/RemoteTest.php create mode 100644 includes/kohana/system/tests/kohana/RequestTest.php create mode 100644 includes/kohana/system/tests/kohana/RouteTest.php create mode 100644 includes/kohana/system/tests/kohana/SecurityTest.php create mode 100644 includes/kohana/system/tests/kohana/SessionTest.php create mode 100644 includes/kohana/system/tests/kohana/TextTest.php create mode 100644 includes/kohana/system/tests/kohana/URLTest.php create mode 100644 includes/kohana/system/tests/kohana/UTF8Test.php create mode 100644 includes/kohana/system/tests/kohana/UploadTest.php create mode 100644 includes/kohana/system/tests/kohana/ValidateTest.php create mode 100644 includes/kohana/system/tests/test_data/github.png create mode 100644 includes/kohana/system/utf8/from_unicode.php create mode 100644 includes/kohana/system/utf8/ltrim.php create mode 100644 includes/kohana/system/utf8/ord.php create mode 100644 includes/kohana/system/utf8/rtrim.php create mode 100644 includes/kohana/system/utf8/str_ireplace.php create mode 100644 includes/kohana/system/utf8/str_pad.php create mode 100644 includes/kohana/system/utf8/str_split.php create mode 100644 includes/kohana/system/utf8/strcasecmp.php create mode 100644 includes/kohana/system/utf8/strcspn.php create mode 100644 includes/kohana/system/utf8/stristr.php create mode 100644 includes/kohana/system/utf8/strlen.php create mode 100644 includes/kohana/system/utf8/strpos.php create mode 100644 includes/kohana/system/utf8/strrev.php create mode 100644 includes/kohana/system/utf8/strrpos.php create mode 100644 includes/kohana/system/utf8/strspn.php create mode 100644 includes/kohana/system/utf8/strtolower.php create mode 100644 includes/kohana/system/utf8/strtoupper.php create mode 100644 includes/kohana/system/utf8/substr.php create mode 100644 includes/kohana/system/utf8/substr_replace.php create mode 100644 includes/kohana/system/utf8/to_unicode.php create mode 100644 includes/kohana/system/utf8/transliterate_to_ascii.php create mode 100644 includes/kohana/system/utf8/trim.php create mode 100644 includes/kohana/system/utf8/ucfirst.php create mode 100644 includes/kohana/system/utf8/ucwords.php create mode 100644 includes/kohana/system/views/kohana/error.php create mode 100644 includes/kohana/system/views/kohana/generate_logo.php create mode 100644 includes/kohana/system/views/kohana/logo.php create mode 100755 includes/kohana/system/views/profiler/stats.php create mode 100644 includes/kohana/system/views/profiler/style.css create mode 100644 kh.php diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..62322fc --- /dev/null +++ b/.htaccess @@ -0,0 +1,21 @@ +# Turn on URL rewriting +RewriteEngine On + +# Installation directory +RewriteBase /pta/ + +# Protect hidden files from being viewed + + Order Deny,Allow + Deny From All + + +# Protect application and system files from being viewed +RewriteRule ^(?:application|modules|includes/kohana)\b.* kh.php/$0 [L] + +# Allow any files or directories that exist to be displayed directly +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d + +# Rewrite all other URLs to kh.php/URL +RewriteRule .* kh.php/$0 [PT] diff --git a/application/bootstrap.php b/application/bootstrap.php new file mode 100644 index 0000000..72bdd15 --- /dev/null +++ b/application/bootstrap.php @@ -0,0 +1,110 @@ + '/', +)); + +/** + * Attach the file write to logging. Multiple writers are supported. + */ +Kohana::$log->attach(new Kohana_Log_File(APPPATH.'logs')); + +/** + * Attach a file reader to config. Multiple readers are supported. + */ +Kohana::$config->attach(new Kohana_Config_File); + +/** + * Enable modules. Modules are referenced by a relative or absolute path. + */ +Kohana::modules(array( + // 'auth' => MODPATH.'auth', // Basic authentication + // 'cache' => MODPATH.'cache', // Caching with multiple backends + // 'codebench' => MODPATH.'codebench', // Benchmarking tool + // 'database' => MODPATH.'database', // Database access + // 'image' => MODPATH.'image', // Image manipulation + // 'orm' => MODPATH.'orm', // Object Relationship Mapping + // 'oauth' => MODPATH.'oauth', // OAuth authentication + // 'pagination' => MODPATH.'pagination', // Paging of results + // 'unittest' => MODPATH.'unittest', // Unit testing + // 'userguide' => MODPATH.'userguide', // User guide and API documentation + )); + +/** + * Set the routes. Each route must have a minimum of a name, a URI and a set of + * defaults for the URI. + */ +Route::set('default', '((/(/)))') + ->defaults(array( + 'controller' => 'welcome', + 'action' => 'index', + )); + +if ( ! defined('SUPPRESS_REQUEST')) +{ + /** + * Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO']. + * If no source is specified, the URI will be automatically detected. + */ + echo Request::instance() + ->execute() + ->send_headers() + ->response; +} diff --git a/application/classes/controller/welcome.php b/application/classes/controller/welcome.php new file mode 100644 index 0000000..e3b27d6 --- /dev/null +++ b/application/classes/controller/welcome.php @@ -0,0 +1,10 @@ +request->response = 'hello, world!'; + } + +} // End Welcome diff --git a/includes/kohana/DEVELOPERS.md b/includes/kohana/DEVELOPERS.md new file mode 100644 index 0000000..c157592 --- /dev/null +++ b/includes/kohana/DEVELOPERS.md @@ -0,0 +1,147 @@ +# Distributed Source Control Management + +Unlike SVN, git does not used a central repository. This is why git is "distributed" and SVN is +"centralized". Although this makes git an extremely powerful system for collaborators, tracking +changes between various collaborators can quickly become difficult as multiple forks are created. + +Please read the following before working with this code: + +1. [Dealing with newlines](http://github.com/guides/dealing-with-newlines-in-git) +2. [Submitting changes from your fork](http://github.com/guides/fork-a-project-and-submit-your-modifications) +3. [Using SSH keys with github](http://github.com/guides/how-to-not-have-to-type-your-password-for-every-push) + +## Managing Remote Repositories + +First, you will need to tell git about the remote repository: + + > git remote add kohana git://github.com/kohana/kohana.git + +This tells git about the kohana repository and gives it a name which we can use to refer to it when +fetching changes from the repository. + +## Developing locally + +There are 3 branches in the kohana/kohana repository: + +* **master** This branch always points to the latest release tag. In essence it points to the last stable edition of the codebase +* **3.0.x** This is a release branch for development of the 3.0.x series, i.e. 3.0, 3.0.3, 3.0.8 etc. +* **3.1.x** This is a release branch for development of the 3.1.x series, i.e. 3.1, 3.1.4, 3.1.14 etc. + +To work on a specific release branch you need to check it out then check out the appropriate system branch. +Release branch names follow the same convention in both kohana/kohana and kohana/core. + +To work on 3.0.x you'd do the following: + + > git clone git://github.com/kohana/kohana.git + # .... + + > cd kohana + > git submodule update --init + # .... + + > git checkout 3.0.x + # Switched to branch '3.0.x' + + > cd system + > git checkout 3.0.x + # Switched to branch 3.0.x + +It's important that you follow the last step, because unlike svn, git submodules point at a +specific commit rather than the tip of a branch. If you cd into the system folder after +a `git submodule update` and run `git status` you'll be told: + + # Not currently on any branch. + nothing to commit (working directory clean) + +**IMPORTANT:** It is highly recommended that you run the unit tests whilst developing to +ensure that any changes you make do not break the api. *See TESTING.md for more info* + +### Creating new features + +New features or API breaking modifications should be developed in separate branches so as to isolate them +until they're stable and **tests have been written for the feature**. + +The naming convention for feature branches is: + + feature/{issue number}-{short hyphenated description} + + // i.e. + + feature/4045-rewriting-config-system + +When a new feature is complete and tested it can be merged into its respective release branch using +`git pull --no-ff`. The `--no-ff` switch is important as it tells git to always create a commit +detailing what branch you're merging from. This makes it a lot easier to analyse a feature's history. + +Here's a quick example: + + > git status + # On branch feature/4045-rewriting-everything + + > git checkout 3.1.x + # Switched to branch '3.1.x' + + > git merge --no-ff feature/4045-rewriting-everything + +**If a change you make intentionally breaks the api then please correct the relevant tests before pushing!** + +### Bug fixing + +If you're making a bugfix then before you start create a unit test which reproduces the bug, +using the `@ticket` notation in the test to reference the bug's issue number +(i.e. `@ticket 4045` for issue #4045). + +If you run the test then the one you've just made should fail. + +Once you've written the bugfix, run the tests again before you commit to make sure that the +fix actually works,then commiti both the fix and the test. + +There is no need to create separate branches for bugfixes, creating them in the main release +branch is perfectly acceptable. + +## Merging Changes from Remote Repositories + +Now that you have a remote repository, you can pull changes in the remote "kohana" repository +into your local repository: + + > git pull kohana master + +**Note:** Before you pull changes you should make sure that any modifications you've made locally +have been committed. + +Sometimes a commit you've made locally will conflict with one made in the "kohana" one. + +There are a couple of scenarios where this might happen: + +### The conflict is to do with a few unrelated commits and you want to keep changes made in both commits + +You'll need to manually modify the files to resolve the conflict, see the "Resolving a merge" +section [in the git-scm book](http://book.git-scm.com/3_basic_branching_and_merging.html) for more info + +### You've fixed something locally which someone else has already done in the remote repo + +The simplest way to fix this is to remove all the changes that you've made locally. + +You can do this using + + > git reset --hard kohana + +### You've fixed something locally which someone else has already fixed but you also have separate commits you'd like to keep + +If this is the case then you'll want to use a tool called rebase. First of all we need to +get rid of the conflicts created due to the merge: + + > git reset --hard HEAD + +Then find the hash of the offending local commit and run: + + > git rebase -i {offending commit hash} + +i.e. + + > git rebase -i 57d0b28 + +A text editor will open with a list of commits, delete the line containing the offending commit +before saving the file & closing your editor. + +Git will remove the commit and you can then pull/merge the remote changes. diff --git a/includes/kohana/LICENSE.md b/includes/kohana/LICENSE.md new file mode 100644 index 0000000..87af9ad --- /dev/null +++ b/includes/kohana/LICENSE.md @@ -0,0 +1,14 @@ +# Kohana License Agreement + +This license is a legal agreement between you and the Kohana Team for the use of Kohana Framework (the "Software"). By obtaining the Software you agree to comply with the terms and conditions of this license. + +Copyright (c) 2007-2010 Kohana Team +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of the Kohana nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/includes/kohana/README.md b/includes/kohana/README.md new file mode 100644 index 0000000..97e31dc --- /dev/null +++ b/includes/kohana/README.md @@ -0,0 +1,3 @@ +# Kohana PHP Framework, version 3.0 (dev) + +This is the current development version of [Kohana](http://kohanaframework.org/). diff --git a/includes/kohana/build.xml b/includes/kohana/build.xml new file mode 100644 index 0000000..daea9ed --- /dev/null +++ b/includes/kohana/build.xml @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/includes/kohana/example.htaccess b/includes/kohana/example.htaccess new file mode 100644 index 0000000..53b8ccb --- /dev/null +++ b/includes/kohana/example.htaccess @@ -0,0 +1,21 @@ +# Turn on URL rewriting +RewriteEngine On + +# Installation directory +RewriteBase / + +# Protect hidden files from being viewed + + Order Deny,Allow + Deny From All + + +# Protect application and system files from being viewed +RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L] + +# Allow any files or directories that exist to be displayed directly +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d + +# Rewrite all other URLs to index.php/URL +RewriteRule .* index.php/$0 [PT] diff --git a/includes/kohana/install.php b/includes/kohana/install.php new file mode 100644 index 0000000..a522c2f --- /dev/null +++ b/includes/kohana/install.php @@ -0,0 +1,217 @@ + + + + + + + + Kohana Installation + + + + + + +

Environment Tests

+ +

+ The following tests have been run to determine if Kohana will work in your environment. + If any of the tests have failed, consult the documentation + for more information on how to correct the problem. +

+ + + + + + + =')): ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PHP VersionKohana requires PHP 5.2.3 or newer, this version is .
System DirectoryThe configured system directory does not exist or does not contain required files.
Application DirectoryThe configured application directory does not exist or does not contain required files.
Cache DirectoryThe directory is not writable.
Logs DirectoryThe directory is not writable.
PCRE UTF-8PCRE has not been compiled with UTF-8 support.PCRE has not been compiled with Unicode property support.Pass
SPL EnabledPassPHP SPL is either not loaded or not compiled in.
Reflection EnabledPassPHP reflection is either not loaded or not compiled in.
Filters EnabledPassThe filter extension is either not loaded or not compiled in.
Iconv Extension LoadedPassThe iconv extension is not loaded.
Mbstring Not OverloadedThe mbstring extension is overloading PHP's native string functions.Pass
Character Type (CTYPE) ExtensionThe ctype extension is not enabled.Pass
URI DeterminationPassNeither $_SERVER['REQUEST_URI'], $_SERVER['PHP_SELF'], or $_SERVER['PATH_INFO'] is available.
+ + +

✘ Kohana may not work correctly with your environment.

+ +

✔ Your environment passed all requirements.
+ Remove or rename the install file now.

+ + +

Optional Tests

+ +

+ The following extensions are not required to run the Kohana core, but if enabled can provide access to additional classes. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
cURL EnabledPassKohana requires cURL for the Remote class.
mcrypt EnabledPassKohana requires mcrypt for the Encrypt class.
GD EnabledPassKohana requires GD v2 for the Image class.
PDO EnabledPassKohana can use PDO to support additional databases.
+ + + diff --git a/includes/kohana/modules/auth/classes/auth.php b/includes/kohana/modules/auth/classes/auth.php new file mode 100644 index 0000000..a02b1e5 --- /dev/null +++ b/includes/kohana/modules/auth/classes/auth.php @@ -0,0 +1,3 @@ +get('driver')) + { + $type = 'ORM'; + } + + // Set the session class name + $class = 'Auth_'.ucfirst($type); + + // Create a new session instance + Auth::$_instance = new $class($config); + } + + return Auth::$_instance; + } + + /** + * Create an instance of Auth. + * + * @return Auth + */ + public static function factory($config = array()) + { + return new Auth($config); + } + + protected $_session; + + protected $_config; + + /** + * Loads Session and configuration options. + * + * @return void + */ + public function __construct($config = array()) + { + // Clean up the salt pattern and split it into an array + $config['salt_pattern'] = preg_split('/,\s*/', Kohana::config('auth')->get('salt_pattern')); + + // Save the config in the object + $this->_config = $config; + + $this->_session = Session::instance(); + } + + abstract protected function _login($username, $password, $remember); + + abstract public function password($username); + + abstract public function check_password($password); + + /** + * Gets the currently logged in user from the session. + * Returns FALSE if no user is currently logged in. + * + * @return mixed + */ + public function get_user() + { + return $this->_session->get($this->_config['session_key'], FALSE); + } + + /** + * Attempt to log in a user by using an ORM object and plain-text password. + * + * @param string username to log in + * @param string password to check against + * @param boolean enable autologin + * @return boolean + */ + public function login($username, $password, $remember = FALSE) + { + if (empty($password)) + return FALSE; + + if (is_string($password)) + { + // Get the salt from the stored password + $salt = $this->find_salt($this->password($username)); + + // Create a hashed password using the salt from the stored password + $password = $this->hash_password($password, $salt); + } + + return $this->_login($username, $password, $remember); + } + + /** + * Log out a user by removing the related session variables. + * + * @param boolean completely destroy the session + * @param boolean remove all tokens for user + * @return boolean + */ + public function logout($destroy = FALSE, $logout_all = FALSE) + { + if ($destroy === TRUE) + { + // Destroy the session completely + $this->_session->destroy(); + } + else + { + // Remove the user from the session + $this->_session->delete($this->_config['session_key']); + + // Regenerate session_id + $this->_session->regenerate(); + } + + // Double check + return ! $this->logged_in(); + } + + /** + * Check if there is an active session. Optionally allows checking for a + * specific role. + * + * @param string role name + * @return mixed + */ + public function logged_in($role = NULL) + { + return FALSE !== $this->get_user(); + } + + /** + * Creates a hashed password from a plaintext password, inserting salt + * based on the configured salt pattern. + * + * @param string plaintext password + * @return string hashed password string + */ + public function hash_password($password, $salt = FALSE) + { + if ($salt === FALSE) + { + // Create a salt seed, same length as the number of offsets in the pattern + $salt = substr($this->hash(uniqid(NULL, TRUE)), 0, count($this->_config['salt_pattern'])); + } + + // Password hash that the salt will be inserted into + $hash = $this->hash($salt.$password); + + // Change salt to an array + $salt = str_split($salt, 1); + + // Returned password + $password = ''; + + // Used to calculate the length of splits + $last_offset = 0; + + foreach ($this->_config['salt_pattern'] as $offset) + { + // Split a new part of the hash off + $part = substr($hash, 0, $offset - $last_offset); + + // Cut the current part out of the hash + $hash = substr($hash, $offset - $last_offset); + + // Add the part to the password, appending the salt character + $password .= $part.array_shift($salt); + + // Set the last offset to the current offset + $last_offset = $offset; + } + + // Return the password, with the remaining hash appended + return $password.$hash; + } + + /** + * Perform a hash, using the configured method. + * + * @param string string to hash + * @return string + */ + public function hash($str) + { + return hash($this->_config['hash_method'], $str); + } + + /** + * Finds the salt from a password, based on the configured salt pattern. + * + * @param string hashed password + * @return string + */ + public function find_salt($password) + { + $salt = ''; + + foreach ($this->_config['salt_pattern'] as $i => $offset) + { + // Find salt characters, take a good long look... + $salt .= substr($password, $offset + $i, 1); + } + + return $salt; + } + + protected function complete_login($user) + { + // Regenerate session_id + $this->_session->regenerate(); + + // Store username in session + $this->_session->set($this->_config['session_key'], $user); + + return TRUE; + } + +} // End Auth \ No newline at end of file diff --git a/includes/kohana/modules/auth/classes/kohana/auth/file.php b/includes/kohana/modules/auth/classes/kohana/auth/file.php new file mode 100644 index 0000000..31ca0c3 --- /dev/null +++ b/includes/kohana/modules/auth/classes/kohana/auth/file.php @@ -0,0 +1,88 @@ +_users = Arr::get($config, 'users', array()); + } + + /** + * Logs a user in. + * + * @param string username + * @param string password + * @param boolean enable autologin (not supported) + * @return boolean + */ + protected function _login($username, $password, $remember) + { + if (isset($this->_users[$username]) AND $this->_users[$username] === $password) + { + // Complete the login + return $this->complete_login($username); + } + + // Login failed + return FALSE; + } + + /** + * Forces a user to be logged in, without specifying a password. + * + * @param mixed username + * @return boolean + */ + public function force_login($username) + { + // Complete the login + return $this->complete_login($username); + } + + /** + * Get the stored password for a username. + * + * @param mixed username + * @return string + */ + public function password($username) + { + return Arr::get($this->_users, $username, FALSE); + } + + /** + * Compare password with original (plain text). Works for current (logged in) user + * + * @param string $password + * @return boolean + */ + public function check_password($password) + { + $username = $this->get_user(); + + if ($username === FALSE) + { + return FALSE; + } + + return ($password === $this->password($username)); + } + +} // End Auth File \ No newline at end of file diff --git a/includes/kohana/modules/auth/classes/kohana/auth/orm.php b/includes/kohana/modules/auth/classes/kohana/auth/orm.php new file mode 100644 index 0000000..48f2bb6 --- /dev/null +++ b/includes/kohana/modules/auth/classes/kohana/auth/orm.php @@ -0,0 +1,322 @@ +get_user(); + + if (is_object($user) AND $user instanceof Model_User AND $user->loaded()) + { + // Everything is okay so far + $status = TRUE; + + if ( ! empty($role)) + { + // Multiple roles to check + if (is_array($role)) + { + // set initial status + $status = (bool) $all_required; + + // Check each role + foreach ($role as $_role) + { + if ( ! is_object($_role)) + { + $_role = ORM::factory('role', array('name' => $_role)); + } + + // If the user doesn't have the role + if ( ! $user->has('roles', $_role)) + { + // Set the status false and get outta here + $status = FALSE; + if ($all_required) + { + break; + } + } + elseif ( ! $all_required ) + { + $status = TRUE; + break; + } + } + } + // Single role to check + else + { + if ( ! is_object($role)) + { + // Load the role + $role = ORM::factory('role', array('name' => $role)); + } + + // Check that the user has the given role + $status = $user->has('roles', $role); + } + } + } + + return $status; + } + + /** + * Logs a user in. + * + * @param string username + * @param string password + * @param boolean enable autologin + * @return boolean + */ + protected function _login($user, $password, $remember) + { + if ( ! is_object($user)) + { + $username = $user; + + // Load the user + $user = ORM::factory('user'); + $user->where($user->unique_key($username), '=', $username)->find(); + } + + // If the passwords match, perform a login + if ($user->has('roles', ORM::factory('role', array('name' => 'login'))) AND $user->password === $password) + { + if ($remember === TRUE) + { + $this->remember($user); + } + + // Finish the login + $this->complete_login($user); + + return TRUE; + } + + // Login failed + return FALSE; + } + + /** + * Forces a user to be logged in, without specifying a password. + * + * @param mixed username string, or user ORM object + * @param boolean mark the session as forced + * @return boolean + */ + public function force_login($user, $mark_session_as_forced = FALSE) + { + if ( ! is_object($user)) + { + $username = $user; + + // Load the user + $user = ORM::factory('user'); + $user->where($user->unique_key($username), '=', $username)->find(); + } + + if ($mark_session_as_forced === TRUE) + { + // Mark the session as forced, to prevent users from changing account information + $this->_session->set($this->_config['forced_key'], TRUE); + } + + // Run the standard completion + $this->complete_login($user); + } + + /** + * Logs a user in, based on the authautologin cookie. + * + * @return mixed + */ + public function auto_login() + { + if ($token = Cookie::get($this->_config['autologin_key'])) + { + // Load the token and user + $token = ORM::factory('user_token', array('token' => $token)); + + if ($token->loaded() AND $token->user->loaded()) + { + if ($token->user_agent === sha1(Request::$user_agent)) + { + // Save the token to create a new unique token + $token->save(); + + // Set the new token + Cookie::set($this->_config['autologin_key'], $token->token, $token->expires - time()); + + // Complete the login with the found data + $this->complete_login($token->user); + + // Automatic login was successful + return $token->user; + } + + // Token is invalid + $token->delete(); + } + } + + return FALSE; + } + + /** + * Gets the currently logged in user from the session (with auto_login check). + * Returns FALSE if no user is currently logged in. + * + * @return mixed + */ + public function get_user() + { + $user = parent::get_user(); + + if ($user === FALSE) + { + // check for "remembered" login + $user = $this->auto_login(); + } + + return $user; + } + + /** + * Log a user out and remove any autologin cookies. + * + * @param boolean completely destroy the session + * @param boolean remove all tokens for user + * @return boolean + */ + public function logout($destroy = FALSE, $logout_all = FALSE) + { + // Set by force_login() + $this->_session->delete($this->_config['forced_key']); + + if ($token = Cookie::get($this->_config['autologin_key'])) + { + // Delete the autologin cookie to prevent re-login + Cookie::delete($this->_config['autologin_key']); + + // Clear the autologin token from the database + $token = ORM::factory('user_token', array('token' => $token)); + + if ($token->loaded() AND $logout_all) + { + ORM::factory('user_token')->where('user_id', '=', $token->user_id)->delete_all(); + } + elseif ($token->loaded()) + { + $token->delete(); + } + } + + return parent::logout($destroy); + } + + /** + * Get the stored password for a username. + * + * @param mixed username string, or user ORM object + * @return string + */ + public function password($user) + { + if ( ! is_object($user)) + { + $username = $user; + + // Load the user + $user = ORM::factory('user'); + $user->where($user->unique_key($username), '=', $username)->find(); + } + + return $user->password; + } + + /** + * Complete the login for a user by incrementing the logins and setting + * session data: user_id, username, roles. + * + * @param object user ORM object + * @return void + */ + protected function complete_login($user) + { + $user->complete_login(); + + return parent::complete_login($user); + } + + /** + * Compare password with original (hashed). Works for current (logged in) user + * + * @param string $password + * @return boolean + */ + public function check_password($password) + { + $user = $this->get_user(); + + if ($user === FALSE) + { + // nothing to compare + return FALSE; + } + + $hash = $this->hash_password($password, $this->find_salt($user->password)); + + return $hash == $user->password; + } + + /** + * Remember user (create token and save it in cookie) + * + * @param Model_User $user + * @return boolean + */ + public function remember($user = NULL) + { + if (is_null($user)) + { + $user = $this->get_user(); + } + if ( ! $user) + { + return FALSE; + } + + // Create a new autologin token + $token = ORM::factory('user_token'); + + // Set token data + $token->user_id = $user->id; + $token->expires = time() + $this->_config['lifetime']; + $token->save(); + + // Set the autologin cookie + Cookie::set($this->_config['autologin_key'], $token->token, $this->_config['lifetime']); + + return TRUE; + } + +} // End Auth ORM \ No newline at end of file diff --git a/includes/kohana/modules/auth/classes/model/auth/role.php b/includes/kohana/modules/auth/classes/model/auth/role.php new file mode 100644 index 0000000..565c4f0 --- /dev/null +++ b/includes/kohana/modules/auth/classes/model/auth/role.php @@ -0,0 +1,27 @@ + array('through' => 'roles_users')); + + // Validation rules + protected $_rules = array( + 'name' => array( + 'not_empty' => NULL, + 'min_length' => array(4), + 'max_length' => array(32), + ), + 'description' => array( + 'max_length' => array(255), + ), + ); + +} // End Auth Role Model \ No newline at end of file diff --git a/includes/kohana/modules/auth/classes/model/auth/user.php b/includes/kohana/modules/auth/classes/model/auth/user.php new file mode 100644 index 0000000..35a512d --- /dev/null +++ b/includes/kohana/modules/auth/classes/model/auth/user.php @@ -0,0 +1,244 @@ + array('model' => 'user_token'), + 'roles' => array('model' => 'role', 'through' => 'roles_users'), + ); + + // Validation rules + protected $_rules = array( + 'username' => array( + 'not_empty' => NULL, + 'min_length' => array(4), + 'max_length' => array(32), + 'regex' => array('/^[-\pL\pN_.]++$/uD'), + ), + 'password' => array( + 'not_empty' => NULL, + 'min_length' => array(5), + 'max_length' => array(42), + ), + 'password_confirm' => array( + 'matches' => array('password'), + ), + 'email' => array( + 'not_empty' => NULL, + 'min_length' => array(4), + 'max_length' => array(127), + 'email' => NULL, + ), + ); + + // Validation callbacks + protected $_callbacks = array( + 'username' => array('username_available'), + 'email' => array('email_available'), + ); + + // Field labels + protected $_labels = array( + 'username' => 'username', + 'email' => 'email address', + 'password' => 'password', + 'password_confirm' => 'password confirmation', + ); + + // Columns to ignore + protected $_ignored_columns = array('password_confirm'); + + /** + * Validates login information from an array, and optionally redirects + * after a successful login. + * + * @param array values to check + * @param string URI or URL to redirect to + * @return boolean + */ + public function login(array & $array, $redirect = FALSE) + { + $fieldname = $this->unique_key($array['username']); + $array = Validate::factory($array) + ->label('username', $this->_labels[$fieldname]) + ->label('password', $this->_labels['password']) + ->filter(TRUE, 'trim') + ->rules('username', $this->_rules[$fieldname]) + ->rules('password', $this->_rules['password']); + + // Get the remember login option + $remember = isset($array['remember']); + + // Login starts out invalid + $status = FALSE; + + if ($array->check()) + { + // Attempt to load the user + $this->where($fieldname, '=', $array['username'])->find(); + + if ($this->loaded() AND Auth::instance()->login($this, $array['password'], $remember)) + { + if (is_string($redirect)) + { + // Redirect after a successful login + Request::instance()->redirect($redirect); + } + + // Login is successful + $status = TRUE; + } + else + { + $array->error('username', 'invalid'); + } + } + + return $status; + } + + /** + * Validates an array for a matching password and password_confirm field, + * and optionally redirects after a successful save. + * + * @param array values to check + * @param string URI or URL to redirect to + * @return boolean + */ + public function change_password(array & $array, $redirect = FALSE) + { + $array = Validate::factory($array) + ->label('password', $this->_labels['password']) + ->label('password_confirm', $this->_labels['password_confirm']) + ->filter(TRUE, 'trim') + ->rules('password', $this->_rules['password']) + ->rules('password_confirm', $this->_rules['password_confirm']); + + if ($status = $array->check()) + { + // Change the password + $this->password = $array['password']; + + if ($status = $this->save() AND is_string($redirect)) + { + // Redirect to the success page + Request::instance()->redirect($redirect); + } + } + + return $status; + } + + /** + * Complete the login for a user by incrementing the logins and saving login timestamp + * + * @return void + */ + public function complete_login() + { + if ( ! $this->_loaded) + { + // nothing to do + return; + } + + // Update the number of logins + $this->logins = new Database_Expression('logins + 1'); + + // Set the last login date + $this->last_login = time(); + + // Save the user + $this->save(); + } + + /** + * Does the reverse of unique_key_exists() by triggering error if username exists. + * Validation callback. + * + * @param Validate Validate object + * @param string field name + * @return void + */ + public function username_available(Validate $array, $field) + { + if ($this->unique_key_exists($array[$field], 'username')) + { + $array->error($field, 'username_available', array($array[$field])); + } + } + + /** + * Does the reverse of unique_key_exists() by triggering error if email exists. + * Validation callback. + * + * @param Validate Validate object + * @param string field name + * @return void + */ + public function email_available(Validate $array, $field) + { + if ($this->unique_key_exists($array[$field], 'email')) + { + $array->error($field, 'email_available', array($array[$field])); + } + } + + /** + * Tests if a unique key value exists in the database. + * + * @param mixed the value to test + * @param string field name + * @return boolean + */ + public function unique_key_exists($value, $field = NULL) + { + if ($field === NULL) + { + // Automatically determine field by looking at the value + $field = $this->unique_key($value); + } + + return (bool) DB::select(array('COUNT("*")', 'total_count')) + ->from($this->_table_name) + ->where($field, '=', $value) + ->where($this->_primary_key, '!=', $this->pk()) + ->execute($this->_db) + ->get('total_count'); + } + + /** + * Allows a model use both email and username as unique identifiers for login + * + * @param string unique value + * @return string field name + */ + public function unique_key($value) + { + return Validate::email($value) ? 'email' : 'username'; + } + + /** + * Saves the current object. Will hash password if it was changed. + * + * @return ORM + */ + public function save() + { + if (array_key_exists('password', $this->_changed)) + { + $this->_object['password'] = Auth::instance()->hash_password($this->_object['password']); + } + + return parent::save(); + } + +} // End Auth User Model \ No newline at end of file diff --git a/includes/kohana/modules/auth/classes/model/auth/user/token.php b/includes/kohana/modules/auth/classes/model/auth/user/token.php new file mode 100644 index 0000000..f42798e --- /dev/null +++ b/includes/kohana/modules/auth/classes/model/auth/user/token.php @@ -0,0 +1,101 @@ + array()); + + // Current timestamp + protected $_now; + + /** + * Handles garbage collection and deleting of expired objects. + * + * @return void + */ + public function __construct($id = NULL) + { + parent::__construct($id); + + // Set the now, we use this a lot + $this->_now = time(); + + if (mt_rand(1, 100) === 1) + { + // Do garbage collection + $this->delete_expired(); + } + + if ($this->expires < $this->_now) + { + // This object has expired + $this->delete(); + } + } + + /** + * Overload saving to set the created time and to create a new token + * when the object is saved. + * + * @return ORM + */ + public function save() + { + if ($this->loaded() === FALSE) + { + // Set the created time, token, and hash of the user agent + $this->created = $this->_now; + $this->user_agent = sha1(Request::$user_agent); + } + + while (TRUE) + { + // Generate a new token + $this->token = $this->create_token(); + + try + { + return parent::save(); + } + catch (Kohana_Database_Exception $e) + { + // Collision occurred, token is not unique + } + } + } + + /** + * Deletes all expired tokens. + * + * @return ORM + */ + public function delete_expired() + { + // Delete all expired tokens + DB::delete($this->_table_name) + ->where('expires', '<', $this->_now) + ->execute($this->_db); + + return $this; + } + + /** + * Generate a new unique token. + * + * @return string + * @uses Text::random + */ + protected function create_token() + { + // Create a random token + return Text::random('alnum', 32); + } + +} // End Auth User Token Model \ No newline at end of file diff --git a/includes/kohana/modules/auth/classes/model/role.php b/includes/kohana/modules/auth/classes/model/role.php new file mode 100644 index 0000000..983fa96 --- /dev/null +++ b/includes/kohana/modules/auth/classes/model/role.php @@ -0,0 +1,7 @@ + 'ORM', + 'hash_method' => 'sha1', + 'salt_pattern' => '1, 3, 5, 9, 14, 15, 20, 21, 28, 30', + 'lifetime' => 1209600, + 'session_key' => 'auth_user', + 'autologin_key' => 'auth_autologin', + 'forced_key' => 'auth_forced', + + // Username/password combinations for the Auth File driver + 'users' => array( + // 'admin' => 'b3154acf3a344170077d11bdb5fff31532f679a1919e716a02', + ), + +); \ No newline at end of file diff --git a/includes/kohana/modules/auth/config/userguide.php b/includes/kohana/modules/auth/config/userguide.php new file mode 100644 index 0000000..b5606e8 --- /dev/null +++ b/includes/kohana/modules/auth/config/userguide.php @@ -0,0 +1,23 @@ + array( + + // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' + 'auth' => array( + + // Whether this modules userguide pages should be shown + 'enabled' => TRUE, + + // The name that should show up on the userguide index page + 'name' => 'Auth', + + // A short description of this module, shown on the index page + 'description' => 'User authentication and authorization.', + + // Copyright message, shown in the footer for this module + 'copyright' => '© 2008–2010 Kohana Team', + ) + ) +); \ No newline at end of file diff --git a/includes/kohana/modules/auth/guide/auth/config.md b/includes/kohana/modules/auth/guide/auth/config.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/guide/auth/edit.md b/includes/kohana/modules/auth/guide/auth/edit.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/guide/auth/index.md b/includes/kohana/modules/auth/guide/auth/index.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/guide/auth/login.md b/includes/kohana/modules/auth/guide/auth/login.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/guide/auth/menu.md b/includes/kohana/modules/auth/guide/auth/menu.md new file mode 100644 index 0000000..1708caa --- /dev/null +++ b/includes/kohana/modules/auth/guide/auth/menu.md @@ -0,0 +1,7 @@ +## [Auth]() +- [Config](config) +- [User Model](user) +- [Register Users](register) +- [Log in and out](login) +- [Edit User](edit) +- [Using Roles](roles) diff --git a/includes/kohana/modules/auth/guide/auth/register.md b/includes/kohana/modules/auth/guide/auth/register.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/guide/auth/roles.md b/includes/kohana/modules/auth/guide/auth/roles.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/guide/auth/user.md b/includes/kohana/modules/auth/guide/auth/user.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/auth/mysql.sql b/includes/kohana/modules/auth/mysql.sql new file mode 100644 index 0000000..1c58ac1 --- /dev/null +++ b/includes/kohana/modules/auth/mysql.sql @@ -0,0 +1,48 @@ +CREATE TABLE IF NOT EXISTS `roles` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `name` varchar(32) NOT NULL, + `description` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `roles` (`id`, `name`, `description`) VALUES(1, 'login', 'Login privileges, granted after account confirmation'); +INSERT INTO `roles` (`id`, `name`, `description`) VALUES(2, 'admin', 'Administrative user, has access to everything.'); + +CREATE TABLE IF NOT EXISTS `roles_users` ( + `user_id` int(10) UNSIGNED NOT NULL, + `role_id` int(10) UNSIGNED NOT NULL, + PRIMARY KEY (`user_id`,`role_id`), + KEY `fk_role_id` (`role_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `users` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `email` varchar(127) NOT NULL, + `username` varchar(32) NOT NULL DEFAULT '', + `password` char(50) NOT NULL, + `logins` int(10) UNSIGNED NOT NULL DEFAULT '0', + `last_login` int(10) UNSIGNED, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_username` (`username`), + UNIQUE KEY `uniq_email` (`email`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `user_tokens` ( + `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + `user_id` int(11) UNSIGNED NOT NULL, + `user_agent` varchar(40) NOT NULL, + `token` varchar(32) NOT NULL, + `created` int(10) UNSIGNED NOT NULL, + `expires` int(10) UNSIGNED NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_token` (`token`), + KEY `fk_user_id` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +ALTER TABLE `roles_users` + ADD CONSTRAINT `roles_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE, + ADD CONSTRAINT `roles_users_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE; + +ALTER TABLE `user_tokens` + ADD CONSTRAINT `user_tokens_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; \ No newline at end of file diff --git a/includes/kohana/modules/auth/postgresql.sql b/includes/kohana/modules/auth/postgresql.sql new file mode 100644 index 0000000..9e192ba --- /dev/null +++ b/includes/kohana/modules/auth/postgresql.sql @@ -0,0 +1,53 @@ +CREATE TABLE roles +( + id serial, + "name" varchar(32) NOT NULL, + description text NOT NULL, + CONSTRAINT roles_id_pkey PRIMARY KEY (id), + CONSTRAINT roles_name_key UNIQUE (name) +); + +CREATE TABLE roles_users +( + user_id integer, + role_id integer +); + +CREATE TABLE users +( + id serial, + email varchar(318) NOT NULL, + username varchar(32) NOT NULL, + "password" varchar(50) NOT NULL, + logins integer NOT NULL DEFAULT 0, + last_login integer, + CONSTRAINT users_id_pkey PRIMARY KEY (id), + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_email_key UNIQUE (email), + CONSTRAINT users_logins_check CHECK (logins >= 0) +); + +CREATE TABLE user_tokens +( + id serial, + user_id integer NOT NULL, + user_agent varchar(40) NOT NULL, + token character varying(32) NOT NULL, + created integer NOT NULL, + expires integer NOT NULL, + CONSTRAINT user_tokens_id_pkey PRIMARY KEY (id), + CONSTRAINT user_tokens_token_key UNIQUE (token) +); + +CREATE INDEX user_id_idx ON roles_users (user_id); +CREATE INDEX role_id_idx ON roles_users (role_id); + +ALTER TABLE roles_users + ADD CONSTRAINT user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + ADD CONSTRAINT role_id_fkey FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE; + +ALTER TABLE user_tokens + ADD CONSTRAINT user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; + +INSERT INTO roles (name, description) VALUES ('login', 'Login privileges, granted after account confirmation'); +INSERT INTO roles (name, description) VALUES ('admin', 'Administrative user, has access to everything.'); \ No newline at end of file diff --git a/includes/kohana/modules/cache/README.md b/includes/kohana/modules/cache/README.md new file mode 100644 index 0000000..cd04fbd --- /dev/null +++ b/includes/kohana/modules/cache/README.md @@ -0,0 +1,61 @@ +Kohana Cache library +==================== + +The cache library for Kohana 3 provides a simple interface to the most common cache solutions. Developers are free to add their own caching solutions that follow the cache design pattern defined within this module. + +Supported cache solutions +------------------------- + +Currently this module supports the following cache methods. + +1. APC +2. eAccelerator +3. Memcache +4. Memcached-tags (Supports tags) +5. SQLite (Supports tags) +6. File +7. Xcache +8. Wincache + +Planned support +--------------- + +In the near future, additional support for the following methods will be included. + +1. Memcached + +Introduction to caching +----------------------- + +To use caching to the maximum potential, your application should be designed with caching in mind from the outset. In general, the most effective caches contain lots of small collections of data that are the result of expensive computational operations, such as searching through a large data set. + +There are many different caching methods available for PHP, from the very basic file based caching to opcode caching in eAccelerator and APC. Caching engines that use physical memory over disk based storage are always faster, however many do not support more advanced features such as tagging. + +Using Cache +----------- + +To use Kohana Cache, download and extract the latest stable release of Kohana Cache from [Github](http://github.com/samsoir/kohana-cache). Place the module into your Kohana instances modules folder. Finally enable the module within the application bootstrap within the section entitled _modules_. + +Quick example +------------- + +The following is a quick example of how to use Kohana Cache. The example is using the SQLite driver. + + 'bar', 'apples' => 'pear', 'BDFL' => 'Shadowhand'); + + // Save the data to cache, with an id of test_id and a lifetime of 10 minutes + $mycache->set('test_id', $data, 600); + + // Retrieve the data from cache + $retrieved_data = $mycache->get('test_id'); + + // Remove the cache item + $mycache->delete('test_id'); + + // Clear the cache of all stored items + $mycache->delete_all(); diff --git a/includes/kohana/modules/cache/classes/cache.php b/includes/kohana/modules/cache/classes/cache.php new file mode 100644 index 0000000..2b43c93 --- /dev/null +++ b/includes/kohana/modules/cache/classes/cache.php @@ -0,0 +1,3 @@ + array( // Default group + * 'driver' => 'memcache', // using Memcache driver + * 'servers' => array( // Available server definitions + * array( + * 'host' => 'localhost', + * 'port' => 11211, + * 'persistent' => FALSE + * ) + * ), + * 'compression' => FALSE, // Use compression? + * ), + * ) + * + * In cases where only one cache group is required, if the group is named `default` there is + * no need to pass the group name when instantiating a cache instance. + * + * #### General cache group configuration settings + * + * Below are the settings available to all types of cache driver. + * + * Name | Required | Description + * -------------- | -------- | --------------------------------------------------------------- + * driver | __YES__ | (_string_) The driver type to use + * + * Details of the settings specific to each driver are available within the drivers documentation. + * + * ### System requirements + * + * * Kohana 3.0.x + * * PHP 5.2.4 or greater + * + * @package Kohana/Cache + * @category Base + * @version 2.0 + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +abstract class Kohana_Cache { + + const DEFAULT_EXPIRE = 3600; + + /** + * @var string default driver to use + */ + public static $default = 'file'; + + /** + * @var Kohana_Cache instances + */ + public static $instances = array(); + + /** + * Creates a singleton of a Kohana Cache group. If no group is supplied + * the __default__ cache group is used. + * + * // Create an instance of the default group + * $default_group = Cache::instance(); + * + * // Create an instance of a group + * $foo_group = Cache::instance('foo'); + * + * // Access an instantiated group directly + * $foo_group = Cache::$instances['default']; + * + * @param string the name of the cache group to use [Optional] + * @return Kohana_Cache + * @throws Kohana_Cache_Exception + */ + public static function instance($group = NULL) + { + // If there is no group supplied + if ($group === NULL) + { + // Use the default setting + $group = Cache::$default; + } + + if (isset(Cache::$instances[$group])) + { + // Return the current group if initiated already + return Cache::$instances[$group]; + } + + $config = Kohana::config('cache'); + + if ( ! $config->offsetExists($group)) + { + throw new Kohana_Cache_Exception('Failed to load Kohana Cache group: :group', array(':group' => $group)); + } + + $config = $config->get($group); + + // Create a new cache type instance + $cache_class = 'Cache_'.ucfirst($config['driver']); + Cache::$instances[$group] = new $cache_class($config); + + // Return the instance + return Cache::$instances[$group]; + } + + /** + * @var Kohana_Config + */ + protected $_config; + + /** + * Ensures singleton pattern is observed, loads the default expiry + * + * @param array configuration + */ + protected function __construct(array $config) + { + $this->_config = $config; + } + + /** + * Overload the __clone() method to prevent cloning + * + * @return void + * @throws Kohana_Cache_Exception + */ + public function __clone() + { + throw new Kohana_Cache_Exception('Cloning of Kohana_Cache objects is forbidden'); + } + + /** + * Retrieve a cached value entry by id. + * + * // Retrieve cache entry from default group + * $data = Cache::instance()->get('foo'); + * + * // Retrieve cache entry from default group and return 'bar' if miss + * $data = Cache::instance()->get('foo', 'bar'); + * + * // Retrieve cache entry from memcache group + * $data = Cache::instance('memcache')->get('foo'); + * + * @param string id of cache to entry + * @param string default value to return if cache miss + * @return mixed + * @throws Kohana_Cache_Exception + */ + abstract public function get($id, $default = NULL); + + /** + * Set a value to cache with id and lifetime + * + * $data = 'bar'; + * + * // Set 'bar' to 'foo' in default group, using default expiry + * Cache::instance()->set('foo', $data); + * + * // Set 'bar' to 'foo' in default group for 30 seconds + * Cache::instance()->set('foo', $data, 30); + * + * // Set 'bar' to 'foo' in memcache group for 10 minutes + * if (Cache::instance('memcache')->set('foo', $data, 600)) + * { + * // Cache was set successfully + * return + * } + * + * @param string id of cache entry + * @param string data to set to cache + * @param integer lifetime in seconds + * @return boolean + */ + abstract public function set($id, $data, $lifetime = 3600); + + /** + * Delete a cache entry based on id + * + * // Delete 'foo' entry from the default group + * Cache::instance()->delete('foo'); + * + * // Delete 'foo' entry from the memcache group + * Cache::instance('memcache')->delete('foo') + * + * @param string id to remove from cache + * @return boolean + */ + abstract public function delete($id); + + /** + * Delete all cache entries. + * + * Beware of using this method when + * using shared memory cache systems, as it will wipe every + * entry within the system for all clients. + * + * // Delete all cache entries in the default group + * Cache::instance()->delete_all(); + * + * // Delete all cache entries in the memcache group + * Cache::instance('memcache')->delete_all(); + * + * @return boolean + */ + abstract public function delete_all(); + + /** + * Replaces troublesome characters with underscores. + * + * // Sanitize a cache id + * $id = $this->_sanitize_id($id); + * + * @param string id of cache to sanitize + * @return string + */ + protected function _sanitize_id($id) + { + // Change slashes and spaces to underscores + return str_replace(array('/', '\\', ' '), '_', $id); + } +} +// End Kohana_Cache diff --git a/includes/kohana/modules/cache/classes/kohana/cache/apc.php b/includes/kohana/modules/cache/classes/kohana/cache/apc.php new file mode 100644 index 0000000..64ffe82 --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/apc.php @@ -0,0 +1,133 @@ + array( // Driver group + * 'driver' => 'apc', // using APC driver + * ), + * ) + * + * In cases where only one cache group is required, if the group is named `default` there is + * no need to pass the group name when instantiating a cache instance. + * + * #### General cache group configuration settings + * + * Below are the settings available to all types of cache driver. + * + * Name | Required | Description + * -------------- | -------- | --------------------------------------------------------------- + * driver | __YES__ | (_string_) The driver type to use + * + * ### System requirements + * + * * Kohana 3.0.x + * * PHP 5.2.4 or greater + * * APC PHP extension + * + * @package Kohana/Cache + * @category Base + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Cache_Apc extends Cache { + + /** + * Check for existence of the APC extension This method cannot be invoked externally. The driver must + * be instantiated using the `Cache::instance()` method. + * + * @param array configuration + * @throws Kohana_Cache_Exception + */ + protected function __construct(array $config) + { + if ( ! extension_loaded('apc')) + { + throw new Kohana_Cache_Exception('PHP APC extension is not available.'); + } + + parent::__construct($config); + } + + /** + * Retrieve a cached value entry by id. + * + * // Retrieve cache entry from apc group + * $data = Cache::instance('apc')->get('foo'); + * + * // Retrieve cache entry from apc group and return 'bar' if miss + * $data = Cache::instance('apc')->get('foo', 'bar'); + * + * @param string id of cache to entry + * @param string default value to return if cache miss + * @return mixed + * @throws Kohana_Cache_Exception + */ + public function get($id, $default = NULL) + { + return (($data = apc_fetch($this->_sanitize_id($id))) === FALSE) ? $default : $data; + } + + /** + * Set a value to cache with id and lifetime + * + * $data = 'bar'; + * + * // Set 'bar' to 'foo' in apc group, using default expiry + * Cache::instance('apc')->set('foo', $data); + * + * // Set 'bar' to 'foo' in apc group for 30 seconds + * Cache::instance('apc')->set('foo', $data, 30); + * + * @param string id of cache entry + * @param string data to set to cache + * @param integer lifetime in seconds + * @return boolean + */ + public function set($id, $data, $lifetime = NULL) + { + if ($lifetime === NULL) + { + $lifetime = Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE); + } + + return apc_store($this->_sanitize_id($id), $data, $lifetime); + } + + /** + * Delete a cache entry based on id + * + * // Delete 'foo' entry from the apc group + * Cache::instance('apc')->delete('foo'); + * + * @param string id to remove from cache + * @return boolean + */ + public function delete($id) + { + return apc_delete($this->_sanitize_id($id)); + } + + /** + * Delete all cache entries. + * + * Beware of using this method when + * using shared memory cache systems, as it will wipe every + * entry within the system for all clients. + * + * // Delete all cache entries in the apc group + * Cache::instance('apc')->delete_all(); + * + * @return boolean + */ + public function delete_all() + { + return apc_clear_cache('user'); + } +} diff --git a/includes/kohana/modules/cache/classes/kohana/cache/eaccelerator.php b/includes/kohana/modules/cache/classes/kohana/cache/eaccelerator.php new file mode 100644 index 0000000..96c97f5 --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/eaccelerator.php @@ -0,0 +1,133 @@ + array( // Driver group + * 'driver' => 'eaccelerator', // using Eaccelerator driver + * ), + * ) + * + * In cases where only one cache group is required, if the group is named `default` there is + * no need to pass the group name when instantiating a cache instance. + * + * #### General cache group configuration settings + * + * Below are the settings available to all types of cache driver. + * + * Name | Required | Description + * -------------- | -------- | --------------------------------------------------------------- + * driver | __YES__ | (_string_) The driver type to use + * + * ### System requirements + * + * * Kohana 3.0.x + * * PHP 5.2.4 or greater + * * Eaccelerator PHP extension + * + * @package Kohana/Cache + * @category Base + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Cache_Eaccelerator extends Cache { + + /** + * Check for existence of the eAccelerator extension This method cannot be invoked externally. The driver must + * be instantiated using the `Cache::instance()` method. + * + * @param array configuration + * @throws Kohana_Cache_Exception + */ + protected function __construct(array $config) + { + if ( ! extension_loaded('eaccelerator')) + { + throw new Kohana_Cache_Exception('PHP eAccelerator extension is not available.'); + } + + parent::__construct($config); + } + + /** + * Retrieve a cached value entry by id. + * + * // Retrieve cache entry from eaccelerator group + * $data = Cache::instance('eaccelerator')->get('foo'); + * + * // Retrieve cache entry from eaccelerator group and return 'bar' if miss + * $data = Cache::instance('eaccelerator')->get('foo', 'bar'); + * + * @param string id of cache to entry + * @param string default value to return if cache miss + * @return mixed + * @throws Kohana_Cache_Exception + */ + public function get($id, $default = NULL) + { + return (($data = eaccelerator_get($this->_sanitize_id($id))) === FALSE) ? $default : $data; + } + + /** + * Set a value to cache with id and lifetime + * + * $data = 'bar'; + * + * // Set 'bar' to 'foo' in eaccelerator group, using default expiry + * Cache::instance('eaccelerator')->set('foo', $data); + * + * // Set 'bar' to 'foo' in eaccelerator group for 30 seconds + * Cache::instance('eaccelerator')->set('foo', $data, 30); + * + * @param string id of cache entry + * @param string data to set to cache + * @param integer lifetime in seconds + * @return boolean + */ + public function set($id, $data, $lifetime = NULL) + { + if ($lifetime === NULL) + { + $lifetime = time() + Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE); + } + + return eaccelerator_put($this->_sanitize_id($id), $data, $lifetime); + } + + /** + * Delete a cache entry based on id + * + * // Delete 'foo' entry from the eaccelerator group + * Cache::instance('eaccelerator')->delete('foo'); + * + * @param string id to remove from cache + * @return boolean + */ + public function delete($id) + { + return eaccelerator_rm($this->_sanitize_id($id)); + } + + /** + * Delete all cache entries. + * + * Beware of using this method when + * using shared memory cache systems, as it will wipe every + * entry within the system for all clients. + * + * // Delete all cache entries in the eaccelerator group + * Cache::instance('eaccelerator')->delete_all(); + * + * @return boolean + */ + public function delete_all() + { + return eaccelerator_clean(); + } +} diff --git a/includes/kohana/modules/cache/classes/kohana/cache/exception.php b/includes/kohana/modules/cache/classes/kohana/cache/exception.php new file mode 100644 index 0000000..d89d25e --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/exception.php @@ -0,0 +1,11 @@ + array( // File driver group + * 'driver' => 'file', // using File driver + * 'cache_dir' => APPPATH.'cache/.kohana_cache', // Cache location + * ), + * ) + * + * In cases where only one cache group is required, if the group is named `default` there is + * no need to pass the group name when instantiating a cache instance. + * + * #### General cache group configuration settings + * + * Below are the settings available to all types of cache driver. + * + * Name | Required | Description + * -------------- | -------- | --------------------------------------------------------------- + * driver | __YES__ | (_string_) The driver type to use + * cache_dir | __NO__ | (_string_) The cache directory to use for this cache instance + * + * ### System requirements + * + * * Kohana 3.0.x + * * PHP 5.2.4 or greater + * + * @package Kohana/Cache + * @category Base + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Cache_File extends Cache implements Kohana_Cache_GarbageCollect { + + /** + * Creates a hashed filename based on the string. This is used + * to create shorter unique IDs for each cache filename. + * + * // Create the cache filename + * $filename = Cache_File::filename($this->_sanitize_id($id)); + * + * @param string string to hash into filename + * @return string + */ + protected static function filename($string) + { + return sha1($string).'.json'; + } + + /** + * @var string the caching directory + */ + protected $_cache_dir; + + /** + * Constructs the file cache driver. This method cannot be invoked externally. The file cache driver must + * be instantiated using the `Cache::instance()` method. + * + * @param array config + * @throws Kohana_Cache_Exception + */ + protected function __construct(array $config) + { + // Setup parent + parent::__construct($config); + + try + { + $directory = Arr::get($this->_config, 'cache_dir', Kohana::$cache_dir); + $this->_cache_dir = new SplFileInfo($directory); + } + // PHP < 5.3 exception handle + catch (ErrorException $e) + { + $this->_cache_dir = $this->_make_directory($directory, 0777, TRUE); + } + // PHP >= 5.3 exception handle + catch (UnexpectedValueException $e) + { + $this->_cache_dir = $this->_make_directory($directory, 0777, TRUE); + } + + // If the defined directory is a file, get outta here + if ($this->_cache_dir->isFile()) + { + throw new Kohana_Cache_Exception('Unable to create cache directory as a file already exists : :resource', array(':resource' => $this->_cache_dir->getRealPath())); + } + + // Check the read status of the directory + if ( ! $this->_cache_dir->isReadable()) + { + throw new Kohana_Cache_Exception('Unable to read from the cache directory :resource', array(':resource' => $this->_cache_dir->getRealPath())); + } + + // Check the write status of the directory + if ( ! $this->_cache_dir->isWritable()) + { + throw new Kohana_Cache_Exception('Unable to write to the cache directory :resource', array(':resource' => $this->_cache_dir->getRealPath())); + } + } + + /** + * Retrieve a cached value entry by id. + * + * // Retrieve cache entry from file group + * $data = Cache::instance('file')->get('foo'); + * + * // Retrieve cache entry from file group and return 'bar' if miss + * $data = Cache::instance('file')->get('foo', 'bar'); + * + * @param string id of cache to entry + * @param string default value to return if cache miss + * @return mixed + * @throws Kohana_Cache_Exception + */ + public function get($id, $default = NULL) + { + $filename = Cache_File::filename($this->_sanitize_id($id)); + $directory = $this->_resolve_directory($filename); + + // Wrap operations in try/catch to handle notices + try + { + // Open file + $file = new SplFileInfo($directory.$filename); + + // If file does not exist + if ( ! $file->isFile()) + { + // Return default value + return $default; + } + else + { + // Open the file and extract the json + $json = $file->openFile()->current(); + + // Decode the json into PHP object + $data = json_decode($json); + + // Test the expiry + if ($data->expiry < time()) + { + // Delete the file + $this->_delete_file($file, NULL, TRUE); + + // Return default value + return $default; + } + else + { + return ($data->type === 'string') ? $data->payload : unserialize($data->payload); + } + } + + } + catch (ErrorException $e) + { + // Handle ErrorException caused by failed unserialization + if ($e->getCode() === E_NOTICE) + { + throw new Kohana_Cache_Exception(__METHOD__.' failed to unserialize cached object with message : '.$e->getMessage()); + } + + // Otherwise throw the exception + throw $e; + } + } + + /** + * Set a value to cache with id and lifetime + * + * $data = 'bar'; + * + * // Set 'bar' to 'foo' in file group, using default expiry + * Cache::instance('file')->set('foo', $data); + * + * // Set 'bar' to 'foo' in file group for 30 seconds + * Cache::instance('file')->set('foo', $data, 30); + * + * @param string id of cache entry + * @param string data to set to cache + * @param integer lifetime in seconds + * @return boolean + */ + public function set($id, $data, $lifetime = NULL) + { + $filename = Cache_File::filename($this->_sanitize_id($id)); + $directory = $this->_resolve_directory($filename); + + // If lifetime is NULL + if ($lifetime === NULL) + { + // Set to the default expiry + $lifetime = Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE); + } + + // Open directory + $dir = new SplFileInfo($directory); + + // If the directory path is not a directory + if ( ! $dir->isDir()) + { + // Create the directory + if ( ! mkdir($directory, 0777, TRUE)) + { + throw new Kohana_Cache_Exception(__METHOD__.' unable to create directory : :directory', array(':directory' => $directory)); + } + + // chmod to solve potential umask issues + chmod($directory, 0777); + } + + // Open file to inspect + $resouce = new SplFileInfo($directory.$filename); + $file = $resouce->openFile('w'); + + try + { + $type = gettype($data); + + // Serialize the data + $data = json_encode( (object) array( + 'payload' => ($type === 'string') ? $data : serialize($data), + 'expiry' => time() + $lifetime, + 'type' => $type + )); + + $size = strlen($data); + } + catch (ErrorException $e) + { + // If serialize through an error exception + if ($e->getCode() === E_NOTICE) + { + // Throw a caching error + throw new Kohana_Cache_Exception(__METHOD__.' failed to serialize data for caching with message : '.$e->getMessage()); + } + + // Else rethrow the error exception + throw $e; + } + + try + { + $file->fwrite($data, $size); + return (bool) $file->fflush(); + } + catch (Exception $e) + { + throw $e; + } + } + + /** + * Delete a cache entry based on id + * + * // Delete 'foo' entry from the file group + * Cache::instance('file')->delete('foo'); + * + * @param string id to remove from cache + * @return boolean + */ + public function delete($id) + { + $filename = Cache_File::filename($this->_sanitize_id($id)); + $directory = $this->_resolve_directory($filename); + + return $this->_delete_file(new SplFileInfo($directory.$filename), NULL, TRUE); + } + + /** + * Delete all cache entries. + * + * Beware of using this method when + * using shared memory cache systems, as it will wipe every + * entry within the system for all clients. + * + * // Delete all cache entries in the file group + * Cache::instance('file')->delete_all(); + * + * @return boolean + */ + public function delete_all() + { + return $this->_delete_file($this->_cache_dir, TRUE); + } + + /** + * Garbage collection method that cleans any expired + * cache entries from the cache. + * + * @return void + */ + public function garbage_collect() + { + $this->_delete_file($this->_cache_dir, TRUE, FALSE, TRUE); + return; + } + + /** + * Deletes files recursively and returns FALSE on any errors + * + * // Delete a file or folder whilst retaining parent directory and ignore all errors + * $this->_delete_file($folder, TRUE, TRUE); + * + * @param SplFileInfo file + * @param boolean retain the parent directory + * @param boolean ignore_errors to prevent all exceptions interrupting exec + * @param boolean only expired files + * @return boolean + * @throws Kohana_Cache_Exception + */ + protected function _delete_file(SplFileInfo $file, $retain_parent_directory = FALSE, $ignore_errors = FALSE, $only_expired = FALSE) + { + // Allow graceful error handling + try + { + // If is file + if ($file->isFile()) + { + try + { + // If only expired is not set + if ($only_expired === FALSE) + { + // We want to delete the file + $delete = TRUE; + } + // Otherwise... + else + { + // Assess the file expiry to flag it for deletion + $json = $file->openFile('r')->current(); + $data = json_decode($json); + $delete = $data->expiry < time(); + } + + // If the delete flag is set + if ($delete === TRUE) + { + // Try to delete + unlink($file->getRealPath()); + } + } + catch (ErrorException $e) + { + // Catch any delete file warnings + if ($e->getCode() === E_WARNING) + { + throw new Kohana_Cache_Exception(__METHOD__.' failed to delete file : :file', array(':file' => $file->getRealPath())); + } + } + } + // Else, is directory + elseif ($file->isDir()) + { + // Create new DirectoryIterator + $files = new DirectoryIterator($file->getPathname()); + + // Iterate over each entry + while ($files->valid()) + { + // Extract the entry name + $name = $files->getFilename(); + + // If the name is not a dot + if ($name != '.' and $name != '..') + { + // Create new file resource + $fp = new SplFileInfo($files->getRealPath()); + // Delete the file + $this->_delete_file($fp); + } + + // Move the file pointer on + $files->next(); + } + + // If set to retain parent directory, return now + if ($retain_parent_directory) + { + return TRUE; + } + + try + { + // Remove the files iterator + // (fixes Windows PHP which has permission issues with open iterators) + unset($files); + + // Try to remove the parent directory + return rmdir($file->getRealPath()); + } + catch (ErrorException $e) + { + // Catch any delete directory warnings + if ($e->getCode() === E_WARNING) + { + throw new Kohana_Cache_Exception(__METHOD__.' failed to delete directory : :directory', array(':directory' => $file->getRealPath())); + } + } + } + } + // Catch all exceptions + catch (Exception $e) + { + // If ignore_errors is on + if ($ignore_errors === TRUE) + { + // Return + return FALSE; + } + // Throw exception + throw $e; + } + } + + /** + * Resolves the cache directory real path from the filename + * + * // Get the realpath of the cache folder + * $realpath = $this->_resolve_directory($filename); + * + * @param string filename to resolve + * @return string + */ + protected function _resolve_directory($filename) + { + return $this->_cache_dir->getRealPath().DIRECTORY_SEPARATOR.$filename[0].$filename[1].DIRECTORY_SEPARATOR; + } + + /** + * Makes the cache directory if it doesn't exist. Simply a wrapper for + * `mkdir` to ensure DRY principles + * + * @see http://php.net/manual/en/function.mkdir.php + * @param string directory + * @param string mode + * @param string recursive + * @param string context + * @return SplFileInfo + * @throws Kohana_Cache_Exception + */ + protected function _make_directory($directory, $mode = 0777, $recursive = FALSE, $context = NULL) + { + if ( ! mkdir($directory, $mode, $recursive, $context)) + { + throw new Kohana_Cache_Exception('Failed to create the defined cache directory : :directory', array(':directory' => $directory)); + } + chmod($directory, $mode); + + return new SplFileInfo($directory);; + } +} diff --git a/includes/kohana/modules/cache/classes/kohana/cache/garbagecollect.php b/includes/kohana/modules/cache/classes/kohana/cache/garbagecollect.php new file mode 100644 index 0000000..62c3148 --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/garbagecollect.php @@ -0,0 +1,23 @@ + array( // Default group + * 'driver' => 'memcache', // using Memcache driver + * 'servers' => array( // Available server definitions + * // First memcache server server + * array( + * 'host' => 'localhost', + * 'port' => 11211, + * 'persistent' => FALSE + * 'weight' => 1, + * 'timeout' => 1, + * 'retry_interval' => 15, + * 'status' => TRUE, + * 'instant_death' => TRUE, + * 'failure_callback' => array('className', 'classMethod') + * ), + * // Second memcache server + * array( + * 'host' => '192.168.1.5', + * 'port' => 22122, + * 'persistent' => TRUE + * ) + * ), + * 'compression' => FALSE, // Use compression? + * ), + * ) + * + * In cases where only one cache group is required, if the group is named `default` there is + * no need to pass the group name when instantiating a cache instance. + * + * #### General cache group configuration settings + * + * Below are the settings available to all types of cache driver. + * + * Name | Required | Description + * -------------- | -------- | --------------------------------------------------------------- + * driver | __YES__ | (_string_) The driver type to use + * servers | __YES__ | (_array_) Associative array of server details, must include a __host__ key. (see _Memcache server configuration_ below) + * compression | __NO__ | (_boolean_) Use data compression when caching + * + * #### Memcache server configuration + * + * The following settings should be used when defining each memcache server + * + * Name | Required | Description + * ---------------- | -------- | --------------------------------------------------------------- + * host | __YES__ | (_string_) The host of the memcache server, i.e. __localhost__; or __127.0.0.1__; or __memcache.domain.tld__ + * port | __NO__ | (_integer_) Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets. Default __11211__ + * persistent | __NO__ | (_boolean_) Controls the use of a persistent connection. Default __TRUE__ + * weight | __NO__ | (_integer_) Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers. Default __1__ + * timeout | __NO__ | (_integer_) Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. Default __1__ + * retry_interval | __NO__ | (_integer_) Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Default __15__ + * status | __NO__ | (_boolean_) Controls if the server should be flagged as online. Default __TRUE__ + * failure_callback | __NO__ | (_[callback](http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback)_) Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server. Default __NULL__ + * + * ### System requirements + * + * * Kohana 3.0.x + * * PHP 5.2.4 or greater + * * Memcache (plus Memcached-tags for native tagging support) + * * Zlib + * + * @package Kohana/Cache + * @category Base + * @version 2.0 + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Cache_Memcache extends Cache { + + // Memcache has a maximum cache lifetime of 30 days + const CACHE_CEILING = 2592000; + + /** + * Memcache resource + * + * @var Memcache + */ + protected $_memcache; + + /** + * Flags to use when storing values + * + * @var string + */ + protected $_flags; + + /** + * The default configuration for the memcached server + * + * @var array + */ + protected $_default_config = array(); + + /** + * Constructs the memcache Kohana_Cache object + * + * @param array configuration + * @throws Kohana_Cache_Exception + */ + protected function __construct(array $config) + { + // Check for the memcache extention + if ( ! extension_loaded('memcache')) + { + throw new Kohana_Cache_Exception('Memcache PHP extention not loaded'); + } + + parent::__construct($config); + + // Setup Memcache + $this->_memcache = new Memcache; + + // Load servers from configuration + $servers = Arr::get($this->_config, 'servers', NULL); + + if ( ! $servers) + { + // Throw an exception if no server found + throw new Kohana_Cache_Exception('No Memcache servers defined in configuration'); + } + + // Setup default server configuration + $this->_default_config = array( + 'host' => 'localhost', + 'port' => 11211, + 'persistent' => FALSE, + 'weight' => 1, + 'timeout' => 1, + 'retry_interval' => 15, + 'status' => TRUE, + 'instant_death' => TRUE, + 'failure_callback' => array($this, '_failed_request'), + ); + + // Add the memcache servers to the pool + foreach ($servers as $server) + { + // Merge the defined config with defaults + $server += $this->_default_config; + + if ( ! $this->_memcache->addServer($server['host'], $server['port'], $server['persistent'], $server['weight'], $server['timeout'], $server['retry_interval'], $server['status'], $server['failure_callback'])) + { + throw new Kohana_Cache_Exception('Memcache could not connect to host \':host\' using port \':port\'', array(':host' => $server['host'], ':port' => $server['port'])); + } + } + + // Setup the flags + $this->_flags = Arr::get($this->_config, 'compression', FALSE) ? MEMCACHE_COMPRESSED : FALSE; + } + + /** + * Retrieve a cached value entry by id. + * + * // Retrieve cache entry from memcache group + * $data = Cache::instance('memcache')->get('foo'); + * + * // Retrieve cache entry from memcache group and return 'bar' if miss + * $data = Cache::instance('memcache')->get('foo', 'bar'); + * + * @param string id of cache to entry + * @param string default value to return if cache miss + * @return mixed + * @throws Kohana_Cache_Exception + */ + public function get($id, $default = NULL) + { + // Get the value from Memcache + $value = $this->_memcache->get($this->_sanitize_id($id)); + + // If the value wasn't found, normalise it + if ($value === FALSE) + { + $value = (NULL === $default) ? NULL : $default; + } + + // Return the value + return $value; + } + + /** + * Set a value to cache with id and lifetime + * + * $data = 'bar'; + * + * // Set 'bar' to 'foo' in memcache group for 10 minutes + * if (Cache::instance('memcache')->set('foo', $data, 600)) + * { + * // Cache was set successfully + * return + * } + * + * @param string id of cache entry + * @param mixed data to set to cache + * @param integer lifetime in seconds, maximum value 2592000 + * @return boolean + */ + public function set($id, $data, $lifetime = 3600) + { + // If the lifetime is greater than the ceiling + if ($lifetime > Cache_Memcache::CACHE_CEILING) + { + // Set the lifetime to maximum cache time + $lifetime = Cache_Memcache::CACHE_CEILING + time(); + } + // Else if the lifetime is greater than zero + elseif ($lifetime > 0) + { + $lifetime += time(); + } + // Else + else + { + // Normalise the lifetime + $lifetime = 0; + } + + // Set the data to memcache + return $this->_memcache->set($this->_sanitize_id($id), $data, $this->_flags, $lifetime); + } + + /** + * Delete a cache entry based on id + * + * // Delete the 'foo' cache entry immediately + * Cache::instance('memcache')->delete('foo'); + * + * // Delete the 'bar' cache entry after 30 seconds + * Cache::instance('memcache')->delete('bar', 30); + * + * @param string id of entry to delete + * @param integer timeout of entry, if zero item is deleted immediately, otherwise the item will delete after the specified value in seconds + * @return boolean + */ + public function delete($id, $timeout = 0) + { + // Delete the id + return $this->_memcache->delete($this->_sanitize_id($id), $timeout); + } + + /** + * Delete all cache entries. + * + * Beware of using this method when + * using shared memory cache systems, as it will wipe every + * entry within the system for all clients. + * + * // Delete all cache entries in the default group + * Cache::instance('memcache')->delete_all(); + * + * @return boolean + */ + public function delete_all() + { + $result = $this->_memcache->flush(); + + // We must sleep after flushing, or overwriting will not work! + // @see http://php.net/manual/en/function.memcache-flush.php#81420 + sleep(1); + + return $result; + } + + /** + * Callback method for Memcache::failure_callback to use if any Memcache call + * on a particular server fails. This method switches off that instance of the + * server if the configuration setting `instant_death` is set to `TRUE`. + * + * @param string hostname + * @param integer port + * @return void|boolean + * @since 3.0.8 + */ + public function _failed_request($hostname, $port) + { + if ( ! $this->_config['instant_death']) + return; + + // Setup non-existent host + $host = FALSE; + + // Get host settings from configuration + foreach ($this->_config['servers'] as $server) + { + // Merge the defaults, since they won't always be set + $server += $this->_default_config; + // We're looking at the failed server + if ($hostname == $server['host'] and $port == $server['port']) + { + // Server to disable, since it failed + $host = $server; + continue; + } + } + + if ( ! $host) + return; + else + { + return $this->_memcache->setServerParams( + $host['host'], + $host['port'], + $host['timeout'], + $host['retry_interval'], + FALSE, // Server is offline + array($this, '_failed_request' + )); + } + } +} \ No newline at end of file diff --git a/includes/kohana/modules/cache/classes/kohana/cache/memcachetag.php b/includes/kohana/modules/cache/classes/kohana/cache/memcachetag.php new file mode 100644 index 0000000..866ab9b --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/memcachetag.php @@ -0,0 +1,76 @@ +_memcache, 'tag_add')) + { + throw new Kohana_Cache_Exception('Memcached-tags PHP plugin not present. Please see http://code.google.com/p/memcached-tags/ for more information'); + } + } + + /** + * Set a value based on an id with tags + * + * @param string id + * @param mixed data + * @param integer lifetime [Optional] + * @param array tags [Optional] + * @return boolean + */ + public function set_with_tags($id, $data, $lifetime = NULL, array $tags = NULL) + { + $result = $this->set($id, $data, $lifetime); + + if ($result and $tags) + { + foreach ($tags as $tag) + { + $this->_memcache->tag_add($tag, $id); + } + } + + return $result; + } + + /** + * Delete cache entries based on a tag + * + * @param string tag + * @return boolean + */ + public function delete_tag($tag) + { + return $this->_memcache->tag_delete($tag); + } + + /** + * Find cache entries based on a tag + * + * @param string tag + * @return void + * @throws Kohana_Cache_Exception + */ + public function find($tag) + { + throw new Kohana_Cache_Exception('Memcached-tags does not support finding by tag'); + } +} diff --git a/includes/kohana/modules/cache/classes/kohana/cache/sqlite.php b/includes/kohana/modules/cache/classes/kohana/cache/sqlite.php new file mode 100644 index 0000000..70045e5 --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/sqlite.php @@ -0,0 +1,336 @@ +_config, 'database', NULL); + + if ($database === NULL) + { + throw new Kohana_Cache_Exception('Database path not available in Kohana Cache configuration'); + } + + // Load new Sqlite DB + $this->_db = new PDO('sqlite:'.$database); + + // Test for existing DB + $result = $this->_db->query("SELECT * FROM sqlite_master WHERE name = 'caches' AND type = 'table'")->fetchAll(); + + // If there is no table, create a new one + if (0 == count($result)) + { + $database_schema = Arr::get($this->_config, 'schema', NULL); + + if ($database_schema === NULL) + { + throw new Kohana_Cache_Exception('Database schema not found in Kohana Cache configuration'); + } + + try + { + // Create the caches table + $this->_db->query(Arr::get($this->_config, 'schema', NULL)); + } + catch (PDOException $e) + { + throw new Kohana_Cache_Exception('Failed to create new SQLite caches table with the following error : :error', array(':error' => $e->getMessage())); + } + } + } + + /** + * Retrieve a value based on an id + * + * @param string id + * @param string default [Optional] Default value to return if id not found + * @return mixed + * @throws Kohana_Cache_Exception + */ + public function get($id, $default = NULL) + { + // Prepare statement + $statement = $this->_db->prepare('SELECT id, expiration, cache FROM caches WHERE id = :id LIMIT 0, 1'); + + // Try and load the cache based on id + try + { + $statement->execute(array(':id' => $this->_sanitize_id($id))); + } + catch (PDOException $e) + { + throw new Kohana_Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + if ( ! $result = $statement->fetch(PDO::FETCH_OBJ)) + { + return $default; + } + + // If the cache has expired + if ($result->expiration != 0 and $result->expiration <= time()) + { + // Delete it and return default value + $this->delete($id); + return $default; + } + // Otherwise return cached object + else + { + // Disable notices for unserializing + $ER = error_reporting(~E_NOTICE); + + // Return the valid cache data + $data = unserialize($result->cache); + + // Turn notices back on + error_reporting($ER); + + // Return the resulting data + return $data; + } + } + + /** + * Set a value based on an id. Optionally add tags. + * + * @param string id + * @param mixed data + * @param integer lifetime [Optional] + * @return boolean + */ + public function set($id, $data, $lifetime = NULL) + { + return (bool) $this->set_with_tags($id, $data, $lifetime); + } + + /** + * Delete a cache entry based on id + * + * @param string id + * @param integer timeout [Optional] + * @return boolean + * @throws Kohana_Cache_Exception + */ + public function delete($id) + { + // Prepare statement + $statement = $this->_db->prepare('DELETE FROM caches WHERE id = :id'); + + // Remove the entry + try + { + $statement->execute(array(':id' => $this->_sanitize_id($id))); + } + catch (PDOException $e) + { + throw new Kohana_Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + return (bool) $statement->rowCount(); + } + + /** + * Delete all cache entries + * + * @return boolean + */ + public function delete_all() + { + // Prepare statement + $statement = $this->_db->prepare('DELETE FROM caches'); + + // Remove the entry + try + { + $statement->execute(); + } + catch (PDOException $e) + { + throw new Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + return (bool) $statement->rowCount(); + } + + /** + * Set a value based on an id. Optionally add tags. + * + * @param string id + * @param mixed data + * @param integer lifetime [Optional] + * @param array tags [Optional] + * @return boolean + * @throws Kohana_Cache_Exception + */ + public function set_with_tags($id, $data, $lifetime = NULL, array $tags = NULL) + { + // Serialize the data + $data = serialize($data); + + // Normalise tags + $tags = (NULL === $tags) ? NULL : ('<'.implode('>,<', $tags).'>'); + + // Setup lifetime + if ($lifetime === NULL) + { + $lifetime = (0 === Arr::get('default_expire', NULL)) ? 0 : (Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE) + time()); + } + else + { + $lifetime = (0 === $lifetime) ? 0 : ($lifetime + time()); + } + + // Prepare statement + // $this->exists() may throw Kohana_Cache_Exception, no need to catch/rethrow + $statement = $this->exists($id) ? $this->_db->prepare('UPDATE caches SET expiration = :expiration, cache = :cache, tags = :tags WHERE id = :id') : $this->_db->prepare('INSERT INTO caches (id, cache, expiration, tags) VALUES (:id, :cache, :expiration, :tags)'); + + // Try to insert + try + { + $statement->execute(array(':id' => $this->_sanitize_id($id), ':cache' => $data, ':expiration' => $lifetime, ':tags' => $tags)); + } + catch (PDOException $e) + { + throw new Kohana_Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + return (bool) $statement->rowCount(); + } + + /** + * Delete cache entries based on a tag + * + * @param string tag + * @param integer timeout [Optional] + * @return boolean + * @throws Kohana_Cache_Exception + */ + public function delete_tag($tag) + { + // Prepare the statement + $statement = $this->_db->prepare('DELETE FROM caches WHERE tags LIKE :tag'); + + // Try to delete + try + { + $statement->execute(array(':tag' => "%<{$tag}>%")); + } + catch (PDOException $e) + { + throw new Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + return (bool) $statement->rowCount(); + } + + /** + * Find cache entries based on a tag + * + * @param string tag + * @return array + * @throws Kohana_Cache_Exception + */ + public function find($tag) + { + // Prepare the statement + $statement = $this->_db->prepare('SELECT id, cache FROM caches WHERE tags LIKE :tag'); + + // Try to find + try + { + if ( ! $statement->execute(array(':tag' => "%<{$tag}>%"))) + { + return array(); + } + } + catch (PDOException $e) + { + throw new Kohana_Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + $result = array(); + + while ($row = $statement->fetchObject()) + { + // Disable notices for unserializing + $ER = error_reporting(~E_NOTICE); + + $result[$row->id] = unserialize($row->cache); + + // Turn notices back on + error_reporting($ER); + } + + return $result; + } + + /** + * Garbage collection method that cleans any expired + * cache entries from the cache. + * + * @return void + */ + public function garbage_collect() + { + // Create the sequel statement + $statement = $this->_db->prepare('DELETE FROM caches WHERE expiration < :expiration'); + + try + { + $statement->execute(array(':expiration' => time())); + } + catch (PDOException $e) + { + throw new Kohana_Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + } + + /** + * Tests whether an id exists or not + * + * @param string id + * @return boolean + * @throws Kohana_Cache_Exception + */ + protected function exists($id) + { + $statement = $this->_db->prepare('SELECT id FROM caches WHERE id = :id'); + try + { + $statement->execute(array(':id' => $this->_sanitize_id($id))); + } + catch (PDOExeption $e) + { + throw new Kohana_Cache_Exception('There was a problem querying the local SQLite3 cache. :error', array(':error' => $e->getMessage())); + } + + return (bool) $statement->fetchAll(); + } +} diff --git a/includes/kohana/modules/cache/classes/kohana/cache/tagging.php b/includes/kohana/modules/cache/classes/kohana/cache/tagging.php new file mode 100644 index 0000000..001a224 --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/tagging.php @@ -0,0 +1,42 @@ + array( // Driver group + * 'driver' => 'wincache', // using wincache driver + * ), + * ) + * + * In cases where only one cache group is required, if the group is named `default` there is + * no need to pass the group name when instantiating a cache instance. + * + * #### General cache group configuration settings + * + * Below are the settings available to all types of cache driver. + * + * Name | Required | Description + * -------------- | -------- | --------------------------------------------------------------- + * driver | __YES__ | (_string_) The driver type to use + * + * ### System requirements + * + * * Windows XP SP3 with IIS 5.1 and » FastCGI Extension + * * Windows Server 2003 with IIS 6.0 and » FastCGI Extension + * * Windows Vista SP1 with IIS 7.0 and FastCGI Module + * * Windows Server 2008 with IIS 7.0 and FastCGI Module + * * Windows 7 with IIS 7.5 and FastCGI Module + * * Windows Server 2008 R2 with IIS 7.5 and FastCGI Module + * * PHP 5.2.X, Non-thread-safe build + * * PHP 5.3 X86, Non-thread-safe VC9 build + * + * @package Kohana/Cache + * @category Base + * @author Kohana Team + * @copyright (c) 2009-2010 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_Cache_Wincache extends Cache { + + /** + * Check for existence of the wincache extension This method cannot be invoked externally. The driver must + * be instantiated using the `Cache::instance()` method. + * + * @param array configuration + * @throws Kohana_Cache_Exception + */ + protected function __construct(array $config) + { + if ( ! extension_loaded('wincache')) + { + throw new Kohana_Cache_Exception('PHP wincache extension is not available.'); + } + + parent::__construct($config); + } + + /** + * Retrieve a cached value entry by id. + * + * // Retrieve cache entry from wincache group + * $data = Cache::instance('wincache')->get('foo'); + * + * // Retrieve cache entry from wincache group and return 'bar' if miss + * $data = Cache::instance('wincache')->get('foo', 'bar'); + * + * @param string id of cache to entry + * @param string default value to return if cache miss + * @return mixed + * @throws Kohana_Cache_Exception + */ + public function get($id, $default = NULL) + { + $data = wincache_ucache_get($this->_sanitize_id($id), $success); + + return $success ? $data : $default; + } + + /** + * Set a value to cache with id and lifetime + * + * $data = 'bar'; + * + * // Set 'bar' to 'foo' in wincache group, using default expiry + * Cache::instance('wincache')->set('foo', $data); + * + * // Set 'bar' to 'foo' in wincache group for 30 seconds + * Cache::instance('wincache')->set('foo', $data, 30); + * + * @param string id of cache entry + * @param string data to set to cache + * @param integer lifetime in seconds + * @return boolean + */ + public function set($id, $data, $lifetime = NULL) + { + if ($lifetime === NULL) + { + $lifetime = Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE); + } + + return wincache_ucache_set($this->_sanitize_id($id), $data, $lifetime); + } + + /** + * Delete a cache entry based on id + * + * // Delete 'foo' entry from the wincache group + * Cache::instance('wincache')->delete('foo'); + * + * @param string id to remove from cache + * @return boolean + */ + public function delete($id) + { + return wincache_ucache_delete($this->_sanitize_id($id)); + } + + /** + * Delete all cache entries. + * + * Beware of using this method when + * using shared memory cache systems, as it will wipe every + * entry within the system for all clients. + * + * // Delete all cache entries in the wincache group + * Cache::instance('wincache')->delete_all(); + * + * @return boolean + */ + public function delete_all() + { + return wincache_ucache_clear(); + } +} diff --git a/includes/kohana/modules/cache/classes/kohana/cache/xcache.php b/includes/kohana/modules/cache/classes/kohana/cache/xcache.php new file mode 100644 index 0000000..133f18b --- /dev/null +++ b/includes/kohana/modules/cache/classes/kohana/cache/xcache.php @@ -0,0 +1,84 @@ +_sanitize_id($id))) === NULL) ? $default : $data; + } + + /** + * Set a value based on an id. Optionally add tags. + * + * @param string id + * @param string data + * @param integer lifetime [Optional] + * @return boolean + */ + public function set($id, $data, $lifetime = NULL) + { + if (NULL === $lifetime) + { + $lifetime = Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE); + } + + return xcache_set($this->_sanitize_id($id), $data, $lifetime); + } + + /** + * Delete a cache entry based on id + * + * @param string id + * @param integer timeout [Optional] + * @return boolean + */ + public function delete($id) + { + return xcache_unset($this->_sanitize_id($id)); + } + + /** + * Delete all cache entries + * To use this method xcache.admin.enable_auth has to be Off in xcache.ini + * + * @return void + */ + public function delete_all() + { + xcache_clear_cache(XC_TYPE_PHP, 0); + } +} diff --git a/includes/kohana/modules/cache/config/cache.php b/includes/kohana/modules/cache/config/cache.php new file mode 100644 index 0000000..9ec311c --- /dev/null +++ b/includes/kohana/modules/cache/config/cache.php @@ -0,0 +1,76 @@ + array + ( + 'driver' => 'memcache', + 'default_expire' => 3600, + 'compression' => FALSE, // Use Zlib compression (can cause issues with integers) + 'servers' => array + ( + array + ( + 'host' => 'localhost', // Memcache Server + 'port' => 11211, // Memcache port number + 'persistent' => FALSE, // Persistent connection + 'weight' => 1, + 'timeout' => 1, + 'retry_interval' => 15, + 'status' => TRUE, + ), + ), + 'instant_death' => TRUE, // Take server offline immediately on first fail (no retry) + ), + 'memcachetag' => array + ( + 'driver' => 'memcachetag', + 'default_expire' => 3600, + 'compression' => FALSE, // Use Zlib compression (can cause issues with integers) + 'servers' => array + ( + array + ( + 'host' => 'localhost', // Memcache Server + 'port' => 11211, // Memcache port number + 'persistent' => FALSE, // Persistent connection + 'weight' => 1, + 'timeout' => 1, + 'retry_interval' => 15, + 'status' => TRUE, + ), + ), + 'instant_death' => TRUE, + ), + 'apc' => array + ( + 'driver' => 'apc', + 'default_expire' => 3600, + ), + 'wincache' => array + ( + 'driver' => 'wincache', + 'default_expire' => 3600, + ), + 'sqlite' => array + ( + 'driver' => 'sqlite', + 'default_expire' => 3600, + 'database' => APPPATH.'cache/kohana-cache.sql3', + 'schema' => 'CREATE TABLE caches(id VARCHAR(127) PRIMARY KEY, tags VARCHAR(255), expiration INTEGER, cache TEXT)', + ), + 'eaccelerator' => array + ( + 'driver' => 'eaccelerator', + ), + 'xcache' => array + ( + 'driver' => 'xcache', + 'default_expire' => 3600, + ), + 'file' => array + ( + 'driver' => 'file', + 'cache_dir' => APPPATH.'cache', + 'default_expire' => 3600, + ) +); \ No newline at end of file diff --git a/includes/kohana/modules/cache/config/userguide.php b/includes/kohana/modules/cache/config/userguide.php new file mode 100644 index 0000000..524afc4 --- /dev/null +++ b/includes/kohana/modules/cache/config/userguide.php @@ -0,0 +1,23 @@ + array( + + // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' + 'cache' => array( + + // Whether this modules userguide pages should be shown + 'enabled' => TRUE, + + // The name that should show up on the userguide index page + 'name' => 'Cache', + + // A short description of this module, shown on the index page + 'description' => 'Common interface for caching engines.', + + // Copyright message, shown in the footer for this module + 'copyright' => '© 2008–2010 Kohana Team', + ) + ) +); \ No newline at end of file diff --git a/includes/kohana/modules/cache/guide/cache.usage.md b/includes/kohana/modules/cache/guide/cache.usage.md new file mode 100644 index 0000000..8a8239b --- /dev/null +++ b/includes/kohana/modules/cache/guide/cache.usage.md @@ -0,0 +1,219 @@ +# Kohana Cache usage + +[Kohana_Cache] provides a simple interface allowing getting, setting and deleting of cached values. Two interfaces included in _Kohana Cache_ additionally provide _tagging_ and _garbage collection_ where they are supported by the respective drivers. + +## Getting a new cache instance + +Creating a new _Kohana Cache_ instance is simple, however it must be done using the [Cache::instance] method, rather than the traditional `new` constructor. + + // Create a new instance of cache using the default group + $cache = Cache::instance(); + +The default group will use whatever is set to [Cache::$default] and must have a corresponding [configuration](cache.config) definition for that group. + +To create a cache instance using a group other than the _default_, simply provide the group name as an argument. + + // Create a new instance of the memcache group + $memcache = Cache::instance('memcache'); + +If there is a cache instance already instantiated then you can get it directly from the class member. + + [!!] Beware that this can cause issues if you do not test for the instance before trying to access it. + + // Check for the existance of the cache driver + if (isset(Cache::$instances['memcache'])) + { + // Get the existing cache instance directly (faster) + $memcache = Cache::$instances['memcache']; + } + else + { + // Get the cache driver instance (slower) + $memcache = Cache::instance('memcache'); + } + +## Setting and getting variables to and from cache + +The cache library supports scalar and object values, utilising object serialization where required (or not supported by the caching engine). This means that the majority or objects can be cached without any modification. + + [!!] Serialisation does not work with resource handles, such as filesystem, curl or socket resources. + +### Setting a value to cache + +Setting a value to cache using the [Cache::set] method can be done in one of two ways; either using the Cache instance interface, which is good for atomic operations; or getting an instance and using that for multiple operations. + +The first example demonstrates how to quickly load and set a value to the default cache instance. + + // Create a cachable object + $object = new stdClass; + + // Set a property + $object->foo = 'bar'; + + // Cache the object using default group (quick interface) with default time (3600 seconds) + Cache::instance()->set('foo', $object); + +If multiple cache operations are required, it is best to assign an instance of Cache to a variable and use that as below. + + // Set the object using a defined group for a defined time period (30 seconds) + $memcache = Cache::instance('memcache'); + $memcache->set('foo', $object, 30); + +#### Setting a value with tags + +Certain cache drivers support setting values with tags. To set a value to cache with tags using the following interface. + + // Get a cache instance that supports tags + $memcache = Cache::instance('memcachetag'); + + // Test for tagging interface + if ($memcache instanceof Kohana_Cache_Tagging) + { + // Set a value with some tags for 30 seconds + $memcache->set('foo', $object, 30, array('snafu', 'stfu', 'fubar')); + } + // Otherwise set without tags + else + { + // Set a value for 30 seconds + $memcache->set('foo', $object, 30); + } + +It is possible to implement custom tagging solutions onto existing or new cache drivers by implementing the [Kohana_Cache_Tagging] interface. Kohana_Cache only applies the interface to drivers that support tagging natively as standard. + +### Getting a value from cache + +Getting variables back from cache is achieved using the [Cache::get] method using a single key to identify the cache entry. + + // Retrieve a value from cache (quickly) + $object = Cache::instance()->get('foo'); + +In cases where the requested key is not available or the entry has expired, a default value will be returned (__NULL__ by default). It is possible to define the default value as the key is requested. + + // If the cache key is available (with default value set to FALSE) + if ($object = Cache::instance()->get('foo', FALSE)) + { + // Do something + } + else + { + // Do something else + } + +#### Getting values from cache using tags + +It is possible to retrieve values from cache grouped by tag, using the [Cache::find] method with drivers that support tagging. + + [!!] The __Memcachetag__ driver does not support the `Cache::find($tag)` interface and will throw an exception. + + // Get an instance of cache + $cache = Cache::instance('memcachetag'); + + // Wrap in a try/catch statement to gracefully handle memcachetag + try + { + // Find values based on tag + return $cache->find('snafu'); + } + catch (Kohana_Cache_Exception $e) + { + // Handle gracefully + return FALSE; + } + +### Deleting values from cache + +Deleting variables is very similar to the getting and setting methods already described. Deleting operations are split into three categories: + + - __Delete value by key__. Deletes a cached value by the associated key. + - __Delete all values__. Deletes all caches values stored in the cache instance. + - __Delete values by tag__. Deletes all values that have the supplied tag. This is only supported by Memcached-Tag and Sqlite. + +#### Delete value by key + +To delete a specific value by its associated key: + + // If the cache entry for 'foo' is deleted + if (Cache::instance()->delete('foo')) + { + // Cache entry successfully deleted, do something + } + +By default a `TRUE` value will be returned. However a `FALSE` value will be returned in instances where the key did not exist in the cache. + +#### Delete all values + +To delete all values in a specific instance: + + // If all cache items where deleted successfully + if (Cache::instance()->delete_all()) + { + // Do something + } + +It is also possible to delete all cache items in every instance: + + // For each cache instance + foreach (Cache::$instances as $group => $instance) + { + if ($instance->delete_all()) + { + var_dump('instance : '.$group.' has been flushed!'); + } + } + +#### Delete values by tag + +Some of the caching drivers support deleting by tag. This will remove all the cached values that are associated with a specific tag. Below is an example of how to robustly handle deletion by tag. + + // Get cache instance + $cache = Cache::instance(); + + // Check for tagging interface + if ($cache instanceof Kohana_Cache_Tagging) + { + // Delete all entries by the tag 'snafu' + $cache->delete_tag('snafu'); + } + +#### Garbage Collection + +Garbage Collection (GC) is the cleaning of expired cache entries. For the most part, caching engines will take care of garbage collection internally. However a few of the file based systems do not handle this task and in these circumstances it would be prudent to garbage collect at a predetermined frequency. If no garbage collection is executed, the resource storing the cache entries will eventually fill and become unusable. + +When not automated, garbage collection is the responsibility of the developer. It is prudent to have a GC probability value that dictates how likely the garbage collection routing will be run. An example of such a system is demonstrated below. + + // Get a cache instance + $cache_file = Cache::instance('file'); + + // Set a GC probability of 10% + $gc = 10; + + // If the GC probability is a hit + if (rand(0,99) <= $gc and $cache_file instanceof Kohana_Cache_GarbageCollect) + { + // Garbage Collect + $cache_file->garbage_collect(); + } + +# Interfaces + +Kohana Cache comes with two interfaces that are implemented where the drivers support them: + + - __[Kohana_Cache_Tagging] for tagging support on cache entries__ + - [Cache_MemcacheTag] + - [Cache_Sqlite] + - __[Kohana_Cache_GarbageCollect] for garbage collection with drivers without native support__ + - [Cache_File] + - [Cache_Sqlite] + +When using interface specific caching features, ensure that code checks for the required interface before using the methods supplied. The following example checks whether the garbage collection interface is available before calling the `garbage_collect` method. + + // Create a cache instance + $cache = Cache::instance(); + + // Test for Garbage Collection + if ($cache instanceof Kohana_Cache_GarbageCollect) + { + // Collect garbage + $cache->garbage_collect(); + } \ No newline at end of file diff --git a/includes/kohana/modules/cache/guide/cache/config.md b/includes/kohana/modules/cache/guide/cache/config.md new file mode 100644 index 0000000..a6d428f --- /dev/null +++ b/includes/kohana/modules/cache/guide/cache/config.md @@ -0,0 +1,168 @@ +# Kohana Cache configuration + +Kohana Cache uses configuration groups to create cache instances. A configuration group can +use any supported driver, with successive groups using multiple instances of the same driver type. + +The default cache group is loaded based on the `Cache::$default` setting. It is set to the `file` driver as standard, however this can be changed within the `/application/boostrap.php` file. + + // Change the default cache driver to memcache + Cache::$default = 'memcache'; + + // Load the memcache cache driver using default setting + $memcache = Cache::instance(); + +## Group settings + +Below are the default cache configuration groups for each supported driver. Add to- or override these settings +within the `application/config/cache.php` file. + +Name | Required | Description +-------------- | -------- | --------------------------------------------------------------- +driver | __YES__ | (_string_) The driver type to use +default_expire | __NO__ | (_string_) The driver type to use + + + 'file' => array + ( + 'driver' => 'file', + 'cache_dir' => APPPATH.'cache/.kohana_cache', + 'default_expire' => 3600, + ), + +## Memcache & Memcached-tag settings + +Name | Required | Description +-------------- | -------- | --------------------------------------------------------------- +driver | __YES__ | (_string_) The driver type to use +servers | __YES__ | (_array_) Associative array of server details, must include a __host__ key. (see _Memcache server configuration_ below) +compression | __NO__ | (_boolean_) Use data compression when caching + +### Memcache server configuration + +Name | Required | Description +---------------- | -------- | --------------------------------------------------------------- +host | __YES__ | (_string_) The host of the memcache server, i.e. __localhost__; or __127.0.0.1__; or __memcache.domain.tld__ +port | __NO__ | (_integer_) Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets. Default __11211__ +persistent | __NO__ | (_boolean_) Controls the use of a persistent connection. Default __TRUE__ +weight | __NO__ | (_integer_) Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers. Default __1__ +timeout | __NO__ | (_integer_) Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. Default __1__ +retry_interval | __NO__ | (_integer_) Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Default __15__ +status | __NO__ | (_boolean_) Controls if the server should be flagged as online. Default __TRUE__ +failure_callback | __NO__ | (_[callback](http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback)_) Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server. Default __NULL__ + + 'memcache' => array + ( + 'driver' => 'memcache', + 'default_expire' => 3600, + 'compression' => FALSE, // Use Zlib compression + (can cause issues with integers) + 'servers' => array + ( + array + ( + 'host' => 'localhost', // Memcache Server + 'port' => 11211, // Memcache port number + 'persistent' => FALSE, // Persistent connection + ), + ), + ), + 'memcachetag' => array + ( + 'driver' => 'memcachetag', + 'default_expire' => 3600, + 'compression' => FALSE, // Use Zlib compression + (can cause issues with integers) + 'servers' => array + ( + array + ( + 'host' => 'localhost', // Memcache Server + 'port' => 11211, // Memcache port number + 'persistent' => FALSE, // Persistent connection + ), + ), + ), + +## APC settings + + 'apc' => array + ( + 'driver' => 'apc', + 'default_expire' => 3600, + ), + +## SQLite settings + + 'sqlite' => array + ( + 'driver' => 'sqlite', + 'default_expire' => 3600, + 'database' => APPPATH.'cache/kohana-cache.sql3', + 'schema' => 'CREATE TABLE caches(id VARCHAR(127) PRIMARY KEY, + tags VARCHAR(255), expiration INTEGER, cache TEXT)', + ), + +## Eaccelerator settings + + 'eaccelerator' array + ( + 'driver' => 'eaccelerator', + ), + +## Xcache settings + + 'xcache' => array + ( + 'driver' => 'xcache', + 'default_expire' => 3600, + ), + +## File settings + + 'file' => array + ( + 'driver' => 'file', + 'cache_dir' => 'cache/.kohana_cache', + 'default_expire' => 3600, + ) + +## Override existing configuration group + +The following example demonstrates how to override an existing configuration setting, using the config file in `/application/config/cache.php`. + + array + ( + 'driver' => 'memcache', // Use Memcached as the default driver + 'default_expire' => 8000, // Overide default expiry + 'servers' => array + ( + // Add a new server + array + ( + 'host' => 'cache.domain.tld', + 'port' => 11211, + 'persistent' => FALSE + ) + ), + 'compression' => FALSE + ) + ); + +## Add new configuration group + +The following example demonstrates how to add a new configuration setting, using the config file in `/application/config/cache.php`. + + array + ( + 'driver' => 'apc', // Use Memcached as the default driver + 'default_expire' => 1000, // Overide default expiry + ) + ); \ No newline at end of file diff --git a/includes/kohana/modules/cache/guide/cache/examples.md b/includes/kohana/modules/cache/guide/cache/examples.md new file mode 100644 index 0000000..e69de29 diff --git a/includes/kohana/modules/cache/guide/cache/index.md b/includes/kohana/modules/cache/guide/cache/index.md new file mode 100644 index 0000000..b93b11d --- /dev/null +++ b/includes/kohana/modules/cache/guide/cache/index.md @@ -0,0 +1,59 @@ +# About Kohana Cache + +[Kohana_Cache] provides a common interface to a variety of caching engines. [Kohana_Cache_Tagging] is +supported where available natively to the cache system. Kohana Cache supports multiple +instances of cache engines through a grouped singleton pattern. + +## Supported cache engines + + * APC ([Cache_Apc]) + * eAccelerator ([Cache_Eaccelerator]) + * File ([Cache_File]) + * Memcached ([Cache_Memcache]) + * Memcached-tags ([Cache_Memcachetag]) + * SQLite ([Cache_Sqlite]) + * Xcache ([Cache_Xcache]) + +## Introduction to caching + +Caching should be implemented with consideration. Generally, caching the result of resources +is faster than reprocessing them. Choosing what, how and when to cache is vital. [PHP APC](http://php.net/manual/en/book.apc.php) is one of the fastest caching systems available, closely followed by [Memcached](http://memcached.org/). [SQLite](http://www.sqlite.org/) and File caching are two of the slowest cache methods, however usually faster than reprocessing +a complex set of instructions. + +Caching engines that use memory are considerably faster than file based alternatives. But +memory is limited whereas disk space is plentiful. If caching large datasets, such as large database result sets, it is best to use file caching. + + [!!] Cache drivers require the relevant PHP extensions to be installed. APC, eAccelerator, Memecached and Xcache all require non-standard PHP extensions. + +## What the Kohana Cache module does (and does not do) + +This module provides a simple abstracted interface to a wide selection of popular PHP cache engines. The caching API provides the basic caching methods implemented across all solutions, memory, network or disk based. Basic key / value storing is supported by all drivers, with additional tagging and garbage collection support where implemented or required. + +_Kohana Cache_ does not provide HTTP style caching for clients (web browsers) and/or proxies (_Varnish_, _Squid_). There are other Kohana modules that provide this functionality. + +## Choosing a cache provider + +Getting and setting values to cache is very simple when using the _Kohana Cache_ interface. The hardest choice is choosing which cache engine to use. When choosing a caching engine, the following criteria must be considered: + + 1. __Does the cache need to be distributed?__ + This is an important consideration as it will severely limit the options available to solutions such as Memcache when a distributed solution is required. + 2. __Does the cache need to be fast?__ + In almost all cases retrieving data from a cache is faster than execution. However generally memory based caching is considerably faster than disk based caching (see table below). + 3. __How much cache is required?__ + Cache is not endless, and memory based caches are subject to a considerably more limited storage resource. + +Driver | Storage | Speed | Tags | Distributed | Automatic Garbage Collection | Notes +---------------- | ------------ | --------- | -------- | ----------- | ---------------------------- | ----------------------- +APC | __Memory__ | Excellent | No | No | Yes | Widely available PHP opcode caching solution, improves php execution performance +eAccelerator | __Memory__ | Excellent | No | No | Yes | Limited support and no longer developed. Included for legacy systems +File | __Disk__ | Poor | No | No | No | Marginally faster than execution +Memcache (tag) | __Memory__ | Good | No (yes) | Yes | Yes | Generally fast distributed solution, but has a speed hit due to variable network latency +Sqlite | __Disk__ | Poor | Yes | No | No | Marginally faster than execution +Xcache | __Memory__ | Excellent | Yes | No | Yes | Very fast memory solution and alternative to APC + +It is possible to have hybrid cache solutions that use a combination of the engines above in different contexts. This is supported with _Kohana Cache_ as well. + +## Minimum requirements + + * Kohana 3.0.4 + * PHP 5.2.4 or greater \ No newline at end of file diff --git a/includes/kohana/modules/cache/guide/cache/menu.md b/includes/kohana/modules/cache/guide/cache/menu.md new file mode 100644 index 0000000..5218558 --- /dev/null +++ b/includes/kohana/modules/cache/guide/cache/menu.md @@ -0,0 +1,3 @@ +## [Cache]() +- [Configuration](config) +- [Usage](usage) \ No newline at end of file diff --git a/includes/kohana/modules/cache/guide/cache/usage.md b/includes/kohana/modules/cache/guide/cache/usage.md new file mode 100644 index 0000000..8a8239b --- /dev/null +++ b/includes/kohana/modules/cache/guide/cache/usage.md @@ -0,0 +1,219 @@ +# Kohana Cache usage + +[Kohana_Cache] provides a simple interface allowing getting, setting and deleting of cached values. Two interfaces included in _Kohana Cache_ additionally provide _tagging_ and _garbage collection_ where they are supported by the respective drivers. + +## Getting a new cache instance + +Creating a new _Kohana Cache_ instance is simple, however it must be done using the [Cache::instance] method, rather than the traditional `new` constructor. + + // Create a new instance of cache using the default group + $cache = Cache::instance(); + +The default group will use whatever is set to [Cache::$default] and must have a corresponding [configuration](cache.config) definition for that group. + +To create a cache instance using a group other than the _default_, simply provide the group name as an argument. + + // Create a new instance of the memcache group + $memcache = Cache::instance('memcache'); + +If there is a cache instance already instantiated then you can get it directly from the class member. + + [!!] Beware that this can cause issues if you do not test for the instance before trying to access it. + + // Check for the existance of the cache driver + if (isset(Cache::$instances['memcache'])) + { + // Get the existing cache instance directly (faster) + $memcache = Cache::$instances['memcache']; + } + else + { + // Get the cache driver instance (slower) + $memcache = Cache::instance('memcache'); + } + +## Setting and getting variables to and from cache + +The cache library supports scalar and object values, utilising object serialization where required (or not supported by the caching engine). This means that the majority or objects can be cached without any modification. + + [!!] Serialisation does not work with resource handles, such as filesystem, curl or socket resources. + +### Setting a value to cache + +Setting a value to cache using the [Cache::set] method can be done in one of two ways; either using the Cache instance interface, which is good for atomic operations; or getting an instance and using that for multiple operations. + +The first example demonstrates how to quickly load and set a value to the default cache instance. + + // Create a cachable object + $object = new stdClass; + + // Set a property + $object->foo = 'bar'; + + // Cache the object using default group (quick interface) with default time (3600 seconds) + Cache::instance()->set('foo', $object); + +If multiple cache operations are required, it is best to assign an instance of Cache to a variable and use that as below. + + // Set the object using a defined group for a defined time period (30 seconds) + $memcache = Cache::instance('memcache'); + $memcache->set('foo', $object, 30); + +#### Setting a value with tags + +Certain cache drivers support setting values with tags. To set a value to cache with tags using the following interface. + + // Get a cache instance that supports tags + $memcache = Cache::instance('memcachetag'); + + // Test for tagging interface + if ($memcache instanceof Kohana_Cache_Tagging) + { + // Set a value with some tags for 30 seconds + $memcache->set('foo', $object, 30, array('snafu', 'stfu', 'fubar')); + } + // Otherwise set without tags + else + { + // Set a value for 30 seconds + $memcache->set('foo', $object, 30); + } + +It is possible to implement custom tagging solutions onto existing or new cache drivers by implementing the [Kohana_Cache_Tagging] interface. Kohana_Cache only applies the interface to drivers that support tagging natively as standard. + +### Getting a value from cache + +Getting variables back from cache is achieved using the [Cache::get] method using a single key to identify the cache entry. + + // Retrieve a value from cache (quickly) + $object = Cache::instance()->get('foo'); + +In cases where the requested key is not available or the entry has expired, a default value will be returned (__NULL__ by default). It is possible to define the default value as the key is requested. + + // If the cache key is available (with default value set to FALSE) + if ($object = Cache::instance()->get('foo', FALSE)) + { + // Do something + } + else + { + // Do something else + } + +#### Getting values from cache using tags + +It is possible to retrieve values from cache grouped by tag, using the [Cache::find] method with drivers that support tagging. + + [!!] The __Memcachetag__ driver does not support the `Cache::find($tag)` interface and will throw an exception. + + // Get an instance of cache + $cache = Cache::instance('memcachetag'); + + // Wrap in a try/catch statement to gracefully handle memcachetag + try + { + // Find values based on tag + return $cache->find('snafu'); + } + catch (Kohana_Cache_Exception $e) + { + // Handle gracefully + return FALSE; + } + +### Deleting values from cache + +Deleting variables is very similar to the getting and setting methods already described. Deleting operations are split into three categories: + + - __Delete value by key__. Deletes a cached value by the associated key. + - __Delete all values__. Deletes all caches values stored in the cache instance. + - __Delete values by tag__. Deletes all values that have the supplied tag. This is only supported by Memcached-Tag and Sqlite. + +#### Delete value by key + +To delete a specific value by its associated key: + + // If the cache entry for 'foo' is deleted + if (Cache::instance()->delete('foo')) + { + // Cache entry successfully deleted, do something + } + +By default a `TRUE` value will be returned. However a `FALSE` value will be returned in instances where the key did not exist in the cache. + +#### Delete all values + +To delete all values in a specific instance: + + // If all cache items where deleted successfully + if (Cache::instance()->delete_all()) + { + // Do something + } + +It is also possible to delete all cache items in every instance: + + // For each cache instance + foreach (Cache::$instances as $group => $instance) + { + if ($instance->delete_all()) + { + var_dump('instance : '.$group.' has been flushed!'); + } + } + +#### Delete values by tag + +Some of the caching drivers support deleting by tag. This will remove all the cached values that are associated with a specific tag. Below is an example of how to robustly handle deletion by tag. + + // Get cache instance + $cache = Cache::instance(); + + // Check for tagging interface + if ($cache instanceof Kohana_Cache_Tagging) + { + // Delete all entries by the tag 'snafu' + $cache->delete_tag('snafu'); + } + +#### Garbage Collection + +Garbage Collection (GC) is the cleaning of expired cache entries. For the most part, caching engines will take care of garbage collection internally. However a few of the file based systems do not handle this task and in these circumstances it would be prudent to garbage collect at a predetermined frequency. If no garbage collection is executed, the resource storing the cache entries will eventually fill and become unusable. + +When not automated, garbage collection is the responsibility of the developer. It is prudent to have a GC probability value that dictates how likely the garbage collection routing will be run. An example of such a system is demonstrated below. + + // Get a cache instance + $cache_file = Cache::instance('file'); + + // Set a GC probability of 10% + $gc = 10; + + // If the GC probability is a hit + if (rand(0,99) <= $gc and $cache_file instanceof Kohana_Cache_GarbageCollect) + { + // Garbage Collect + $cache_file->garbage_collect(); + } + +# Interfaces + +Kohana Cache comes with two interfaces that are implemented where the drivers support them: + + - __[Kohana_Cache_Tagging] for tagging support on cache entries__ + - [Cache_MemcacheTag] + - [Cache_Sqlite] + - __[Kohana_Cache_GarbageCollect] for garbage collection with drivers without native support__ + - [Cache_File] + - [Cache_Sqlite] + +When using interface specific caching features, ensure that code checks for the required interface before using the methods supplied. The following example checks whether the garbage collection interface is available before calling the `garbage_collect` method. + + // Create a cache instance + $cache = Cache::instance(); + + // Test for Garbage Collection + if ($cache instanceof Kohana_Cache_GarbageCollect) + { + // Collect garbage + $cache->garbage_collect(); + } \ No newline at end of file diff --git a/includes/kohana/modules/cache/tests/cache/KohanaCacheTest.php b/includes/kohana/modules/cache/tests/cache/KohanaCacheTest.php new file mode 100644 index 0000000..229e7d3 --- /dev/null +++ b/includes/kohana/modules/cache/tests/cache/KohanaCacheTest.php @@ -0,0 +1,91 @@ +delete_all(); + + self::$test_instance->set('testGet1', 'foo', 3600); + } + + public function tearDown() + { + self::$test_instance->delete_all(); + self::$test_instance = NULL; + } + + /** + * Tests the cache static instance method + */ + public function testInstance() + { + $file_instance = Cache::instance('file'); + $file_instance2 = Cache::instance('file'); + + // Try and load a Cache instance + $this->assertType('Kohana_Cache', Cache::instance()); + $this->assertType('Kohana_Cache_File', $file_instance); + + // Test instances are only initialised once + $this->assertTrue(spl_object_hash($file_instance) == spl_object_hash($file_instance2)); + + // Test the publically accessible Cache instance store + $this->assertTrue(spl_object_hash(Cache::$instances['file']) == spl_object_hash($file_instance)); + + // Get the constructor method + $constructorMethod = new ReflectionMethod($file_instance, '__construct'); + + // Test the constructor for hidden visibility + $this->assertTrue($constructorMethod->isProtected(), '__construct is does not have protected visibility'); + } + + public function testGet() + { + // Try and get a non property + $this->assertNull(self::$test_instance->get('testGet0')); + + // Try and get a non property with default return value + $this->assertEquals('bar', self::$test_instance->get('testGet0', 'bar')); + + // Try and get a real cached property + $this->assertEquals('foo', self::$test_instance->get('testGet1')); + } + + public function testSet() + { + $value = 'foobar'; + $value2 = 'snafu'; + + // Set a new property + $this->assertTrue(self::$test_instance->set('testSet1', $value)); + + // Test the property exists + $this->assertEquals(self::$test_instance->get('testSet1'), $value); + + // Test short set + $this->assertTrue(self::$test_instance->set('testSet2', $value2, 3)); + + // Test the property exists + $this->assertEquals(self::$test_instance->get('testSet2'), $value2); + + // Allow test2 to expire + sleep(4); + + // Test the property has expired + $this->assertNull(self::$test_instance->get('testSet2')); + } + + public function testDelete() + { + + } + + public function testDeleteAll() + { + + } +} \ No newline at end of file diff --git a/includes/kohana/modules/cache/tests/phpunit.xml b/includes/kohana/modules/cache/tests/phpunit.xml new file mode 100644 index 0000000..5e3b9c7 --- /dev/null +++ b/includes/kohana/modules/cache/tests/phpunit.xml @@ -0,0 +1,16 @@ + + + + + cache/ + + + diff --git a/includes/kohana/modules/codebench/classes/bench/arrcallback.php b/includes/kohana/modules/codebench/classes/bench/arrcallback.php new file mode 100644 index 0000000..698a6b8 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/arrcallback.php @@ -0,0 +1,57 @@ + + */ +class Bench_ArrCallback extends Codebench { + + public $description = + 'Parsing command[param,param] strings in Arr::callback(): + http://github.com/shadowhand/kohana/commit/c3aaae849164bf92a486e29e736a265b350cb4da#L0R127'; + + public $loops = 10000; + + public $subjects = array + ( + // Valid callback strings + 'foo', + 'foo::bar', + 'foo[apple,orange]', + 'foo::bar[apple,orange]', + '[apple,orange]', // no command, only params + 'foo[[apple],[orange]]', // params with brackets inside + + // Invalid callback strings + 'foo[apple,orange', // no closing bracket + ); + + public function bench_shadowhand($subject) + { + // The original regex we're trying to optimize + if (preg_match('/([^\[]*+)\[(.*)\]/', $subject, $match)) + return $match; + } + + public function bench_geert_regex_1($subject) + { + // Added ^ and $ around the whole pattern + if (preg_match('/^([^\[]*+)\[(.*)\]$/', $subject, $matches)) + return $matches; + } + + public function bench_geert_regex_2($subject) + { + // A rather experimental approach using \K which requires PCRE 7.2 ~ PHP 5.2.4 + // Note: $matches[0] = params, $matches[1] = command + if (preg_match('/^([^\[]*+)\[\K.*(?=\]$)/', $subject, $matches)) + return $matches; + } + + public function bench_geert_str($subject) + { + // A native string function approach which beats all the regexes + if (strpos($subject, '[') !== FALSE AND substr($subject, -1) === ']') + return explode('[', substr($subject, 0, -1), 2); + } +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/autolinkemails.php b/includes/kohana/modules/codebench/classes/bench/autolinkemails.php new file mode 100644 index 0000000..46e7a15 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/autolinkemails.php @@ -0,0 +1,70 @@ + + */ +class Bench_AutoLinkEmails extends Codebench { + + public $description = + 'Fixing #2772, and comparing some possibilities.'; + + public $loops = 1000; + + public $subjects = array + ( + '
    +
  • voorzitter@xxxx.com
  • +
  • vicevoorzitter@xxxx.com
  • +
', + ); + + // The original function, with str_replace replaced by preg_replace. Looks clean. + public function bench_match_all_loop($subject) + { + if (preg_match_all('~\b(?|58;)(?!\.)[-+_a-z0-9.]++(?|58;)(?!\.)[-+_a-z0-9.]++(?|58;)(?!\.)[-+_a-z0-9.]++(?|58;)(?!\.)[-+_a-z0-9.]++(? + */ +class Bench_DateSpan extends Codebench { + + public $description = + 'Optimization for Date::span().'; + + public $loops = 1000; + + public $subjects = array(); + + public function __construct() + { + parent::__construct(); + + $this->subjects = array( + time(), + time() - Date::MONTH, + time() - Date::YEAR, + time() - Date::YEAR * 10, + ); + } + + // Original method + public static function bench_span_original($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds') + { + // Array with the output formats + $output = preg_split('/[^a-z]+/', strtolower((string) $output)); + + // Invalid output + if (empty($output)) + return FALSE; + + // Make the output values into keys + extract(array_flip($output), EXTR_SKIP); + + if ($local === NULL) + { + // Calculate the span from the current time + $local = time(); + } + + // Calculate timespan (seconds) + $timespan = abs($remote - $local); + + if (isset($years)) + { + $timespan -= Date::YEAR * ($years = (int) floor($timespan / Date::YEAR)); + } + + if (isset($months)) + { + $timespan -= Date::MONTH * ($months = (int) floor($timespan / Date::MONTH)); + } + + if (isset($weeks)) + { + $timespan -= Date::WEEK * ($weeks = (int) floor($timespan / Date::WEEK)); + } + + if (isset($days)) + { + $timespan -= Date::DAY * ($days = (int) floor($timespan / Date::DAY)); + } + + if (isset($hours)) + { + $timespan -= Date::HOUR * ($hours = (int) floor($timespan / Date::HOUR)); + } + + if (isset($minutes)) + { + $timespan -= Date::MINUTE * ($minutes = (int) floor($timespan / Date::MINUTE)); + } + + // Seconds ago, 1 + if (isset($seconds)) + { + $seconds = $timespan; + } + + // Remove the variables that cannot be accessed + unset($timespan, $remote, $local); + + // Deny access to these variables + $deny = array_flip(array('deny', 'key', 'difference', 'output')); + + // Return the difference + $difference = array(); + foreach ($output as $key) + { + if (isset($$key) AND ! isset($deny[$key])) + { + // Add requested key to the output + $difference[$key] = $$key; + } + } + + // Invalid output formats string + if (empty($difference)) + return FALSE; + + // If only one output format was asked, don't put it in an array + if (count($difference) === 1) + return current($difference); + + // Return array + return $difference; + } + + // Using an array for the output + public static function bench_span_use_array($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds') + { + // Array with the output formats + $output = preg_split('/[^a-z]+/', strtolower((string) $output)); + + // Invalid output + if (empty($output)) + return FALSE; + + // Convert the list of outputs to an associative array + $output = array_combine($output, array_fill(0, count($output), 0)); + + // Make the output values into keys + extract(array_flip($output), EXTR_SKIP); + + if ($local === NULL) + { + // Calculate the span from the current time + $local = time(); + } + + // Calculate timespan (seconds) + $timespan = abs($remote - $local); + + if (isset($output['years'])) + { + $timespan -= Date::YEAR * ($output['years'] = (int) floor($timespan / Date::YEAR)); + } + + if (isset($output['months'])) + { + $timespan -= Date::MONTH * ($output['months'] = (int) floor($timespan / Date::MONTH)); + } + + if (isset($output['weeks'])) + { + $timespan -= Date::WEEK * ($output['weeks'] = (int) floor($timespan / Date::WEEK)); + } + + if (isset($output['days'])) + { + $timespan -= Date::DAY * ($output['days'] = (int) floor($timespan / Date::DAY)); + } + + if (isset($output['hours'])) + { + $timespan -= Date::HOUR * ($output['hours'] = (int) floor($timespan / Date::HOUR)); + } + + if (isset($output['minutes'])) + { + $timespan -= Date::MINUTE * ($output['minutes'] = (int) floor($timespan / Date::MINUTE)); + } + + // Seconds ago, 1 + if (isset($output['seconds'])) + { + $output['seconds'] = $timespan; + } + + if (count($output) === 1) + { + // Only a single output was requested, return it + return array_pop($output); + } + + // Return array + return $output; + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/explodelimit.php b/includes/kohana/modules/codebench/classes/bench/explodelimit.php new file mode 100644 index 0000000..4bf2acc --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/explodelimit.php @@ -0,0 +1,34 @@ + + */ +class Bench_ExplodeLimit extends Codebench { + + public $description = + 'Having a look at the effect of adding a limit to the explode function.
+ http://stackoverflow.com/questions/1308149/how-to-get-a-part-of-url-between-4th-and-5th-slashes'; + + public $loops = 10000; + + public $subjects = array + ( + 'http://example.com/articles/123a/view', + 'http://example.com/articles/123a/view/x/x/x/x/x', + 'http://example.com/articles/123a/view/x/x/x/x/x/x/x/x/x/x/x/x/x/x/x/x/x/x', + ); + + public function bench_explode_without_limit($subject) + { + $parts = explode('/', $subject); + return $parts[4]; + } + + public function bench_explode_with_limit($subject) + { + $parts = explode('/', $subject, 6); + return $parts[4]; + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/gruberurl.php b/includes/kohana/modules/codebench/classes/bench/gruberurl.php new file mode 100644 index 0000000..af23975 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/gruberurl.php @@ -0,0 +1,61 @@ + + */ +class Bench_GruberURL extends Codebench { + + public $description = + 'Optimization for http://daringfireball.net/2009/11/liberal_regex_for_matching_urls'; + + public $loops = 10000; + + public $subjects = array + ( + 'http://foo.com/blah_blah', + 'http://foo.com/blah_blah/', + '(Something like http://foo.com/blah_blah)', + 'http://foo.com/blah_blah_(wikipedia)', + '(Something like http://foo.com/blah_blah_(wikipedia))', + 'http://foo.com/blah_blah.', + 'http://foo.com/blah_blah/.', + '', + '', + 'http://foo.com/blah_blah,', + 'http://www.example.com/wpstyle/?p=364.', + 'http://✪df.ws/e7l', + 'rdar://1234', + 'rdar:/1234', + 'x-yojimbo-item://6303E4C1-xxxx-45A6-AB9D-3A908F59AE0E', + 'message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e', + 'http://➡.ws/䨹', + 'www.➡.ws/䨹', + 'http://example.com', + 'Just a www.example.com link.', + // To test the use of possessive quatifiers: + 'httpppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp', + ); + + public function bench_daringfireball($subject) + { + // Original regex by John Gruber + preg_match('~\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))~', $subject, $matches); + return (empty($matches)) ? FALSE : $matches[0]; + } + + public function bench_daringfireball_v2($subject) + { + // Removed outer capturing parentheses, made another pair non-capturing + preg_match('~\b(?:[\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|/))~', $subject, $matches); + return (empty($matches)) ? FALSE : $matches[0]; + } + + public function bench_daringfireball_v3($subject) + { + // Made quantifiers possessive where possible + preg_match('~\b(?:[\w-]++://?+|www[.])[^\s()<>]+(?:\([\w\d]++\)|(?:[^[:punct:]\s]|/))~', $subject, $matches); + return (empty($matches)) ? FALSE : $matches[0]; + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/ltrimdigits.php b/includes/kohana/modules/codebench/classes/bench/ltrimdigits.php new file mode 100644 index 0000000..71ead49 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/ltrimdigits.php @@ -0,0 +1,28 @@ + + */ +class Bench_LtrimDigits extends Codebench { + + public $description = 'Chopping off leading digits: regex vs ltrim.'; + + public $loops = 100000; + + public $subjects = array + ( + '123digits', + 'no-digits', + ); + + public function bench_regex($subject) + { + return preg_replace('/^\d+/', '', $subject); + } + + public function bench_ltrim($subject) + { + return ltrim($subject, '0..9'); + } +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/mddobaseurl.php b/includes/kohana/modules/codebench/classes/bench/mddobaseurl.php new file mode 100644 index 0000000..1ad2a1b --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/mddobaseurl.php @@ -0,0 +1,66 @@ + + */ +class Bench_MDDoBaseURL extends Codebench { + + public $description = + 'Optimization for the doBaseURL() method of Kohana_Kodoc_Markdown + for the Kohana Userguide.'; + + public $loops = 10000; + + public $subjects = array + ( + // Valid matches + '[filesystem](about.filesystem)', + '[filesystem](about.filesystem "Optional title")', + '[same page link](#id)', + '[object oriented](http://wikipedia.org/wiki/Object-Oriented_Programming)', + + // Invalid matches + '![this is image syntax](about.filesystem)', + '[filesystem](about.filesystem', + ); + + public function bench_original($subject) + { + // The original regex contained a bug, which is fixed here for benchmarking purposes. + // At the very start of the regex, (?!!) has been replace by (? + */ +class Bench_MDDoImageURL extends Codebench { + + public $description = + 'Optimization for the doImageURL() method of Kohana_Kodoc_Markdown + for the Kohana Userguide.'; + + public $loops = 10000; + + public $subjects = array + ( + // Valid matches + '![Alt text](http://img.skitch.com/20091019-rud5mmqbf776jwua6hx9nm1n.png)', + '![Alt text](https://img.skitch.com/20091019-rud5mmqbf776jwua6hx9nm1n.png)', + '![Alt text](otherprotocol://image.png "Optional title")', + '![Alt text](img/install.png "Optional title")', + '![Alt text containing [square] brackets](img/install.png)', + '![Empty src]()', + + // Invalid matches + '![Alt text](img/install.png "No closing parenthesis"', + ); + + public function bench_original($subject) + { + return preg_replace_callback('~!\[(.+?)\]\((\S*(?:\s*".+?")?)\)~', array($this, '_add_image_url_original'), $subject); + } + protected function _add_image_url_original($matches) + { + if ($matches[2] AND strpos($matches[2], '://') === FALSE) + { + // Add the base url to the link URL + $matches[2] = 'http://BASE/'.$matches[2]; + } + + // Recreate the link + return "![{$matches[1]}]({$matches[2]})"; + } + + public function bench_optimized_callback($subject) + { + // Moved the check for "://" to the regex, simplifying the callback function + return preg_replace_callback('~!\[(.+?)\]\((?!\w++://)(\S*(?:\s*+".+?")?)\)~', array($this, '_add_image_url_optimized'), $subject); + } + protected function _add_image_url_optimized($matches) + { + // Add the base url to the link URL + $matches[2] = 'http://BASE/'.$matches[2]; + + // Recreate the link + return "![{$matches[1]}]({$matches[2]})"; + } + + public function bench_callback_gone($subject) + { + // All the optimized callback was doing now, is prepend some text to the URL. + // We don't need a callback for that, and that should be clearly faster. + return preg_replace('~(!\[.+?\]\()(?!\w++://)(\S*(?:\s*+".+?")?\))~', '$1http://BASE/$2', $subject); + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/mddoincludeviews.php b/includes/kohana/modules/codebench/classes/bench/mddoincludeviews.php new file mode 100644 index 0000000..9cac3d6 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/mddoincludeviews.php @@ -0,0 +1,50 @@ + + */ +class Bench_MDDoIncludeViews extends Codebench { + + public $description = + 'Optimization for the doIncludeViews() method of Kohana_Kodoc_Markdown + for the Kohana Userguide.'; + + public $loops = 10000; + + public $subjects = array + ( + // Valid matches + '{{one}} two {{three}}', + '{{userguide/examples/hello_world_error}}', + + // Invalid matches + '{}', + '{{}}', + '{{userguide/examples/hello_world_error}', + '{{userguide/examples/hello_world_error }}', + '{{userguide/examples/{{hello_world_error }}', + ); + + public function bench_original($subject) + { + preg_match_all('/{{(\S+?)}}/m', $subject, $matches, PREG_SET_ORDER); + return $matches; + } + + public function bench_possessive($subject) + { + // Using a possessive character class + // Removed useless /m modifier + preg_match_all('/{{([^\s{}]++)}}/', $subject, $matches, PREG_SET_ORDER); + return $matches; + } + + public function bench_lookaround($subject) + { + // Using lookaround to move $mathes[1] into $matches[0] + preg_match_all('/(?<={{)[^\s{}]++(?=}})/', $subject, $matches, PREG_SET_ORDER); + return $matches; + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/stripnullbytes.php b/includes/kohana/modules/codebench/classes/bench/stripnullbytes.php new file mode 100644 index 0000000..4d28853 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/stripnullbytes.php @@ -0,0 +1,37 @@ + + */ +class Bench_StripNullBytes extends Codebench { + + public $description = + 'String replacement comparisons related to #2676.'; + + public $loops = 1000; + + public $subjects = array + ( + "\0", + "\0\0\0\0\0\0\0\0\0\0", + "bla\0bla\0bla\0bla\0bla\0bla\0bla\0bla\0bla\0bla", + "blablablablablablablablablablablablablablablabla", + ); + + public function bench_str_replace($subject) + { + return str_replace("\0", '', $subject); + } + + public function bench_strtr($subject) + { + return strtr($subject, array("\0" => '')); + } + + public function bench_preg_replace($subject) + { + return preg_replace('~\0+~', '', $subject); + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/transliterate.php b/includes/kohana/modules/codebench/classes/bench/transliterate.php new file mode 100644 index 0000000..aff8693 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/transliterate.php @@ -0,0 +1,65 @@ + + */ +class Bench_Transliterate extends Codebench { + + public $description = + 'Inspired by: + http://forum.kohanaframework.org/comments.php?DiscussionID=6113'; + + public $loops = 10; + + public $subjects = array + ( + // ASCII + 'a', 'b', 'c', 'd', '1', '2', '3', + + // Non-ASCII + 'à', 'ô', 'ď', 'ḟ', 'ë', 'š', 'ơ', + 'ß', 'ă', 'ř', 'ț', 'ň', 'ā', 'ķ', + 'ŝ', 'ỳ', 'ņ', 'ĺ', 'ħ', 'ṗ', 'ó', + 'ú', 'ě', 'é', 'ç', 'ẁ', 'ċ', 'õ', + 'ṡ', 'ø', 'ģ', 'ŧ', 'ș', 'ė', 'ĉ', + 'ś', 'î', 'ű', 'ć', 'ę', 'ŵ', 'ṫ', + 'ū', 'č', 'ö', 'è', 'ŷ', 'ą', 'ł', + 'ų', 'ů', 'ş', 'ğ', 'ļ', 'ƒ', 'ž', + 'ẃ', 'ḃ', 'å', 'ì', 'ï', 'ḋ', 'ť', + 'ŗ', 'ä', 'í', 'ŕ', 'ê', 'ü', 'ò', + 'ē', 'ñ', 'ń', 'ĥ', 'ĝ', 'đ', 'ĵ', + 'ÿ', 'ũ', 'ŭ', 'ư', 'ţ', 'ý', 'ő', + 'â', 'ľ', 'ẅ', 'ż', 'ī', 'ã', 'ġ', + 'ṁ', 'ō', 'ĩ', 'ù', 'į', 'ź', 'á', + 'û', 'þ', 'ð', 'æ', 'µ', 'ĕ', 'ı', + 'À', 'Ô', 'Ď', 'Ḟ', 'Ë', 'Š', 'Ơ', + 'Ă', 'Ř', 'Ț', 'Ň', 'Ā', 'Ķ', 'Ĕ', + 'Ŝ', 'Ỳ', 'Ņ', 'Ĺ', 'Ħ', 'Ṗ', 'Ó', + 'Ú', 'Ě', 'É', 'Ç', 'Ẁ', 'Ċ', 'Õ', + 'Ṡ', 'Ø', 'Ģ', 'Ŧ', 'Ș', 'Ė', 'Ĉ', + 'Ś', 'Î', 'Ű', 'Ć', 'Ę', 'Ŵ', 'Ṫ', + 'Ū', 'Č', 'Ö', 'È', 'Ŷ', 'Ą', 'Ł', + 'Ų', 'Ů', 'Ş', 'Ğ', 'Ļ', 'Ƒ', 'Ž', + 'Ẃ', 'Ḃ', 'Å', 'Ì', 'Ï', 'Ḋ', 'Ť', + 'Ŗ', 'Ä', 'Í', 'Ŕ', 'Ê', 'Ü', 'Ò', + 'Ē', 'Ñ', 'Ń', 'Ĥ', 'Ĝ', 'Đ', 'Ĵ', + 'Ÿ', 'Ũ', 'Ŭ', 'Ư', 'Ţ', 'Ý', 'Ő', + 'Â', 'Ľ', 'Ẅ', 'Ż', 'Ī', 'Ã', 'Ġ', + 'Ṁ', 'Ō', 'Ĩ', 'Ù', 'Į', 'Ź', 'Á', + 'Û', 'Þ', 'Ð', 'Æ', 'İ', + ); + + public function bench_utf8($subject) + { + return UTF8::transliterate_to_ascii($subject); + } + + public function bench_iconv($subject) + { + // Note: need to suppress errors on iconv because some chars trigger the following notice: + // "Detected an illegal character in input string" + return preg_replace('~[^-a-z0-9]+~i', '', @iconv('UTF-8', 'ASCII//TRANSLIT', $subject)); + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/urlsite.php b/includes/kohana/modules/codebench/classes/bench/urlsite.php new file mode 100644 index 0000000..0db347d --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/urlsite.php @@ -0,0 +1,123 @@ + + */ +class Bench_URLSite extends Codebench { + + public $description = 'http://dev.kohanaframework.org/issues/3110'; + + public $loops = 1000; + + public $subjects = array + ( + '', + 'news', + 'news/', + '/news/', + 'news/page/5', + 'news/page:5', + 'http://example.com/', + 'http://example.com/hello', + 'http://example.com:80/', + 'http://user:pass@example.com/', + ); + + public function __construct() + { + foreach ($this->subjects as $subject) + { + // Automatically create URIs with query string and/or fragment part appended + $this->subjects[] = $subject.'?query=string'; + $this->subjects[] = $subject.'#fragment'; + $this->subjects[] = $subject.'?query=string#fragment'; + } + + parent::__construct(); + } + + public function bench_original($uri) + { + // Get the path from the URI + $path = trim(parse_url($uri, PHP_URL_PATH), '/'); + + if ($query = parse_url($uri, PHP_URL_QUERY)) + { + $query = '?'.$query; + } + + if ($fragment = parse_url($uri, PHP_URL_FRAGMENT)) + { + $fragment = '#'.$fragment; + } + + return $path.$query.$fragment; + } + + public function bench_explode($uri) + { + // Chop off possible scheme, host, port, user and pass parts + $path = preg_replace('~^[-a-z0-9+.]++://[^/]++/?~', '', trim($uri, '/')); + + $fragment = ''; + $explode = explode('#', $path, 2); + if (isset($explode[1])) + { + $path = $explode[0]; + $fragment = '#'.$explode[1]; + } + + $query = ''; + $explode = explode('?', $path, 2); + if (isset($explode[1])) + { + $path = $explode[0]; + $query = '?'.$explode[1]; + } + + return $path.$query.$fragment; + } + + public function bench_regex($uri) + { + preg_match('~^(?:[-a-z0-9+.]++://[^/]++/?)?([^?#]++)?(\?[^#]*+)?(#.*)?~', trim($uri, '/'), $matches); + $path = Arr::get($matches, 1, ''); + $query = Arr::get($matches, 2, ''); + $fragment = Arr::get($matches, 3, ''); + + return $path.$query.$fragment; + } + + public function bench_regex_without_arrget($uri) + { + preg_match('~^(?:[-a-z0-9+.]++://[^/]++/?)?([^?#]++)?(\?[^#]*+)?(#.*)?~', trim($uri, '/'), $matches); + $path = isset($matches[1]) ? $matches[1] : ''; + $query = isset($matches[2]) ? $matches[2] : ''; + $fragment = isset($matches[3]) ? $matches[3] : ''; + + return $path.$query.$fragment; + } + + // And then I thought, why do all the work of extracting the query and fragment parts and then reappending them? + // Just leaving them alone should be fine, right? As a bonus we get a very nice speed boost. + public function bench_less_is_more($uri) + { + // Chop off possible scheme, host, port, user and pass parts + $path = preg_replace('~^[-a-z0-9+.]++://[^/]++/?~', '', trim($uri, '/')); + + return $path; + } + + public function bench_less_is_more_with_strpos_optimization($uri) + { + if (strpos($uri, '://') !== FALSE) + { + // Chop off possible scheme, host, port, user and pass parts + $uri = preg_replace('~^[-a-z0-9+.]++://[^/]++/?~', '', trim($uri, '/')); + } + + return $uri; + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/userfuncarray.php b/includes/kohana/modules/codebench/classes/bench/userfuncarray.php new file mode 100644 index 0000000..f53d0c6 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/userfuncarray.php @@ -0,0 +1,58 @@ + + */ +class Bench_UserFuncArray extends Codebench { + + public $description = + 'Testing the speed difference of using call_user_func_array + compared to counting args and doing manual calls.'; + + public $loops = 100000; + + public $subjects = array + ( + // Argument sets + array(), + array('one'), + array('one', 'two'), + array('one', 'two', 'three'), + ); + + public function bench_count_args($args) + { + $name = 'callme'; + switch (count($args)) + { + case 1: + $this->$name($args[0]); + break; + case 2: + $this->$name($args[0], $args[1]); + break; + case 3: + $this->$name($args[0], $args[1], $args[2]); + break; + case 4: + $this->$name($args[0], $args[1], $args[2], $args[3]); + break; + default: + call_user_func_array(array($this, $name), $args); + break; + } + } + + public function bench_direct_call($args) + { + $name = 'callme'; + call_user_func_array(array($this, $name), $args); + } + + protected function callme() + { + return count(func_get_args()); + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/validcolor.php b/includes/kohana/modules/codebench/classes/bench/validcolor.php new file mode 100644 index 0000000..8d04608 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/validcolor.php @@ -0,0 +1,116 @@ + + */ +class Bench_ValidColor extends Codebench { + + public $description = + 'Optimization for Validate::color(). + See: http://forum.kohanaphp.com/comments.php?DiscussionID=2192. + + Note that the methods with an _invalid suffix contain flawed regexes and should be + completely discarded. I left them in here for educational purposes, and to remind myself + to think harder and test more thoroughly. It can\'t be that I only found out so late in + the game. For the regex explanation have a look at the forum topic mentioned earlier.'; + + public $loops = 10000; + + public $subjects = array + ( + // Valid colors + 'aaA', + '123', + '000000', + '#123456', + '#abcdef', + + // Invalid colors + 'ggg', + '1234', + '#1234567', + "#000\n", + '}§è!çà%$z', + ); + + // Note that I added the D modifier to corey's regexes. We need to match exactly + // the same if we want the benchmarks to be of any value. + public function bench_corey_regex_1_invalid($subject) + { + return (bool) preg_match('/^#?([0-9a-f]{1,2}){3}$/iD', $subject); + } + + public function bench_corey_regex_2($subject) + { + return (bool) preg_match('/^#?([0-9a-f]){3}(([0-9a-f]){3})?$/iD', $subject); + } + + // Optimized corey_regex_1 + // Using non-capturing parentheses and a possessive interval + public function bench_geert_regex_1a_invalid($subject) + { + return (bool) preg_match('/^#?(?:[0-9a-f]{1,2}+){3}$/iD', $subject); + } + + // Optimized corey_regex_2 + // Removed useless parentheses, made the remaining ones non-capturing + public function bench_geert_regex_2a($subject) + { + return (bool) preg_match('/^#?[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $subject); + } + + // Optimized geert_regex_1a + // Possessive "#" + public function bench_geert_regex_1b_invalid($subject) + { + return (bool) preg_match('/^#?+(?:[0-9a-f]{1,2}+){3}$/iD', $subject); + } + + // Optimized geert_regex_2a + // Possessive "#" + public function bench_geert_regex_2b($subject) + { + return (bool) preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $subject); + } + + // Using \z instead of $ + public function bench_salathe_regex_1($subject) + { + return (bool) preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?\z/i', $subject); + } + + // Using \A instead of ^ + public function bench_salathe_regex_2($subject) + { + return (bool) preg_match('/\A#?+[0-9a-f]{3}(?:[0-9a-f]{3})?\z/i', $subject); + } + + // A solution without regex + public function bench_geert_str($subject) + { + if ($subject[0] === '#') + { + $subject = substr($subject, 1); + } + + $strlen = strlen($subject); + return (($strlen === 3 OR $strlen === 6) AND ctype_xdigit($subject)); + } + + // An ugly, but fast, solution without regex + public function bench_salathe_str($subject) + { + if ($subject[0] === '#') + { + $subject = substr($subject, 1); + } + + // TRUE if: + // 1. $subject is 6 or 3 chars long + // 2. $subject contains only hexadecimal digits + return (((isset($subject[5]) AND ! isset($subject[6])) OR + (isset($subject[2]) AND ! isset($subject[3]))) + AND ctype_xdigit($subject)); + } +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/bench/validurl.php b/includes/kohana/modules/codebench/classes/bench/validurl.php new file mode 100644 index 0000000..3c88675 --- /dev/null +++ b/includes/kohana/modules/codebench/classes/bench/validurl.php @@ -0,0 +1,105 @@ + + */ +class Bench_ValidURL extends Codebench { + + public $description = + 'filter_var vs regex: + http://dev.kohanaframework.org/issues/2847'; + + public $loops = 1000; + + public $subjects = array + ( + // Valid + 'http://google.com', + 'http://google.com/', + 'http://google.com/?q=abc', + 'http://google.com/#hash', + 'http://localhost', + 'http://hello-world.pl', + 'http://hello--world.pl', + 'http://h.e.l.l.0.pl', + 'http://server.tld/get/info', + 'http://127.0.0.1', + 'http://127.0.0.1:80', + 'http://user@127.0.0.1', + 'http://user:pass@127.0.0.1', + 'ftp://my.server.com', + 'rss+xml://rss.example.com', + + // Invalid + 'http://google.2com', + 'http://google.com?q=abc', + 'http://google.com#hash', + 'http://hello-.pl', + 'http://hel.-lo.world.pl', + 'http://ww£.google.com', + 'http://127.0.0.1234', + 'http://127.0.0.1.1', + 'http://user:@127.0.0.1', + "http://finalnewline.com\n", + ); + + public function bench_filter_var($url) + { + return (bool) filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED); + } + + public function bench_regex($url) + { + // Based on http://www.apps.ietf.org/rfc/rfc1738.html#sec-5 + if ( ! preg_match( + '~^ + + # scheme + [-a-z0-9+.]++:// + + # username:password (optional) + (?: + [-a-z0-9$_.+!*\'(),;?&=%]++ # username + (?::[-a-z0-9$_.+!*\'(),;?&=%]++)? # password (optional) + @ + )? + + (?: + # ip address + \d{1,3}+(?:\.\d{1,3}+){3}+ + + | # or + + # hostname (captured) + ( + (?!-)[-a-z0-9]{1,63}+(? 253) + return FALSE; + + // An extra check for the top level domain + // It must start with a letter + $tld = ltrim(substr($matches[1], (int) strrpos($matches[1], '.')), '.'); + return ctype_alpha($tld[0]); + } + +} \ No newline at end of file diff --git a/includes/kohana/modules/codebench/classes/codebench.php b/includes/kohana/modules/codebench/classes/codebench.php new file mode 100644 index 0000000..0f4c55c --- /dev/null +++ b/includes/kohana/modules/codebench/classes/codebench.php @@ -0,0 +1,3 @@ +request->redirect('codebench/'.trim($_POST['class'])); + + // Pass the class name on to the view + $this->template->class = (string) $class; + + // Try to load the class, then run it + if (Kohana::auto_load($class) === TRUE) + { + $codebench = new $class; + $this->template->codebench = $codebench->run(); + } + } +} diff --git a/includes/kohana/modules/codebench/classes/kohana/codebench.php b/includes/kohana/modules/codebench/classes/kohana/codebench.php new file mode 100644 index 0000000..68601bd --- /dev/null +++ b/includes/kohana/modules/codebench/classes/kohana/codebench.php @@ -0,0 +1,217 @@ + 'A', + 150 => 'B', + 200 => 'C', + 300 => 'D', + 500 => 'E', + 'default' => 'F', + ); + + /** + * Constructor. + * + * @return void + */ + public function __construct() + { + // Set the maximum execution time + set_time_limit(Kohana::config('codebench')->max_execution_time); + } + + /** + * Runs Codebench on the extending class. + * + * @return array benchmark output + */ + public function run() + { + // Array of all methods to loop over + $methods = array_filter(get_class_methods($this), array($this, '_method_filter')); + + // Make sure the benchmark runs at least once, + // also if no subject data has been provided. + if (empty($this->subjects)) + { + $this->subjects = array('NULL' => NULL); + } + + // Initialize benchmark output + $codebench = array + ( + 'class' => get_class($this), + 'description' => $this->description, + 'loops' => array + ( + 'base' => (int) $this->loops, + 'total' => (int) $this->loops * count($this->subjects) * count($methods), + ), + 'subjects' => $this->subjects, + 'benchmarks' => array(), + ); + + // Benchmark each method + foreach ($methods as $method) + { + // Initialize benchmark output for this method + $codebench['benchmarks'][$method] = array('time' => 0, 'memory' => 0); + + // Using Reflection because simply calling $this->$method($subject) in the loop below + // results in buggy benchmark times correlating to the length of the method name. + $reflection = new ReflectionMethod(get_class($this), $method); + + // Benchmark each subject on each method + foreach ($this->subjects as $subject_key => $subject) + { + // Prerun each method/subject combo before the actual benchmark loop. + // This way relatively expensive initial processes won't be benchmarked, e.g. autoloading. + // At the same time we capture the return here so we don't have to do that in the loop anymore. + $return = $reflection->invoke($this, $subject); + + // Start the timer for one subject + $token = Profiler::start('codebench', $method.$subject_key); + + // The heavy work + for ($i = 0; $i < $this->loops; ++$i) + { + $reflection->invoke($this, $subject); + } + + // Stop and read the timer + $benchmark = Profiler::total($token); + + // Benchmark output specific to the current method and subject + $codebench['benchmarks'][$method]['subjects'][$subject_key] = array + ( + 'return' => $return, + 'time' => $benchmark[0], + 'memory' => $benchmark[1], + ); + + // Update method totals + $codebench['benchmarks'][$method]['time'] += $benchmark[0]; + $codebench['benchmarks'][$method]['memory'] += $benchmark[1]; + } + } + + // Initialize the fastest and slowest benchmarks for both methods and subjects, time and memory, + // these values will be overwritten using min() and max() later on. + // The 999999999 values look like a hack, I know, but they work, + // unless your method runs for more than 31 years or consumes over 1GB of memory. + $fastest_method = $fastest_subject = array('time' => 999999999, 'memory' => 999999999); + $slowest_method = $slowest_subject = array('time' => 0, 'memory' => 0); + + // Find the fastest and slowest benchmarks, needed for the percentage calculations + foreach ($methods as $method) + { + // Update the fastest and slowest method benchmarks + $fastest_method['time'] = min($fastest_method['time'], $codebench['benchmarks'][$method]['time']); + $fastest_method['memory'] = min($fastest_method['memory'], $codebench['benchmarks'][$method]['memory']); + $slowest_method['time'] = max($slowest_method['time'], $codebench['benchmarks'][$method]['time']); + $slowest_method['memory'] = max($slowest_method['memory'], $codebench['benchmarks'][$method]['memory']); + + foreach ($this->subjects as $subject_key => $subject) + { + // Update the fastest and slowest subject benchmarks + $fastest_subject['time'] = min($fastest_subject['time'], $codebench['benchmarks'][$method]['subjects'][$subject_key]['time']); + $fastest_subject['memory'] = min($fastest_subject['memory'], $codebench['benchmarks'][$method]['subjects'][$subject_key]['memory']); + $slowest_subject['time'] = max($slowest_subject['time'], $codebench['benchmarks'][$method]['subjects'][$subject_key]['time']); + $slowest_subject['memory'] = max($slowest_subject['memory'], $codebench['benchmarks'][$method]['subjects'][$subject_key]['memory']); + } + } + + // Percentage calculations for methods + foreach ($codebench['benchmarks'] as & $method) + { + // Calculate percentage difference relative to fastest and slowest methods + $method['percent']['fastest']['time'] = (empty($fastest_method['time'])) ? 0 : ($method['time'] / $fastest_method['time'] * 100); + $method['percent']['fastest']['memory'] = (empty($fastest_method['memory'])) ? 0 : ($method['memory'] / $fastest_method['memory'] * 100); + $method['percent']['slowest']['time'] = (empty($slowest_method['time'])) ? 0 : ($method['time'] / $slowest_method['time'] * 100); + $method['percent']['slowest']['memory'] = (empty($slowest_method['memory'])) ? 0 : ($method['memory'] / $slowest_method['memory'] * 100); + + // Assign a grade for time and memory to each method + $method['grade']['time'] = $this->_grade($method['percent']['fastest']['time']); + $method['grade']['memory'] = $this->_grade($method['percent']['fastest']['memory']); + + // Percentage calculations for subjects + foreach ($method['subjects'] as & $subject) + { + // Calculate percentage difference relative to fastest and slowest subjects for this method + $subject['percent']['fastest']['time'] = (empty($fastest_subject['time'])) ? 0 : ($subject['time'] / $fastest_subject['time'] * 100); + $subject['percent']['fastest']['memory'] = (empty($fastest_subject['memory'])) ? 0 : ($subject['memory'] / $fastest_subject['memory'] * 100); + $subject['percent']['slowest']['time'] = (empty($slowest_subject['time'])) ? 0 : ($subject['time'] / $slowest_subject['time'] * 100); + $subject['percent']['slowest']['memory'] = (empty($slowest_subject['memory'])) ? 0 : ($subject['memory'] / $slowest_subject['memory'] * 100); + + // Assign a grade letter for time and memory to each subject + $subject['grade']['time'] = $this->_grade($subject['percent']['fastest']['time']); + $subject['grade']['memory'] = $this->_grade($subject['percent']['fastest']['memory']); + } + } + + return $codebench; + } + + /** + * Callback for array_filter(). + * Filters out all methods not to benchmark. + * + * @param string method name + * @return boolean + */ + protected function _method_filter($method) + { + // Only benchmark methods with the "bench" prefix + return (substr($method, 0, 5) === 'bench'); + } + + /** + * Returns the applicable grade letter for a score. + * + * @param integer|double score + * @return string grade letter + */ + protected function _grade($score) + { + foreach ($this->grades as $max => $grade) + { + if ($max === 'default') + continue; + + if ($score <= $max) + return $grade; + } + + return $this->grades['default']; + } +} diff --git a/includes/kohana/modules/codebench/config/codebench.php b/includes/kohana/modules/codebench/config/codebench.php new file mode 100644 index 0000000..590186d --- /dev/null +++ b/includes/kohana/modules/codebench/config/codebench.php @@ -0,0 +1,16 @@ + 0, + + /** + * Expand all benchmark details by default. + */ + 'expand_all' => FALSE, + +); diff --git a/includes/kohana/modules/codebench/config/userguide.php b/includes/kohana/modules/codebench/config/userguide.php new file mode 100644 index 0000000..f9e6a14 --- /dev/null +++ b/includes/kohana/modules/codebench/config/userguide.php @@ -0,0 +1,23 @@ + array( + + // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' + 'codebench' => array( + + // Whether this modules userguide pages should be shown + 'enabled' => TRUE, + + // The name that should show up on the userguide index page + 'name' => 'Codebench', + + // A short description of this module, shown on the index page + 'description' => 'Code benchmarking tool.', + + // Copyright message, shown in the footer for this module + 'copyright' => '© 2008–2010 Kohana Team', + ) + ) +); \ No newline at end of file diff --git a/includes/kohana/modules/codebench/guide/codebench/index.md b/includes/kohana/modules/codebench/guide/codebench/index.md new file mode 100644 index 0000000..78b6f21 --- /dev/null +++ b/includes/kohana/modules/codebench/guide/codebench/index.md @@ -0,0 +1,76 @@ +# Using Codebench + +[!!] The contents of this page are taken (with some minor changes) from and are copyright Geert De Deckere. + +For a long time I have been using a quick-and-dirty `benchmark.php` file to optimize bits of PHP code, many times regex-related stuff. The file contained not much more than a [gettimeofday](http://php.net/gettimeofday) function wrapped around a `for` loop. It worked, albeit not very efficiently. Something more solid was needed. I set out to create a far more usable piece of software to aid in the everlasting quest to squeeze every millisecond out of those regular expressions. + +## Codebench Goals + +### Benchmark multiple regular expressions at once + +Being able to compare the speed of an arbitrary amount of regular expressions would be tremendously useful. In case you are wondering—yes, I had been writing down benchmark times for each regex, uncommenting them one by one. You get the idea. Those days should be gone forever now. + +### Benchmark multiple subjects at once + +What gets overlooked too often when testing and optimizing regular expressions is the fact that speed can vastly differ depending on the subjects, also known as input or target strings. Just because your regular expression matches, say, a valid email address quickly, does not necessarily mean it will quickly realize when an invalid email is provided. I plan to write a follow-up article with hands-on regex examples to demonstrate this point. Anyway, Codebench allows you to create an array of subjects which will be passed to each benchmark. + +### Make it flexible enough to work for all PCRE functions + +Initially I named the module “Regexbench”. I quickly realized, though, it would be flexible enough to benchmark all kinds of PHP code, hence the change to “Codebench”. While tools specifically built to help profiling PCRE functions, like [preg_match](http://php.net/preg_match) or [preg_replace](http://php.net/preg_replace), definitely have their use, more flexibility was needed here. You should be able to compare all kinds of constructions like combinations of PCRE functions and native PHP string functions. + +### Create clean and portable benchmark cases + +Throwing valuable benchmark data away every time I needed to optimize another regular expression had to stop. A clean file containing the complete set of all regex variations to compare, together with the set of subjects to test them against, would be more than welcome. Moreover, it would be easy to exchange benchmark cases with others. + +### Visualize the benchmarks + +Obviously providing a visual representation of the benchmark results, via simple graphs, would make interpreting them easier. Having not to think about Internet Explorer for once, made writing CSS a whole lot more easy and fun. It resulted in some fine graphs which are fully resizable. + +Below are two screenshots of Codebench in action. `Valid_Color` is a class made for benchmarking different ways to validate hexadecimal HTML color values, e.g. `#FFF`. If you are interested in the story behind the actual regular expressions, take a look at [this topic in the Kohana forums](http://forum.kohanaphp.com/comments.php?DiscussionID=2192). + +![Benchmarking several ways to validate HTML color values](codebench_screenshot1.png) +**Benchmarking seven ways to validate HTML color values** + +![Collapsable results per subject for each method](codebench_screenshot2.png) +**Collapsable results per subject for each method** + +## Working with Codebench + +Codebench is included in Kohana 3, but if you need you [can download it](http://github.com/kohana/codebench/) from GitHub. Be sure Codebench is activated in your `application/bootstrap.php`. + +Creating your own benchmarks is just a matter of creating a class that extends the Codebench class. The class should go in `classes/bench` and the class name should have the `Bench_` prefix. Put the code parts you want to compare into separate methods. Be sure to prefix those methods with `bench_`, other methods will not be benchmarked. Glance at the files in `modules/codebench/classes/bench/` for more examples. + +Here is another short example with some extra explanations. + + // classes/bench/ltrimdigits.php + class Bench_LtrimDigits extends Codebench { + + // Some optional explanatory comments about the benchmark file. + // HTML allowed. URLs will be converted to links automatically. + public $description = 'Chopping off leading digits: regex vs ltrim.'; + + // How many times to execute each method per subject. + // Total loops = loops * number of methods * number of subjects + public $loops = 100000; + + // The subjects to supply iteratively to your benchmark methods. + public $subjects = array + ( + '123digits', + 'no-digits', + ); + + public function bench_regex($subject) + { + return preg_replace('/^\d+/', '', $subject); + } + + public function bench_ltrim($subject) + { + return ltrim($subject, '0..9'); + } + } + + + +And the winner is… [ltrim](http://php.net/ltrim). Happy benchmarking! \ No newline at end of file diff --git a/includes/kohana/modules/codebench/guide/codebench/menu.md b/includes/kohana/modules/codebench/guide/codebench/menu.md new file mode 100644 index 0000000..c73a19a --- /dev/null +++ b/includes/kohana/modules/codebench/guide/codebench/menu.md @@ -0,0 +1 @@ +## [Codebench]() \ No newline at end of file diff --git a/includes/kohana/modules/codebench/init.php b/includes/kohana/modules/codebench/init.php new file mode 100644 index 0000000..866cc34 --- /dev/null +++ b/includes/kohana/modules/codebench/init.php @@ -0,0 +1,8 @@ +)') + ->defaults(array( + 'controller' => 'codebench', + 'action' => 'index', + 'class' => NULL)); diff --git a/includes/kohana/modules/codebench/media/guide/codebench/codebench_screenshot1.png b/includes/kohana/modules/codebench/media/guide/codebench/codebench_screenshot1.png new file mode 100755 index 0000000000000000000000000000000000000000..d1cfcfb2cc4db8afe79465408be1c0587244b780 GIT binary patch literal 15827 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 X%k+Esjeze-6WmwTQ7Kn?68`@HDeN9w literal 0 HcmV?d00001 diff --git a/includes/kohana/modules/codebench/media/guide/codebench/codebench_screenshot2.png b/includes/kohana/modules/codebench/media/guide/codebench/codebench_screenshot2.png new file mode 100755 index 0000000000000000000000000000000000000000..85bf560bead5dd6042892a5a90f2d1212a7c8ee0 GIT binary patch literal 13575 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 literal 0 HcmV?d00001 diff --git a/includes/kohana/modules/codebench/views/codebench.php b/includes/kohana/modules/codebench/views/codebench.php new file mode 100644 index 0000000..1961950 --- /dev/null +++ b/includes/kohana/modules/codebench/views/codebench.php @@ -0,0 +1,258 @@ + + + + + + + + <?php if ($class !== '') echo $class, ' · ' ?>Codebench + + + + + + + + + + + +
+

+ + + + + Library not found + + No methods found to benchmark + + +

+
+ + + + + +

+ + Remember to prefix the methods you want to benchmark with “bench”.
+ You might also want to overwrite Codebench->method_filter(). +
+

+ + + +
    + $benchmark) { ?> +
  • + +

    + + + +% + +

    + +
    + + + + + + + + + + + + $subject) { ?> + + + + + + + + +
    Benchmarks per subject for
    subject → returns
    + + [] → + + () + + + + + + + + + + + s + + +
    +
    + +
  • + +
+ + + + + + + + Raw output:', Kohana::debug($codebench) ?> + + + + + + + \ No newline at end of file diff --git a/includes/kohana/modules/database/classes/database.php b/includes/kohana/modules/database/classes/database.php new file mode 100644 index 0000000..810f9ed --- /dev/null +++ b/includes/kohana/modules/database/classes/database.php @@ -0,0 +1,3 @@ +_database_instance = $config['instance']; + } + + if (isset($config['table'])) + { + $this->_database_table = $config['table']; + } + + parent::__construct(); + } + + /** + * Query the configuration table for all values for this group and + * unserialize each of the values. + * + * @param string group name + * @param array configuration array + * @return $this clone of the current object + */ + public function load($group, array $config = NULL) + { + if ($config === NULL AND $group !== 'database') + { + // Load all of the configuration values for this group + $query = DB::select('config_key', 'config_value') + ->from($this->_database_table) + ->where('group_name', '=', $group) + ->execute($this->_database_instance); + + if (count($query) > 0) + { + // Unserialize the configuration values + $config = array_map('unserialize', $query->as_array('config_key', 'config_value')); + } + } + + return parent::load($group, $config); + } + + /** + * Overload setting offsets to insert or update the database values as + * changes occur. + * + * @param string array key + * @param mixed new value + * @return mixed + */ + public function offsetSet($key, $value) + { + if ( ! $this->offsetExists($key)) + { + // Insert a new value + DB::insert($this->_database_table, array('group_name', 'config_key', 'config_value')) + ->values(array($this->_configuration_group, $key, serialize($value))) + ->execute($this->_database_instance); + } + elseif ($this->offsetGet($key) !== $value) + { + // Update the value + DB::update($this->_database_table) + ->value('config_value', serialize($value)) + ->where('group_name', '=', $this->_configuration_group) + ->where('config_key', '=', $key) + ->execute($this->_database_instance); + } + + return parent::offsetSet($key, $value); + } + +} // End Kohana_Config_Database diff --git a/includes/kohana/modules/database/classes/kohana/database.php b/includes/kohana/modules/database/classes/kohana/database.php new file mode 100644 index 0000000..558ff0c --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database.php @@ -0,0 +1,600 @@ +$name; + } + + if ( ! isset($config['type'])) + { + throw new Kohana_Exception('Database type not defined in :name configuration', + array(':name' => $name)); + } + + // Set the driver class name + $driver = 'Database_'.ucfirst($config['type']); + + // Create the database connection instance + new $driver($name, $config); + } + + return Database::$instances[$name]; + } + + /** + * @var string the last query executed + */ + public $last_query; + + // Character that is used to quote identifiers + protected $_identifier = '"'; + + // Instance name + protected $_instance; + + // Raw server connection + protected $_connection; + + // Configuration array + protected $_config; + + /** + * Stores the database configuration locally and name the instance. + * + * [!!] This method cannot be accessed directly, you must use [Database::instance]. + * + * @return void + */ + protected function __construct($name, array $config) + { + // Set the instance name + $this->_instance = $name; + + // Store the config locally + $this->_config = $config; + + // Store the database instance + Database::$instances[$name] = $this; + } + + /** + * Disconnect from the database when the object is destroyed. + * + * // Destroy the database instance + * unset(Database::instances[(string) $db], $db); + * + * [!!] Calling `unset($db)` is not enough to destroy the database, as it + * will still be stored in `Database::$instances`. + * + * @return void + */ + final public function __destruct() + { + $this->disconnect(); + } + + /** + * Returns the database instance name. + * + * echo (string) $db; + * + * @return string + */ + final public function __toString() + { + return $this->_instance; + } + + /** + * Connect to the database. This is called automatically when the first + * query is executed. + * + * $db->connect(); + * + * @throws Database_Exception + * @return void + */ + abstract public function connect(); + + /** + * Disconnect from the database. This is called automatically by [Database::__destruct]. + * + * $db->disconnect(); + * + * @return boolean + */ + abstract public function disconnect(); + + /** + * Set the connection character set. This is called automatically by [Database::connect]. + * + * $db->set_charset('utf8'); + * + * @throws Database_Exception + * @param string character set name + * @return void + */ + abstract public function set_charset($charset); + + /** + * Perform an SQL query of the given type. + * + * // Make a SELECT query and use objects for results + * $db->query(Database::SELECT, 'SELECT * FROM groups', TRUE); + * + * // Make a SELECT query and use "Model_User" for the results + * $db->query(Database::SELECT, 'SELECT * FROM users LIMIT 1', 'Model_User'); + * + * @param integer Database::SELECT, Database::INSERT, etc + * @param string SQL query + * @param mixed result object class string, TRUE for stdClass, FALSE for assoc array + * @param array object construct parameters for result class + * @return object Database_Result for SELECT queries + * @return array list (insert id, row count) for INSERT queries + * @return integer number of affected rows for all other queries + */ + abstract public function query($type, $sql, $as_object = FALSE, array $params = NULL); + + /** + * Count the number of records in the last query, without LIMIT or OFFSET applied. + * + * // Get the total number of records that match the last query + * $count = $db->count_last_query(); + * + * @deprecated since v3.0.9 + * @return integer + */ + public function count_last_query() + { + if ($sql = $this->last_query) + { + $sql = trim($sql); + if (stripos($sql, 'SELECT') !== 0) + { + return FALSE; + } + + if (stripos($sql, 'LIMIT') !== FALSE) + { + // Remove LIMIT from the SQL + $sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql); + } + + if (stripos($sql, 'OFFSET') !== FALSE) + { + // Remove OFFSET from the SQL + $sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql); + } + + // Get the total rows from the last query executed + $result = $this->query + ( + Database::SELECT, + 'SELECT COUNT(*) AS '.$this->quote_identifier('total_rows').' ' + .'FROM ('.$sql.') AS '.$this->quote_table('counted_results'), + TRUE + ); + + // Return the total number of rows from the query + return (int) $result->current()->total_rows; + } + + return FALSE; + } + + /** + * Count the number of records in a table. + * + * // Get the total number of records in the "users" table + * $count = $db->count_records('users'); + * + * @param mixed table name string or array(query, alias) + * @return integer + */ + public function count_records($table) + { + // Quote the table name + $table = $this->quote_identifier($table); + + return $this->query(Database::SELECT, 'SELECT COUNT(*) AS total_row_count FROM '.$table, FALSE) + ->get('total_row_count'); + } + + /** + * Returns a normalized array describing the SQL data type + * + * $db->datatype('char'); + * + * @param string SQL data type + * @return array + */ + public function datatype($type) + { + static $types = array + ( + // SQL-92 + 'bit' => array('type' => 'string', 'exact' => TRUE), + 'bit varying' => array('type' => 'string'), + 'char' => array('type' => 'string', 'exact' => TRUE), + 'char varying' => array('type' => 'string'), + 'character' => array('type' => 'string', 'exact' => TRUE), + 'character varying' => array('type' => 'string'), + 'date' => array('type' => 'string'), + 'dec' => array('type' => 'float', 'exact' => TRUE), + 'decimal' => array('type' => 'float', 'exact' => TRUE), + 'double precision' => array('type' => 'float'), + 'float' => array('type' => 'float'), + 'int' => array('type' => 'int', 'min' => '-2147483648', 'max' => '2147483647'), + 'integer' => array('type' => 'int', 'min' => '-2147483648', 'max' => '2147483647'), + 'interval' => array('type' => 'string'), + 'national char' => array('type' => 'string', 'exact' => TRUE), + 'national char varying' => array('type' => 'string'), + 'national character' => array('type' => 'string', 'exact' => TRUE), + 'national character varying' => array('type' => 'string'), + 'nchar' => array('type' => 'string', 'exact' => TRUE), + 'nchar varying' => array('type' => 'string'), + 'numeric' => array('type' => 'float', 'exact' => TRUE), + 'real' => array('type' => 'float'), + 'smallint' => array('type' => 'int', 'min' => '-32768', 'max' => '32767'), + 'time' => array('type' => 'string'), + 'time with time zone' => array('type' => 'string'), + 'timestamp' => array('type' => 'string'), + 'timestamp with time zone' => array('type' => 'string'), + 'varchar' => array('type' => 'string'), + + // SQL:1999 + 'binary large object' => array('type' => 'string', 'binary' => TRUE), + 'blob' => array('type' => 'string', 'binary' => TRUE), + 'boolean' => array('type' => 'bool'), + 'char large object' => array('type' => 'string'), + 'character large object' => array('type' => 'string'), + 'clob' => array('type' => 'string'), + 'national character large object' => array('type' => 'string'), + 'nchar large object' => array('type' => 'string'), + 'nclob' => array('type' => 'string'), + 'time without time zone' => array('type' => 'string'), + 'timestamp without time zone' => array('type' => 'string'), + + // SQL:2003 + 'bigint' => array('type' => 'int', 'min' => '-9223372036854775808', 'max' => '9223372036854775807'), + + // SQL:2008 + 'binary' => array('type' => 'string', 'binary' => TRUE, 'exact' => TRUE), + 'binary varying' => array('type' => 'string', 'binary' => TRUE), + 'varbinary' => array('type' => 'string', 'binary' => TRUE), + ); + + if (isset($types[$type])) + return $types[$type]; + + return array(); + } + + /** + * List all of the tables in the database. Optionally, a LIKE string can + * be used to search for specific tables. + * + * // Get all tables in the current database + * $tables = $db->list_tables(); + * + * // Get all user-related tables + * $tables = $db->list_tables('user%'); + * + * @param string table to search for + * @return array + */ + abstract public function list_tables($like = NULL); + + /** + * Lists all of the columns in a table. Optionally, a LIKE string can be + * used to search for specific fields. + * + * // Get all columns from the "users" table + * $columns = $db->list_columns('users'); + * + * // Get all name-related columns + * $columns = $db->list_columns('users', '%name%'); + * + * // Get the columns from a table that doesn't use the table prefix + * $columns = $db->list_columns('users', NULL, FALSE); + * + * @param string table to get columns from + * @param string column to search for + * @param boolean whether to add the table prefix automatically or not + * @return array + */ + abstract public function list_columns($table, $like = NULL, $add_prefix = TRUE); + + /** + * Extracts the text between parentheses, if any. + * + * // Returns: array('CHAR', '6') + * list($type, $length) = $db->_parse_type('CHAR(6)'); + * + * @param string + * @return array list containing the type and length, if any + */ + protected function _parse_type($type) + { + if (($open = strpos($type, '(')) === FALSE) + { + // No length specified + return array($type, NULL); + } + + // Closing parenthesis + $close = strpos($type, ')', $open); + + // Length without parentheses + $length = substr($type, $open + 1, $close - 1 - $open); + + // Type without the length + $type = substr($type, 0, $open).substr($type, $close + 1); + + return array($type, $length); + } + + /** + * Return the table prefix defined in the current configuration. + * + * $prefix = $db->table_prefix(); + * + * @return string + */ + public function table_prefix() + { + return $this->_config['table_prefix']; + } + + /** + * Quote a value for an SQL query. + * + * $db->quote(NULL); // 'NULL' + * $db->quote(10); // 10 + * $db->quote('fred'); // 'fred' + * + * Objects passed to this function will be converted to strings. + * [Database_Expression] objects will use the value of the expression. + * [Database_Query] objects will be compiled and converted to a sub-query. + * All other objects will be converted using the `__toString` method. + * + * @param mixed any value to quote + * @return string + * @uses Database::escape + */ + public function quote($value) + { + if ($value === NULL) + { + return 'NULL'; + } + elseif ($value === TRUE) + { + return "'1'"; + } + elseif ($value === FALSE) + { + return "'0'"; + } + elseif (is_object($value)) + { + if ($value instanceof Database_Query) + { + // Create a sub-query + return '('.$value->compile($this).')'; + } + elseif ($value instanceof Database_Expression) + { + // Use a raw expression + return $value->value(); + } + else + { + // Convert the object to a string + return $this->quote( (string) $value); + } + } + elseif (is_array($value)) + { + return '('.implode(', ', array_map(array($this, __FUNCTION__), $value)).')'; + } + elseif (is_int($value)) + { + return (int) $value; + } + elseif (is_float($value)) + { + // Convert to non-locale aware float to prevent possible commas + return sprintf('%F', $value); + } + + return $this->escape($value); + } + + /** + * Quote a database table name and adds the table prefix if needed. + * + * $table = $db->quote_table($table); + * + * @param mixed table name or array(table, alias) + * @return string + * @uses Database::quote_identifier + * @uses Database::table_prefix + */ + public function quote_table($value) + { + // Assign the table by reference from the value + if (is_array($value)) + { + $table =& $value[0]; + + // Attach table prefix to alias + $value[1] = $this->table_prefix().$value[1]; + } + else + { + $table =& $value; + } + + if (is_string($table) AND strpos($table, '.') === FALSE) + { + // Add the table prefix for tables + $table = $this->table_prefix().$table; + } + + return $this->quote_identifier($value); + } + + /** + * Quote a database identifier, such as a column name. Adds the + * table prefix to the identifier if a table name is present. + * + * $column = $db->quote_identifier($column); + * + * You can also use SQL methods within identifiers. + * + * // The value of "column" will be quoted + * $column = $db->quote_identifier('COUNT("column")'); + * + * Objects passed to this function will be converted to strings. + * [Database_Expression] objects will use the value of the expression. + * [Database_Query] objects will be compiled and converted to a sub-query. + * All other objects will be converted using the `__toString` method. + * + * @param mixed any identifier + * @return string + * @uses Database::table_prefix + */ + public function quote_identifier($value) + { + if ($value === '*') + { + return $value; + } + elseif (is_object($value)) + { + if ($value instanceof Database_Query) + { + // Create a sub-query + return '('.$value->compile($this).')'; + } + elseif ($value instanceof Database_Expression) + { + // Use a raw expression + return $value->value(); + } + else + { + // Convert the object to a string + return $this->quote_identifier( (string) $value); + } + } + elseif (is_array($value)) + { + // Separate the column and alias + list ($value, $alias) = $value; + + return $this->quote_identifier($value).' AS '.$this->quote_identifier($alias); + } + + if (strpos($value, '"') !== FALSE) + { + // Quote the column in FUNC("ident") identifiers + return preg_replace('/"(.+?)"/e', '$this->quote_identifier("$1")', $value); + } + elseif (strpos($value, '.') !== FALSE) + { + // Split the identifier into the individual parts + $parts = explode('.', $value); + + if ($prefix = $this->table_prefix()) + { + // Get the offset of the table name, 2nd-to-last part + // This works for databases that can have 3 identifiers (Postgre) + $offset = count($parts) - 2; + + // Add the table prefix to the table name + $parts[$offset] = $prefix.$parts[$offset]; + } + + // Quote each of the parts + return implode('.', array_map(array($this, __FUNCTION__), $parts)); + } + else + { + return $this->_identifier.$value.$this->_identifier; + } + } + + /** + * Sanitize a string by escaping characters that could cause an SQL + * injection attack. + * + * $value = $db->escape('any string'); + * + * @param string value to quote + * @return string + */ + abstract public function escape($value); + +} // End Database_Connection diff --git a/includes/kohana/modules/database/classes/kohana/database/exception.php b/includes/kohana/modules/database/classes/kohana/database/exception.php new file mode 100644 index 0000000..ea2630e --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/exception.php @@ -0,0 +1,11 @@ +_value = $value; + } + + /** + * Get the expression value as a string. + * + * $sql = $expression->value(); + * + * @return string + */ + public function value() + { + return (string) $this->_value; + } + + /** + * Return the value of the expression as a string. + * + * echo $expression; + * + * @return string + * @uses Database_Expression::value + */ + public function __toString() + { + return $this->value(); + } + +} // End Database_Expression diff --git a/includes/kohana/modules/database/classes/kohana/database/mysql.php b/includes/kohana/modules/database/classes/kohana/database/mysql.php new file mode 100644 index 0000000..67224a4 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/mysql.php @@ -0,0 +1,379 @@ +_connection) + return; + + if (Database_MySQL::$_set_names === NULL) + { + // Determine if we can use mysql_set_charset(), which is only + // available on PHP 5.2.3+ when compiled against MySQL 5.0+ + Database_MySQL::$_set_names = ! function_exists('mysql_set_charset'); + } + + // Extract the connection parameters, adding required variabels + extract($this->_config['connection'] + array( + 'database' => '', + 'hostname' => '', + 'username' => '', + 'password' => '', + 'persistent' => FALSE, + )); + + // Prevent this information from showing up in traces + unset($this->_config['connection']['username'], $this->_config['connection']['password']); + + try + { + if ($persistent) + { + // Create a persistent connection + $this->_connection = mysql_pconnect($hostname, $username, $password); + } + else + { + // Create a connection and force it to be a new link + $this->_connection = mysql_connect($hostname, $username, $password, TRUE); + } + } + catch (ErrorException $e) + { + // No connection exists + $this->_connection = NULL; + + throw new Database_Exception(':error', array( + ':error' => mysql_error(), + ), + mysql_errno()); + } + + // \xFF is a better delimiter, but the PHP driver uses underscore + $this->_connection_id = sha1($hostname.'_'.$username.'_'.$password); + + $this->_select_db($database); + + if ( ! empty($this->_config['charset'])) + { + // Set the character set + $this->set_charset($this->_config['charset']); + } + } + + /** + * Select the database + * + * @param string Database + * @return void + */ + protected function _select_db($database) + { + if ( ! mysql_select_db($database, $this->_connection)) + { + // Unable to select database + throw new Database_Exception(':error', + array(':error' => mysql_error($this->_connection)), + mysql_errno($this->_connection)); + } + + Database_MySQL::$_current_databases[$this->_connection_id] = $database; + } + + public function disconnect() + { + try + { + // Database is assumed disconnected + $status = TRUE; + + if (is_resource($this->_connection)) + { + if ($status = mysql_close($this->_connection)) + { + // Clear the connection + $this->_connection = NULL; + } + } + } + catch (Exception $e) + { + // Database is probably not disconnected + $status = ! is_resource($this->_connection); + } + + return $status; + } + + public function set_charset($charset) + { + // Make sure the database is connected + $this->_connection or $this->connect(); + + if (Database_MySQL::$_set_names === TRUE) + { + // PHP is compiled against MySQL 4.x + $status = (bool) mysql_query('SET NAMES '.$this->quote($charset), $this->_connection); + } + else + { + // PHP is compiled against MySQL 5.x + $status = mysql_set_charset($charset, $this->_connection); + } + + if ($status === FALSE) + { + throw new Database_Exception(':error', + array(':error' => mysql_error($this->_connection)), + mysql_errno($this->_connection)); + } + } + + public function query($type, $sql, $as_object = FALSE, array $params = NULL) + { + // Make sure the database is connected + $this->_connection or $this->connect(); + + if ( ! empty($this->_config['profiling'])) + { + // Benchmark this query for the current instance + $benchmark = Profiler::start("Database ({$this->_instance})", $sql); + } + + if ( ! empty($this->_config['connection']['persistent']) AND $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id]) + { + // Select database on persistent connections + $this->_select_db($this->_config['connection']['database']); + } + + // Execute the query + if (($result = mysql_query($sql, $this->_connection)) === FALSE) + { + if (isset($benchmark)) + { + // This benchmark is worthless + Profiler::delete($benchmark); + } + + throw new Database_Exception(':error [ :query ]', + array(':error' => mysql_error($this->_connection), ':query' => $sql), + mysql_errno($this->_connection)); + } + + if (isset($benchmark)) + { + Profiler::stop($benchmark); + } + + // Set the last query + $this->last_query = $sql; + + if ($type === Database::SELECT) + { + // Return an iterator of results + return new Database_MySQL_Result($result, $sql, $as_object, $params); + } + elseif ($type === Database::INSERT) + { + // Return a list of insert id and rows created + return array( + mysql_insert_id($this->_connection), + mysql_affected_rows($this->_connection), + ); + } + else + { + // Return the number of rows affected + return mysql_affected_rows($this->_connection); + } + } + + public function datatype($type) + { + static $types = array + ( + 'blob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '65535'), + 'bool' => array('type' => 'bool'), + 'bigint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '18446744073709551615'), + 'datetime' => array('type' => 'string'), + 'decimal unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'), + 'double' => array('type' => 'float'), + 'double precision unsigned' => array('type' => 'float', 'min' => '0'), + 'double unsigned' => array('type' => 'float', 'min' => '0'), + 'enum' => array('type' => 'string'), + 'fixed' => array('type' => 'float', 'exact' => TRUE), + 'fixed unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'), + 'float unsigned' => array('type' => 'float', 'min' => '0'), + 'int unsigned' => array('type' => 'int', 'min' => '0', 'max' => '4294967295'), + 'integer unsigned' => array('type' => 'int', 'min' => '0', 'max' => '4294967295'), + 'longblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '4294967295'), + 'longtext' => array('type' => 'string', 'character_maximum_length' => '4294967295'), + 'mediumblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '16777215'), + 'mediumint' => array('type' => 'int', 'min' => '-8388608', 'max' => '8388607'), + 'mediumint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '16777215'), + 'mediumtext' => array('type' => 'string', 'character_maximum_length' => '16777215'), + 'national varchar' => array('type' => 'string'), + 'numeric unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'), + 'nvarchar' => array('type' => 'string'), + 'point' => array('type' => 'string', 'binary' => TRUE), + 'real unsigned' => array('type' => 'float', 'min' => '0'), + 'set' => array('type' => 'string'), + 'smallint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '65535'), + 'text' => array('type' => 'string', 'character_maximum_length' => '65535'), + 'tinyblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '255'), + 'tinyint' => array('type' => 'int', 'min' => '-128', 'max' => '127'), + 'tinyint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '255'), + 'tinytext' => array('type' => 'string', 'character_maximum_length' => '255'), + 'year' => array('type' => 'string'), + ); + + $type = str_replace(' zerofill', '', $type); + + if (isset($types[$type])) + return $types[$type]; + + return parent::datatype($type); + } + + public function list_tables($like = NULL) + { + if (is_string($like)) + { + // Search for table names + $result = $this->query(Database::SELECT, 'SHOW TABLES LIKE '.$this->quote($like), FALSE); + } + else + { + // Find all table names + $result = $this->query(Database::SELECT, 'SHOW TABLES', FALSE); + } + + $tables = array(); + foreach ($result as $row) + { + $tables[] = reset($row); + } + + return $tables; + } + + public function list_columns($table, $like = NULL, $add_prefix = TRUE) + { + // Quote the table name + $table = ($add_prefix === TRUE) ? $this->quote_table($table) : $table; + + if (is_string($like)) + { + // Search for column names + $result = $this->query(Database::SELECT, 'SHOW FULL COLUMNS FROM '.$table.' LIKE '.$this->quote($like), FALSE); + } + else + { + // Find all column names + $result = $this->query(Database::SELECT, 'SHOW FULL COLUMNS FROM '.$table, FALSE); + } + + $count = 0; + $columns = array(); + foreach ($result as $row) + { + list($type, $length) = $this->_parse_type($row['Type']); + + $column = $this->datatype($type); + + $column['column_name'] = $row['Field']; + $column['column_default'] = $row['Default']; + $column['data_type'] = $type; + $column['is_nullable'] = ($row['Null'] == 'YES'); + $column['ordinal_position'] = ++$count; + + switch ($column['type']) + { + case 'float': + if (isset($length)) + { + list($column['numeric_precision'], $column['numeric_scale']) = explode(',', $length); + } + break; + case 'int': + if (isset($length)) + { + // MySQL attribute + $column['display'] = $length; + } + break; + case 'string': + switch ($column['data_type']) + { + case 'binary': + case 'varbinary': + $column['character_maximum_length'] = $length; + break; + case 'char': + case 'varchar': + $column['character_maximum_length'] = $length; + case 'text': + case 'tinytext': + case 'mediumtext': + case 'longtext': + $column['collation_name'] = $row['Collation']; + break; + case 'enum': + case 'set': + $column['collation_name'] = $row['Collation']; + $column['options'] = explode('\',\'', substr($length, 1, -1)); + break; + } + break; + } + + // MySQL attributes + $column['comment'] = $row['Comment']; + $column['extra'] = $row['Extra']; + $column['key'] = $row['Key']; + $column['privileges'] = $row['Privileges']; + + $columns[$row['Field']] = $column; + } + + return $columns; + } + + public function escape($value) + { + // Make sure the database is connected + $this->_connection or $this->connect(); + + if (($value = mysql_real_escape_string( (string) $value, $this->_connection)) === FALSE) + { + throw new Database_Exception(':error', + array(':error' => mysql_errno($this->_connection)), + mysql_error($this->_connection)); + } + + // SQL standard is to use single-quotes for all values + return "'$value'"; + } + +} // End Database_MySQL diff --git a/includes/kohana/modules/database/classes/kohana/database/mysql/result.php b/includes/kohana/modules/database/classes/kohana/database/mysql/result.php new file mode 100644 index 0000000..6a644e0 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/mysql/result.php @@ -0,0 +1,71 @@ +_total_rows = mysql_num_rows($result); + } + + public function __destruct() + { + if (is_resource($this->_result)) + { + mysql_free_result($this->_result); + } + } + + public function seek($offset) + { + if ($this->offsetExists($offset) AND mysql_data_seek($this->_result, $offset)) + { + // Set the current row to the offset + $this->_current_row = $this->_internal_row = $offset; + + return TRUE; + } + else + { + return FALSE; + } + } + + public function current() + { + if ($this->_current_row !== $this->_internal_row AND ! $this->seek($this->_current_row)) + return FALSE; + + // Increment internal row for optimization assuming rows are fetched in order + $this->_internal_row++; + + if ($this->_as_object === TRUE) + { + // Return an stdClass + return mysql_fetch_object($this->_result); + } + elseif (is_string($this->_as_object)) + { + // Return an object of given class name + return mysql_fetch_object($this->_result, $this->_as_object, $this->_object_params); + } + else + { + // Return an array of the row + return mysql_fetch_assoc($this->_result); + } + } + +} // End Database_MySQL_Result_Select diff --git a/includes/kohana/modules/database/classes/kohana/database/pdo.php b/includes/kohana/modules/database/classes/kohana/database/pdo.php new file mode 100644 index 0000000..b34e028 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/pdo.php @@ -0,0 +1,186 @@ +_config['identifier'])) + { + // Allow the identifier to be overloaded per-connection + $this->_identifier = (string) $this->_config['identifier']; + } + } + + public function connect() + { + if ($this->_connection) + return; + + // Extract the connection parameters, adding required variabels + extract($this->_config['connection'] + array( + 'dsn' => '', + 'username' => NULL, + 'password' => NULL, + 'persistent' => FALSE, + )); + + // Clear the connection parameters for security + unset($this->_config['connection']); + + // Force PDO to use exceptions for all errors + $attrs = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); + + if ( ! empty($persistent)) + { + // Make the connection persistent + $attrs[PDO::ATTR_PERSISTENT] = TRUE; + } + + try + { + // Create a new PDO connection + $this->_connection = new PDO($dsn, $username, $password, $attrs); + } + catch (PDOException $e) + { + throw new Database_Exception(':error', array( + ':error' => $e->getMessage(), + ), + $e->getCode(), + $e); + } + + if ( ! empty($this->_config['charset'])) + { + // Set the character set + $this->set_charset($this->_config['charset']); + } + } + + public function disconnect() + { + // Destroy the PDO object + $this->_connection = NULL; + + return TRUE; + } + + public function set_charset($charset) + { + // Make sure the database is connected + $this->_connection or $this->connect(); + + // Execute a raw SET NAMES query + $this->_connection->exec('SET NAMES '.$this->quote($charset)); + } + + public function query($type, $sql, $as_object = FALSE, array $params = NULL) + { + // Make sure the database is connected + $this->_connection or $this->connect(); + + if ( ! empty($this->_config['profiling'])) + { + // Benchmark this query for the current instance + $benchmark = Profiler::start("Database ({$this->_instance})", $sql); + } + + try + { + $result = $this->_connection->query($sql); + } + catch (Exception $e) + { + if (isset($benchmark)) + { + // This benchmark is worthless + Profiler::delete($benchmark); + } + + // Convert the exception in a database exception + throw new Database_Exception(':error [ :query ]', array( + ':error' => $e->getMessage(), + ':query' => $sql + ), + $e->getCode(), + $e); + } + + if (isset($benchmark)) + { + Profiler::stop($benchmark); + } + + // Set the last query + $this->last_query = $sql; + + if ($type === Database::SELECT) + { + // Convert the result into an array, as PDOStatement::rowCount is not reliable + if ($as_object === FALSE) + { + $result->setFetchMode(PDO::FETCH_ASSOC); + } + elseif (is_string($as_object)) + { + $result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params); + } + else + { + $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass'); + } + + $result = $result->fetchAll(); + + // Return an iterator of results + return new Database_Result_Cached($result, $sql, $as_object, $params); + } + elseif ($type === Database::INSERT) + { + // Return a list of insert id and rows created + return array( + $this->_connection->lastInsertId(), + $result->rowCount(), + ); + } + else + { + // Return the number of rows affected + return $result->rowCount(); + } + } + + public function list_tables($like = NULL) + { + throw new Kohana_Exception('Database method :method is not supported by :class', + array(':method' => __FUNCTION__, ':class' => __CLASS__)); + } + + public function list_columns($table, $like = NULL, $add_prefix = TRUE) + { + throw new Kohana_Exception('Database method :method is not supported by :class', + array(':method' => __FUNCTION__, ':class' => __CLASS__)); + } + + public function escape($value) + { + // Make sure the database is connected + $this->_connection or $this->connect(); + + return $this->_connection->quote($value); + } + +} // End Database_PDO diff --git a/includes/kohana/modules/database/classes/kohana/database/query.php b/includes/kohana/modules/database/classes/kohana/database/query.php new file mode 100644 index 0000000..3567b15 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query.php @@ -0,0 +1,236 @@ +_type = $type; + $this->_sql = $sql; + } + + /** + * Return the SQL query string. + * + * @return string + */ + final public function __toString() + { + try + { + // Return the SQL string + return $this->compile(Database::instance()); + } + catch (Exception $e) + { + return Kohana::exception_text($e); + } + } + + /** + * Get the type of the query. + * + * @return integer + */ + public function type() + { + return $this->_type; + } + + /** + * Enables the query to be cached for a specified amount of time. + * + * @param integer number of seconds to cache or null for default + * @return $this + * @uses Kohana::$cache_life + */ + public function cached($lifetime = NULL) + { + if ($lifetime === NULL) + { + // Use the global setting + $lifetime = Kohana::$cache_life; + } + + $this->_lifetime = $lifetime; + + return $this; + } + + /** + * Returns results as associative arrays + * + * @return $this + */ + public function as_assoc() + { + $this->_as_object = FALSE; + + $this->_object_params = array(); + + return $this; + } + + /** + * Returns results as objects + * + * @param string classname or TRUE for stdClass + * @return $this + */ + public function as_object($class = TRUE, array $params = NULL) + { + $this->_as_object = $class; + + if ($params) + { + // Add object parameters + $this->_object_params = $params; + } + + return $this; + } + + /** + * Set the value of a parameter in the query. + * + * @param string parameter key to replace + * @param mixed value to use + * @return $this + */ + public function param($param, $value) + { + // Add or overload a new parameter + $this->_parameters[$param] = $value; + + return $this; + } + + /** + * Bind a variable to a parameter in the query. + * + * @param string parameter key to replace + * @param mixed variable to use + * @return $this + */ + public function bind($param, & $var) + { + // Bind a value to a variable + $this->_parameters[$param] =& $var; + + return $this; + } + + /** + * Add multiple parameters to the query. + * + * @param array list of parameters + * @return $this + */ + public function parameters(array $params) + { + // Merge the new parameters in + $this->_parameters = $params + $this->_parameters; + + return $this; + } + + /** + * Compile the SQL query and return it. Replaces any parameters with their + * given values. + * + * @param object Database instance + * @return string + */ + public function compile(Database $db) + { + // Import the SQL locally + $sql = $this->_sql; + + if ( ! empty($this->_parameters)) + { + // Quote all of the values + $values = array_map(array($db, 'quote'), $this->_parameters); + + // Replace the values in the SQL + $sql = strtr($sql, $values); + } + + return $sql; + } + + /** + * Execute the current query on the given database. + * + * @param mixed Database instance or name of instance + * @return object Database_Result for SELECT queries + * @return mixed the insert id for INSERT queries + * @return integer number of affected rows for all other queries + */ + public function execute($db = NULL) + { + if ( ! is_object($db)) + { + // Get the database instance + $db = Database::instance($db); + } + + // Compile the SQL query + $sql = $this->compile($db); + + if ( ! empty($this->_lifetime) AND $this->_type === Database::SELECT) + { + // Set the cache key based on the database instance name and SQL + $cache_key = 'Database::query("'.$db.'", "'.$sql.'")'; + + if ($result = Kohana::cache($cache_key, NULL, $this->_lifetime)) + { + // Return a cached result + return new Database_Result_Cached($result, $sql, $this->_as_object, $this->_object_params); + } + } + + // Execute the query + $result = $db->query($this->_type, $sql, $this->_as_object, $this->_object_params); + + if (isset($cache_key)) + { + // Cache the result array + Kohana::cache($cache_key, $result->as_array(), $this->_lifetime); + } + + return $result; + } + +} // End Database_Query diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder.php b/includes/kohana/modules/database/classes/kohana/database/query/builder.php new file mode 100644 index 0000000..bcc4a1a --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder.php @@ -0,0 +1,211 @@ +compile($db); + } + + return implode(' ', $statements); + } + + /** + * Compiles an array of conditions into an SQL partial. Used for WHERE + * and HAVING. + * + * @param object Database instance + * @param array condition statements + * @return string + */ + protected function _compile_conditions(Database $db, array $conditions) + { + $last_condition = NULL; + + $sql = ''; + foreach ($conditions as $group) + { + // Process groups of conditions + foreach ($group as $logic => $condition) + { + if ($condition === '(') + { + if ( ! empty($sql) AND $last_condition !== '(') + { + // Include logic operator + $sql .= ' '.$logic.' '; + } + + $sql .= '('; + } + elseif ($condition === ')') + { + $sql .= ')'; + } + else + { + if ( ! empty($sql) AND $last_condition !== '(') + { + // Add the logic operator + $sql .= ' '.$logic.' '; + } + + // Split the condition + list($column, $op, $value) = $condition; + + if ($value === NULL) + { + if ($op === '=') + { + // Convert "val = NULL" to "val IS NULL" + $op = 'IS'; + } + elseif ($op === '!=') + { + // Convert "val != NULL" to "valu IS NOT NULL" + $op = 'IS NOT'; + } + } + + // Database operators are always uppercase + $op = strtoupper($op); + + if ($op === 'BETWEEN' AND is_array($value)) + { + // BETWEEN always has exactly two arguments + list($min, $max) = $value; + + if (is_string($min) AND array_key_exists($min, $this->_parameters)) + { + // Set the parameter as the minimum + $min = $this->_parameters[$min]; + } + + if (is_string($max) AND array_key_exists($max, $this->_parameters)) + { + // Set the parameter as the maximum + $max = $this->_parameters[$max]; + } + + // Quote the min and max value + $value = $db->quote($min).' AND '.$db->quote($max); + } + else + { + if (is_string($value) AND array_key_exists($value, $this->_parameters)) + { + // Set the parameter as the value + $value = $this->_parameters[$value]; + } + + // Quote the entire value normally + $value = $db->quote($value); + } + + if ($column) + { + // Apply proper quoting to the column + $column = $db->quote_identifier($column); + } + + // Append the statement to the query + $sql .= trim($column.' '.$op.' '.$value); + } + + $last_condition = $condition; + } + } + + return $sql; + } + + /** + * Compiles an array of set values into an SQL partial. Used for UPDATE. + * + * @param object Database instance + * @param array updated values + * @return string + */ + protected function _compile_set(Database $db, array $values) + { + $set = array(); + foreach ($values as $group) + { + // Split the set + list ($column, $value) = $group; + + // Quote the column name + $column = $db->quote_identifier($column); + + if (is_string($value) AND array_key_exists($value, $this->_parameters)) + { + // Use the parameter value + $value = $this->_parameters[$value]; + } + + $set[$column] = $column.' = '.$db->quote($value); + } + + return implode(', ', $set); + } + + /** + * Compiles an array of ORDER BY statements into an SQL partial. + * + * @param object Database instance + * @param array sorting columns + * @return string + */ + protected function _compile_order_by(Database $db, array $columns) + { + $sort = array(); + foreach ($columns as $group) + { + list ($column, $direction) = $group; + + if ($direction) + { + // Make the direction uppercase + $direction = strtoupper($direction); + } + + if ($column) + { + // Quote the column, if it has a value + $column = $db->quote_identifier($column); + } + + $sort[] = trim($column.' '.$direction); + } + + return 'ORDER BY '.implode(', ', $sort); + } + + /** + * Reset the current builder status. + * + * @return $this + */ + abstract public function reset(); + +} // End Database_Query_Builder diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder/delete.php b/includes/kohana/modules/database/classes/kohana/database/query/builder/delete.php new file mode 100644 index 0000000..f854536 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder/delete.php @@ -0,0 +1,89 @@ +_table = $table; + } + + // Start the query with no SQL + return parent::__construct(Database::DELETE, ''); + } + + /** + * Sets the table to delete from. + * + * @param mixed table name or array($table, $alias) or object + * @return $this + */ + public function table($table) + { + $this->_table = $table; + + return $this; + } + + /** + * Compile the SQL query and return it. + * + * @param object Database instance + * @return string + */ + public function compile(Database $db) + { + // Start a deletion query + $query = 'DELETE FROM '.$db->quote_table($this->_table); + + if ( ! empty($this->_where)) + { + // Add deletion conditions + $query .= ' WHERE '.$this->_compile_conditions($db, $this->_where); + } + + if ( ! empty($this->_order_by)) + { + // Add sorting + $query .= ' '.$this->_compile_order_by($db, $this->_order_by); + } + + if ($this->_limit !== NULL) + { + // Add limiting + $query .= ' LIMIT '.$this->_limit; + } + + return $query; + } + + public function reset() + { + $this->_table = NULL; + $this->_where = array(); + + $this->_parameters = array(); + + return $this; + } + +} // End Database_Query_Builder_Delete diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder/insert.php b/includes/kohana/modules/database/classes/kohana/database/query/builder/insert.php new file mode 100644 index 0000000..7302d43 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder/insert.php @@ -0,0 +1,171 @@ +_table = $table; + } + + if ($columns) + { + // Set the column names + $this->_columns = $columns; + } + + // Start the query with no SQL + return parent::__construct(Database::INSERT, ''); + } + + /** + * Sets the table to insert into. + * + * @param mixed table name or array($table, $alias) or object + * @return $this + */ + public function table($table) + { + $this->_table = $table; + + return $this; + } + + /** + * Set the columns that will be inserted. + * + * @param array column names + * @return $this + */ + public function columns(array $columns) + { + $this->_columns = $columns; + + return $this; + } + + /** + * Adds or overwrites values. Multiple value sets can be added. + * + * @param array values list + * @param ... + * @return $this + */ + public function values(array $values) + { + if ( ! is_array($this->_values)) + { + throw new Kohana_Exception('INSERT INTO ... SELECT statements cannot be combined with INSERT INTO ... VALUES'); + } + + // Get all of the passed values + $values = func_get_args(); + + $this->_values = array_merge($this->_values, $values); + + return $this; + } + + /** + * Use a sub-query to for the inserted values. + * + * @param object Database_Query of SELECT type + * @return $this + */ + public function select(Database_Query $query) + { + if ($query->type() !== Database::SELECT) + { + throw new Kohana_Exception('Only SELECT queries can be combined with INSERT queries'); + } + + $this->_values = $query; + + return $this; + } + + /** + * Compile the SQL query and return it. + * + * @param object Database instance + * @return string + */ + public function compile(Database $db) + { + // Start an insertion query + $query = 'INSERT INTO '.$db->quote_table($this->_table); + + // Add the column names + $query .= ' ('.implode(', ', array_map(array($db, 'quote_identifier'), $this->_columns)).') '; + + if (is_array($this->_values)) + { + // Callback for quoting values + $quote = array($db, 'quote'); + + $groups = array(); + foreach ($this->_values as $group) + { + foreach ($group as $i => $value) + { + if (is_string($value) AND isset($this->_parameters[$value])) + { + // Use the parameter value + $group[$i] = $this->_parameters[$value]; + } + } + + $groups[] = '('.implode(', ', array_map($quote, $group)).')'; + } + + // Add the values + $query .= 'VALUES '.implode(', ', $groups); + } + else + { + // Add the sub-query + $query .= (string) $this->_values; + } + + return $query; + } + + public function reset() + { + $this->_table = NULL; + + $this->_columns = + $this->_values = array(); + + $this->_parameters = array(); + + return $this; + } + +} // End Database_Query_Builder_Insert diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder/join.php b/includes/kohana/modules/database/classes/kohana/database/query/builder/join.php new file mode 100644 index 0000000..d87da44 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder/join.php @@ -0,0 +1,107 @@ +_table = $table; + + if ($type !== NULL) + { + // Set the JOIN type + $this->_type = (string) $type; + } + } + + /** + * Adds a new condition for joining. + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column name or array($column, $alias) or object + * @return $this + */ + public function on($c1, $op, $c2) + { + $this->_on[] = array($c1, $op, $c2); + + return $this; + } + + /** + * Compile the SQL partial for a JOIN statement and return it. + * + * @param object Database instance + * @return string + */ + public function compile(Database $db) + { + if ($this->_type) + { + $sql = strtoupper($this->_type).' JOIN'; + } + else + { + $sql = 'JOIN'; + } + + // Quote the table name that is being joined + $sql .= ' '.$db->quote_table($this->_table).' ON '; + + $conditions = array(); + foreach ($this->_on as $condition) + { + // Split the condition + list($c1, $op, $c2) = $condition; + + if ($op) + { + // Make the operator uppercase and spaced + $op = ' '.strtoupper($op); + } + + // Quote each of the identifiers used for the condition + $conditions[] = $db->quote_identifier($c1).$op.' '.$db->quote_identifier($c2); + } + + // Concat the conditions "... AND ..." + $sql .= '('.implode(' AND ', $conditions).')'; + + return $sql; + } + + public function reset() + { + $this->_type = + $this->_table = NULL; + + $this->_on = array(); + } + +} // End Database_Query_Builder_Join diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder/select.php b/includes/kohana/modules/database/classes/kohana/database/query/builder/select.php new file mode 100644 index 0000000..de7c8d3 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder/select.php @@ -0,0 +1,388 @@ +_select = $columns; + } + + // Start the query with no actual SQL statement + parent::__construct(Database::SELECT, ''); + } + + /** + * Enables or disables selecting only unique columns using "SELECT DISTINCT" + * + * @param boolean enable or disable distinct columns + * @return $this + */ + public function distinct($value) + { + $this->_distinct = (bool) $value; + + return $this; + } + + /** + * Choose the columns to select from. + * + * @param mixed column name or array($column, $alias) or object + * @param ... + * @return $this + */ + public function select($columns = NULL) + { + $columns = func_get_args(); + + $this->_select = array_merge($this->_select, $columns); + + return $this; + } + + /** + * Choose the columns to select from, using an array. + * + * @param array list of column names or aliases + * @return $this + */ + public function select_array(array $columns) + { + $this->_select = array_merge($this->_select, $columns); + + return $this; + } + + /** + * Choose the tables to select "FROM ..." + * + * @param mixed table name or array($table, $alias) or object + * @param ... + * @return $this + */ + public function from($tables) + { + $tables = func_get_args(); + + $this->_from = array_merge($this->_from, $tables); + + return $this; + } + + /** + * Adds addition tables to "JOIN ...". + * + * @param mixed column name or array($column, $alias) or object + * @param string join type (LEFT, RIGHT, INNER, etc) + * @return $this + */ + public function join($table, $type = NULL) + { + $this->_join[] = $this->_last_join = new Database_Query_Builder_Join($table, $type); + + return $this; + } + + /** + * Adds "ON ..." conditions for the last created JOIN statement. + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column name or array($column, $alias) or object + * @return $this + */ + public function on($c1, $op, $c2) + { + $this->_last_join->on($c1, $op, $c2); + + return $this; + } + + /** + * Creates a "GROUP BY ..." filter. + * + * @param mixed column name or array($column, $alias) or object + * @param ... + * @return $this + */ + public function group_by($columns) + { + $columns = func_get_args(); + + $this->_group_by = array_merge($this->_group_by, $columns); + + return $this; + } + + /** + * Alias of and_having() + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column value + * @return $this + */ + public function having($column, $op, $value = NULL) + { + return $this->and_having($column, $op, $value); + } + + /** + * Creates a new "AND HAVING" condition for the query. + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column value + * @return $this + */ + public function and_having($column, $op, $value = NULL) + { + $this->_having[] = array('AND' => array($column, $op, $value)); + + return $this; + } + + /** + * Creates a new "OR HAVING" condition for the query. + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column value + * @return $this + */ + public function or_having($column, $op, $value = NULL) + { + $this->_having[] = array('OR' => array($column, $op, $value)); + + return $this; + } + + /** + * Alias of and_having_open() + * + * @return $this + */ + public function having_open() + { + return $this->and_having_open(); + } + + /** + * Opens a new "AND HAVING (...)" grouping. + * + * @return $this + */ + public function and_having_open() + { + $this->_having[] = array('AND' => '('); + + return $this; + } + + /** + * Opens a new "OR HAVING (...)" grouping. + * + * @return $this + */ + public function or_having_open() + { + $this->_having[] = array('OR' => '('); + + return $this; + } + + /** + * Closes an open "AND HAVING (...)" grouping. + * + * @return $this + */ + public function having_close() + { + return $this->and_having_close(); + } + + /** + * Closes an open "AND HAVING (...)" grouping. + * + * @return $this + */ + public function and_having_close() + { + $this->_having[] = array('AND' => ')'); + + return $this; + } + + /** + * Closes an open "OR HAVING (...)" grouping. + * + * @return $this + */ + public function or_having_close() + { + $this->_having[] = array('OR' => ')'); + + return $this; + } + + /** + * Start returning results after "OFFSET ..." + * + * @param integer starting result number + * @return $this + */ + public function offset($number) + { + $this->_offset = (int) $number; + + return $this; + } + + /** + * Compile the SQL query and return it. + * + * @param object Database instance + * @return string + */ + public function compile(Database $db) + { + // Callback to quote identifiers + $quote_ident = array($db, 'quote_identifier'); + + // Callback to quote tables + $quote_table = array($db, 'quote_table'); + + // Start a selection query + $query = 'SELECT '; + + if ($this->_distinct === TRUE) + { + // Select only unique results + $query .= 'DISTINCT '; + } + + if (empty($this->_select)) + { + // Select all columns + $query .= '*'; + } + else + { + // Select all columns + $query .= implode(', ', array_unique(array_map($quote_ident, $this->_select))); + } + + if ( ! empty($this->_from)) + { + // Set tables to select from + $query .= ' FROM '.implode(', ', array_unique(array_map($quote_table, $this->_from))); + } + + if ( ! empty($this->_join)) + { + // Add tables to join + $query .= ' '.$this->_compile_join($db, $this->_join); + } + + if ( ! empty($this->_where)) + { + // Add selection conditions + $query .= ' WHERE '.$this->_compile_conditions($db, $this->_where); + } + + if ( ! empty($this->_group_by)) + { + // Add sorting + $query .= ' GROUP BY '.implode(', ', array_map($quote_ident, $this->_group_by)); + } + + if ( ! empty($this->_having)) + { + // Add filtering conditions + $query .= ' HAVING '.$this->_compile_conditions($db, $this->_having); + } + + if ( ! empty($this->_order_by)) + { + // Add sorting + $query .= ' '.$this->_compile_order_by($db, $this->_order_by); + } + + if ($this->_limit !== NULL) + { + // Add limiting + $query .= ' LIMIT '.$this->_limit; + } + + if ($this->_offset !== NULL) + { + // Add offsets + $query .= ' OFFSET '.$this->_offset; + } + + return $query; + } + + public function reset() + { + $this->_select = + $this->_from = + $this->_join = + $this->_where = + $this->_group_by = + $this->_having = + $this->_order_by = array(); + + $this->_distinct = FALSE; + + $this->_limit = + $this->_offset = + $this->_last_join = NULL; + + $this->_parameters = array(); + + return $this; + } + +} // End Database_Query_Select diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder/update.php b/includes/kohana/modules/database/classes/kohana/database/query/builder/update.php new file mode 100644 index 0000000..deedc9e --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder/update.php @@ -0,0 +1,130 @@ +_table = $table; + } + + // Start the query with no SQL + return parent::__construct(Database::UPDATE, ''); + } + + /** + * Sets the table to update. + * + * @param mixed table name or array($table, $alias) or object + * @return $this + */ + public function table($table) + { + $this->_table = $table; + + return $this; + } + + /** + * Set the values to update with an associative array. + * + * @param array associative (column => value) list + * @return $this + */ + public function set(array $pairs) + { + foreach ($pairs as $column => $value) + { + $this->_set[] = array($column, $value); + } + + return $this; + } + + /** + * Set the value of a single column. + * + * @param mixed table name or array($table, $alias) or object + * @param mixed column value + * @return $this + */ + public function value($column, $value) + { + $this->_set[] = array($column, $value); + + return $this; + } + + /** + * Compile the SQL query and return it. + * + * @param object Database instance + * @return string + */ + public function compile(Database $db) + { + // Start an update query + $query = 'UPDATE '.$db->quote_table($this->_table); + + // Add the columns to update + $query .= ' SET '.$this->_compile_set($db, $this->_set); + + if ( ! empty($this->_where)) + { + // Add selection conditions + $query .= ' WHERE '.$this->_compile_conditions($db, $this->_where); + } + + if ( ! empty($this->_order_by)) + { + // Add sorting + $query .= ' '.$this->_compile_order_by($db, $this->_order_by); + } + + if ($this->_limit !== NULL) + { + // Add limiting + $query .= ' LIMIT '.$this->_limit; + } + + return $query; + } + + public function reset() + { + $this->_table = NULL; + + $this->_set = + $this->_where = array(); + + $this->_limit = NULL; + + $this->_parameters = array(); + + return $this; + } + + +} // End Database_Query_Builder_Update diff --git a/includes/kohana/modules/database/classes/kohana/database/query/builder/where.php b/includes/kohana/modules/database/classes/kohana/database/query/builder/where.php new file mode 100644 index 0000000..aeece75 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/query/builder/where.php @@ -0,0 +1,160 @@ +and_where($column, $op, $value); + } + + /** + * Creates a new "AND WHERE" condition for the query. + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column value + * @return $this + */ + public function and_where($column, $op, $value) + { + $this->_where[] = array('AND' => array($column, $op, $value)); + + return $this; + } + + /** + * Creates a new "OR WHERE" condition for the query. + * + * @param mixed column name or array($column, $alias) or object + * @param string logic operator + * @param mixed column value + * @return $this + */ + public function or_where($column, $op, $value) + { + $this->_where[] = array('OR' => array($column, $op, $value)); + + return $this; + } + + /** + * Alias of and_where_open() + * + * @return $this + */ + public function where_open() + { + return $this->and_where_open(); + } + + /** + * Opens a new "AND WHERE (...)" grouping. + * + * @return $this + */ + public function and_where_open() + { + $this->_where[] = array('AND' => '('); + + return $this; + } + + /** + * Opens a new "OR WHERE (...)" grouping. + * + * @return $this + */ + public function or_where_open() + { + $this->_where[] = array('OR' => '('); + + return $this; + } + + /** + * Closes an open "AND WHERE (...)" grouping. + * + * @return $this + */ + public function where_close() + { + return $this->and_where_close(); + } + + /** + * Closes an open "AND WHERE (...)" grouping. + * + * @return $this + */ + public function and_where_close() + { + $this->_where[] = array('AND' => ')'); + + return $this; + } + + /** + * Closes an open "OR WHERE (...)" grouping. + * + * @return $this + */ + public function or_where_close() + { + $this->_where[] = array('OR' => ')'); + + return $this; + } + + /** + * Applies sorting with "ORDER BY ..." + * + * @param mixed column name or array($column, $alias) or object + * @param string direction of sorting + * @return $this + */ + public function order_by($column, $direction = NULL) + { + $this->_order_by[] = array($column, $direction); + + return $this; + } + + /** + * Return up to "LIMIT ..." results + * + * @param integer maximum results to return + * @return $this + */ + public function limit($number) + { + $this->_limit = (int) $number; + + return $this; + } + +} // End Database_Query_Builder_Where diff --git a/includes/kohana/modules/database/classes/kohana/database/result.php b/includes/kohana/modules/database/classes/kohana/database/result.php new file mode 100644 index 0000000..6ddd458 --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/result.php @@ -0,0 +1,331 @@ +_result = $result; + + // Store the SQL locally + $this->_query = $sql; + + if (is_object($as_object)) + { + // Get the object class name + $as_object = get_class($as_object); + } + + // Results as objects or associative arrays + $this->_as_object = $as_object; + + if ($params) + { + // Object constructor params + $this->_object_params = $params; + } + } + + /** + * Result destruction cleans up all open result sets. + * + * @return void + */ + abstract public function __destruct(); + + /** + * Get a cached database result from the current result iterator. + * + * $cachable = serialize($result->cached()); + * + * @return Database_Result_Cached + * @since 3.0.5 + */ + public function cached() + { + return new Database_Result_Cached($this->as_array(), $this->_query, $this->_as_object); + } + + /** + * Return all of the rows in the result as an array. + * + * // Indexed array of all rows + * $rows = $result->as_array(); + * + * // Associative array of rows by "id" + * $rows = $result->as_array('id'); + * + * // Associative array of rows, "id" => "name" + * $rows = $result->as_array('id', 'name'); + * + * @param string column for associative keys + * @param string column for values + * @return array + */ + public function as_array($key = NULL, $value = NULL) + { + $results = array(); + + if ($key === NULL AND $value === NULL) + { + // Indexed rows + + foreach ($this as $row) + { + $results[] = $row; + } + } + elseif ($key === NULL) + { + // Indexed columns + + if ($this->_as_object) + { + foreach ($this as $row) + { + $results[] = $row->$value; + } + } + else + { + foreach ($this as $row) + { + $results[] = $row[$value]; + } + } + } + elseif ($value === NULL) + { + // Associative rows + + if ($this->_as_object) + { + foreach ($this as $row) + { + $results[$row->$key] = $row; + } + } + else + { + foreach ($this as $row) + { + $results[$row[$key]] = $row; + } + } + } + else + { + // Associative columns + + if ($this->_as_object) + { + foreach ($this as $row) + { + $results[$row->$key] = $row->$value; + } + } + else + { + foreach ($this as $row) + { + $results[$row[$key]] = $row[$value]; + } + } + } + + $this->rewind(); + + return $results; + } + + /** + * Return the named column from the current row. + * + * // Get the "id" value + * $id = $result->get('id'); + * + * @param string column to get + * @param mixed default value if the column does not exist + * @return mixed + */ + public function get($name, $default = NULL) + { + $row = $this->current(); + + if ($this->_as_object) + { + if (isset($row->$name)) + return $row->$name; + } + else + { + if (isset($row[$name])) + return $row[$name]; + } + + return $default; + } + + /** + * Implements [Countable::count], returns the total number of rows. + * + * echo count($result); + * + * @return integer + */ + public function count() + { + return $this->_total_rows; + } + + /** + * Implements [ArrayAccess::offsetExists], determines if row exists. + * + * if (isset($result[10])) + * { + * // Row 10 exists + * } + * + * @return boolean + */ + public function offsetExists($offset) + { + return ($offset >= 0 AND $offset < $this->_total_rows); + } + + /** + * Implements [ArrayAccess::offsetGet], gets a given row. + * + * $row = $result[10]; + * + * @return mixed + */ + public function offsetGet($offset) + { + if ( ! $this->seek($offset)) + return NULL; + + return $this->current(); + } + + /** + * Implements [ArrayAccess::offsetSet], throws an error. + * + * [!!] You cannot modify a database result. + * + * @return void + * @throws Kohana_Exception + */ + final public function offsetSet($offset, $value) + { + throw new Kohana_Exception('Database results are read-only'); + } + + /** + * Implements [ArrayAccess::offsetUnset], throws an error. + * + * [!!] You cannot modify a database result. + * + * @return void + * @throws Kohana_Exception + */ + final public function offsetUnset($offset) + { + throw new Kohana_Exception('Database results are read-only'); + } + + /** + * Implements [Iterator::key], returns the current row number. + * + * echo key($result); + * + * @return integer + */ + public function key() + { + return $this->_current_row; + } + + /** + * Implements [Iterator::next], moves to the next row. + * + * next($result); + * + * @return $this + */ + public function next() + { + ++$this->_current_row; + return $this; + } + + /** + * Implements [Iterator::prev], moves to the previous row. + * + * prev($result); + * + * @return $this + */ + public function prev() + { + --$this->_current_row; + return $this; + } + + /** + * Implements [Iterator::rewind], sets the current row to zero. + * + * rewind($result); + * + * @return $this + */ + public function rewind() + { + $this->_current_row = 0; + return $this; + } + + /** + * Implements [Iterator::valid], checks if the current row exists. + * + * [!!] This method is only used internally. + * + * @return boolean + */ + public function valid() + { + return $this->offsetExists($this->_current_row); + } + +} // End Database_Result diff --git a/includes/kohana/modules/database/classes/kohana/database/result/cached.php b/includes/kohana/modules/database/classes/kohana/database/result/cached.php new file mode 100644 index 0000000..0fff47f --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/database/result/cached.php @@ -0,0 +1,51 @@ +_total_rows = count($result); + } + + public function __destruct() + { + // Cached results do not use resources + } + + public function cached() + { + return $this; + } + + public function seek($offset) + { + if ($this->offsetExists($offset)) + { + $this->_current_row = $offset; + + return TRUE; + } + else + { + return FALSE; + } + } + + public function current() + { + // Return an array of the row + return $this->valid() ? $this->_result[$this->_current_row] : FALSE; + } + +} // End Database_Result_Cached diff --git a/includes/kohana/modules/database/classes/kohana/db.php b/includes/kohana/modules/database/classes/kohana/db.php new file mode 100644 index 0000000..b6e513f --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/db.php @@ -0,0 +1,139 @@ +[`DB::select_array()`](#select_array) | [Database_Query_Builder_Select] + * [`DB::update()`](#update) | [Database_Query_Builder_Update] + * [`DB::delete()`](#delete) | [Database_Query_Builder_Delete] + * [`DB::expr()`](#expr) | [Database_Expression] + * + * You pass the same parameters to these functions as you pass to the objects they return. + * + * @package Kohana/Database + * @category Base + * @author Kohana Team + * @copyright (c) 2009 Kohana Team + * @license http://kohanaphp.com/license + */ +class Kohana_DB { + + /** + * Create a new [Database_Query] of the given type. + * + * // Create a new SELECT query + * $query = DB::query(Database::SELECT, 'SELECT * FROM users'); + * + * // Create a new DELETE query + * $query = DB::query(Database::DELETE, 'DELETE FROM users WHERE id = 5'); + * + * Specifying the type changes the returned result. When using + * `Database::SELECT`, a [Database_Query_Result] will be returned. + * `Database::INSERT` queries will return the insert id and number of rows. + * For all other queries, the number of affected rows is returned. + * + * @param integer type: Database::SELECT, Database::UPDATE, etc + * @param string SQL statement + * @return Database_Query + */ + public static function query($type, $sql) + { + return new Database_Query($type, $sql); + } + + /** + * Create a new [Database_Query_Builder_Select]. Each argument will be + * treated as a column. To generate a `foo AS bar` alias, use an array. + * + * // SELECT id, username + * $query = DB::select('id', 'username'); + * + * // SELECT id AS user_id + * $query = DB::select(array('id', 'user_id')); + * + * @param mixed column name or array($column, $alias) or object + * @param ... + * @return Database_Query_Builder_Select + */ + public static function select($columns = NULL) + { + return new Database_Query_Builder_Select(func_get_args()); + } + + /** + * Create a new [Database_Query_Builder_Select] from an array of columns. + * + * // SELECT id, username + * $query = DB::select_array(array('id', 'username')); + * + * @param array columns to select + * @return Database_Query_Builder_Select + */ + public static function select_array(array $columns = NULL) + { + return new Database_Query_Builder_Select($columns); + } + + /** + * Create a new [Database_Query_Builder_Insert]. + * + * // INSERT INTO users (id, username) + * $query = DB::insert('users', array('id', 'username')); + * + * @param string table to insert into + * @param array list of column names or array($column, $alias) or object + * @return Database_Query_Builder_Insert + */ + public static function insert($table = NULL, array $columns = NULL) + { + return new Database_Query_Builder_Insert($table, $columns); + } + + /** + * Create a new [Database_Query_Builder_Update]. + * + * // UPDATE users + * $query = DB::update('users'); + * + * @param string table to update + * @return Database_Query_Builder_Update + */ + public static function update($table = NULL) + { + return new Database_Query_Builder_Update($table); + } + + /** + * Create a new [Database_Query_Builder_Delete]. + * + * // DELETE FROM users + * $query = DB::delete('users'); + * + * @param string table to delete from + * @return Database_Query_Builder_Delete + */ + public static function delete($table = NULL) + { + return new Database_Query_Builder_Delete($table); + } + + /** + * Create a new [Database_Expression] which is not escaped. An expression + * is the only way to use SQL functions within query builders. + * + * $expression = DB::expr('COUNT(users.id)'); + * $query = DB::update('users')->set(array('login_count' => DB::expr('login_count + 1')))->where('id', '=', $id); + * $users = ORM::factory('user')->where(DB::expr("BINARY `hash`"), '=', $hash)->find(); + * + * @param string expression + * @return Database_Expression + */ + public static function expr($string) + { + return new Database_Expression($string); + } + +} // End DB diff --git a/includes/kohana/modules/database/classes/kohana/session/database.php b/includes/kohana/modules/database/classes/kohana/session/database.php new file mode 100644 index 0000000..1a381cd --- /dev/null +++ b/includes/kohana/modules/database/classes/kohana/session/database.php @@ -0,0 +1,229 @@ + 'session_id', + 'last_active' => 'last_active', + 'contents' => 'contents' + ); + + // Garbage collection requests + protected $_gc = 500; + + // The current session id + protected $_session_id; + + // The old session id + protected $_update_id; + + public function __construct(array $config = NULL, $id = NULL) + { + if ( ! isset($config['group'])) + { + // Use the default group + $config['group'] = 'default'; + } + + // Load the database + $this->_db = Database::instance($config['group']); + + if (isset($config['table'])) + { + // Set the table name + $this->_table = (string) $config['table']; + } + + if (isset($config['gc'])) + { + // Set the gc chance + $this->_gc = (int) $config['gc']; + } + + if (isset($config['columns'])) + { + // Overload column names + $this->_columns = $config['columns']; + } + + parent::__construct($config, $id); + + if (mt_rand(0, $this->_gc) === $this->_gc) + { + // Run garbage collection + // This will average out to run once every X requests + $this->_gc(); + } + } + + public function id() + { + return $this->_session_id; + } + + protected function _read($id = NULL) + { + if ($id OR $id = Cookie::get($this->_name)) + { + $result = DB::select(array($this->_columns['contents'], 'contents')) + ->from($this->_table) + ->where($this->_columns['session_id'], '=', ':id') + ->limit(1) + ->param(':id', $id) + ->execute($this->_db); + + if ($result->count()) + { + // Set the current session id + $this->_session_id = $this->_update_id = $id; + + // Return the contents + return $result->get('contents'); + } + } + + // Create a new session id + $this->_regenerate(); + + return NULL; + } + + protected function _regenerate() + { + // Create the query to find an ID + $query = DB::select($this->_columns['session_id']) + ->from($this->_table) + ->where($this->_columns['session_id'], '=', ':id') + ->limit(1) + ->bind(':id', $id); + + do + { + // Create a new session id + $id = str_replace('.', '-', uniqid(NULL, TRUE)); + + // Get the the id from the database + $result = $query->execute($this->_db); + } + while ($result->count()); + + return $this->_session_id = $id; + } + + protected function _write() + { + if ($this->_update_id === NULL) + { + // Insert a new row + $query = DB::insert($this->_table, $this->_columns) + ->values(array(':new_id', ':active', ':contents')); + } + else + { + // Update the row + $query = DB::update($this->_table) + ->value($this->_columns['last_active'], ':active') + ->value($this->_columns['contents'], ':contents') + ->where($this->_columns['session_id'], '=', ':old_id'); + + if ($this->_update_id !== $this->_session_id) + { + // Also update the session id + $query->value($this->_columns['session_id'], ':new_id'); + } + } + + $query + ->param(':new_id', $this->_session_id) + ->param(':old_id', $this->_update_id) + ->param(':active', $this->_data['last_active']) + ->param(':contents', $this->__toString()); + + // Execute the query + $query->execute($this->_db); + + // The update and the session id are now the same + $this->_update_id = $this->_session_id; + + // Update the cookie with the new session id + Cookie::set($this->_name, $this->_session_id, $this->_lifetime); + + return TRUE; + } + + protected function _destroy() + { + if ($this->_update_id === NULL) + { + // Session has not been created yet + return TRUE; + } + + // Delete the current session + $query = DB::delete($this->_table) + ->where($this->_columns['session_id'], '=', ':id') + ->param(':id', $this->_update_id); + + try + { + // Execute the query + $query->execute($this->_db); + + // Delete the cookie + Cookie::delete($this->_name); + } + catch (Exception $e) + { + // An error occurred, the session has not been deleted + return FALSE; + } + + return TRUE; + } + + protected function _gc() + { + if ($this->_lifetime) + { + // Expire sessions when their lifetime is up + $expires = $this->_lifetime; + } + else + { + // Expire sessions after one month + $expires = Date::MONTH; + } + + // Delete all sessions that have expired + DB::delete($this->_table) + ->where($this->_columns['last_active'], '<', ':time') + ->param(':time', time() - $expires) + ->execute($this->_db); + } + +} // End Session_Database diff --git a/includes/kohana/modules/database/classes/session/database.php b/includes/kohana/modules/database/classes/session/database.php new file mode 100644 index 0000000..1e75223 --- /dev/null +++ b/includes/kohana/modules/database/classes/session/database.php @@ -0,0 +1,3 @@ + array + ( + 'type' => 'mysql', + 'connection' => array( + /** + * The following options are available for MySQL: + * + * string hostname server hostname, or socket + * string database database name + * string username database username + * string password database password + * boolean persistent use persistent connections? + * + * Ports and sockets may be appended to the hostname. + */ + 'hostname' => 'localhost', + 'database' => 'kohana', + 'username' => FALSE, + 'password' => FALSE, + 'persistent' => FALSE, + ), + 'table_prefix' => '', + 'charset' => 'utf8', + 'caching' => FALSE, + 'profiling' => TRUE, + ), + 'alternate' => array( + 'type' => 'pdo', + 'connection' => array( + /** + * The following options are available for PDO: + * + * string dsn Data Source Name + * string username database username + * string password database password + * boolean persistent use persistent connections? + */ + 'dsn' => 'mysql:host=localhost;dbname=kohana', + 'username' => 'root', + 'password' => 'r00tdb', + 'persistent' => FALSE, + ), + /** + * The following extra options are available for PDO: + * + * string identifier set the escaping identifier + */ + 'table_prefix' => '', + 'charset' => 'utf8', + 'caching' => FALSE, + 'profiling' => TRUE, + ), +); \ No newline at end of file diff --git a/includes/kohana/modules/database/config/session.php b/includes/kohana/modules/database/config/session.php new file mode 100644 index 0000000..a4229c7 --- /dev/null +++ b/includes/kohana/modules/database/config/session.php @@ -0,0 +1,27 @@ + array( + /** + * Database settings for session storage. + * + * string group configuation group name + * string table session table name + * integer gc number of requests before gc is invoked + * columns array custom column names + */ + 'group' => 'default', + 'table' => 'sessions', + 'gc' => 500, + 'columns' => array( + /** + * session_id: session identifier + * last_active: timestamp of the last activity + * contents: serialized session data + */ + 'session_id' => 'session_id', + 'last_active' => 'last_active', + 'contents' => 'contents' + ), + ), +); diff --git a/includes/kohana/modules/database/config/userguide.php b/includes/kohana/modules/database/config/userguide.php new file mode 100644 index 0000000..36b79a0 --- /dev/null +++ b/includes/kohana/modules/database/config/userguide.php @@ -0,0 +1,23 @@ + array( + + // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' + 'database' => array( + + // Whether this modules userguide pages should be shown + 'enabled' => TRUE, + + // The name that should show up on the userguide index page + 'name' => 'Database', + + // A short description of this module, shown on the index page + 'description' => 'Database agnostic querying and result management.', + + // Copyright message, shown in the footer for this module + 'copyright' => '© 2008–2010 Kohana Team', + ) + ) +); \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/config.md b/includes/kohana/modules/database/guide/database/config.md new file mode 100644 index 0000000..6879c0a --- /dev/null +++ b/includes/kohana/modules/database/guide/database/config.md @@ -0,0 +1,118 @@ +# Configuration + +The default config file is located in `MODPATH/database/config/database.php`. You should copy this file to `APPPATH/config/database.php` and make changes there, in keeping with the [cascading filesystem](../kohana/files). + +The database configuration file contains an array of configuration groups. The structure of each database configuration group, called an "instance", looks like this: + + string INSTANCE_NAME => array( + 'type' => string DATABASE_TYPE, + 'connection' => array CONNECTION_ARRAY, + 'table_prefix' => string TABLE_PREFIX, + 'charset' => string CHARACTER_SET, + 'profiling' => boolean QUERY_PROFILING, + ), + +Understanding each of these settings is important. + +INSTANCE_NAME +: Connections can be named anything you want, but you should always have at least one connection called "default". + +DATABASE_TYPE +: One of the installed database drivers. Kohana comes with "mysql" and "pdo" drivers. Drivers must extend the Database class. + +CONNECTION_ARRAY +: Specific driver options for connecting to your database. (Driver options are explained [below](#connection-settings).) + +TABLE_PREFIX +: Prefix that will be added to all table names by the [query builder](#query_building). Prepared statements will **not** use the table prefix. + +QUERY_PROFILING +: Enables [profiling](../kohana/profiling) of database queries. This is useful for seeing how many queries each page is using, and which are taking the longest. You must enable the profiler the view these stats. + +## Example + +The example file below shows 2 MySQL connections, one local and one remote. + + return array + ( + 'default' => array + ( + 'type' => 'mysql', + 'connection' => array( + 'hostname' => 'localhost', + 'username' => 'dbuser', + 'password' => 'mypassword', + 'persistent' => FALSE, + 'database' => 'my_db_name', + ), + 'table_prefix' => '', + 'charset' => 'utf8', + 'profiling' => TRUE, + ), + 'remote' => array( + 'type' => 'mysql', + 'connection' => array( + 'hostname' => '55.55.55.55', + 'username' => 'remote_user', + 'password' => 'mypassword', + 'persistent' => FALSE, + 'database' => 'my_remote_db_name', + ), + 'table_prefix' => '', + 'charset' => 'utf8', + 'profiling' => TRUE, + ), + ); + +## Connections and Instances + +Each configuration group is referred to as a database instance. Each instance can be accessed by calling [Database::instance]. If you don't provide a parameter, the default instance is used. + + // This would connect to the database defined as 'default' + $default = Database::instance(); + + // This would connect to the database defined as 'remote' + $remote = Database::instance('remote'); + +To disconnect the database, simply destroy the object: + + unset($default) + + // Or + + unset(Database::$instances['default']); + +If you want to disconnect all of the database instances at once: + + Database::$instances = array(); + +## Connection Settings + +Every database driver has different connection settings. + +### MySQL + +A [MySQL database](http://www.php.net/manual/en/book.mysql.php) can accept the following options in the `connection` array: + +Type | Option | Description | Default value +----------|------------|----------------------------| ------------------------- +`string` | hostname | Hostname of the database | `localhost` +`integer` | port | Port number | `NULL` +`string` | socket | UNIX socket | `NULL` +`string` | username | Database username | `NULL` +`string` | password | Database password | `NULL` +`boolean` | persistent | Persistent connections | `FALSE` +`string` | database | Database name | `kohana` + +### PDO + +A [PDO database](http://php.net/manual/en/book.pdo.php) can accept these options in the `connection` array: + +Type | Option | Description | Default value +----------|------------|----------------------------| ------------------------- +`string` | dsn | PDO data source identifier | `localhost` +`string` | username | Database username | `NULL` +`string` | password | Database password | `NULL` +`boolean` | persistent | Persistent connections | `FALSE` + +[!!] If you are using PDO and are not sure what to use for the `dsn` option, review [PDO::__construct](http://php.net/pdo.construct). \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/examples.md b/includes/kohana/modules/database/guide/database/examples.md new file mode 100644 index 0000000..4849823 --- /dev/null +++ b/includes/kohana/modules/database/guide/database/examples.md @@ -0,0 +1,52 @@ +# Examples + +Here are some "real world" examples of using the database library to construct your queries and use the results. + +## Examples of Prepared Statements + +TODO: 4-6 examples of prepared statements of varying complexity, including a good bind() example. + +## Pagination and search/filter + +In this example, we loop through an array of whitelisted input fields and for each allowed non-empty value we add it to the search query. We make a clone of the query and then execute that query to count the total number of results. The count is then passed to the [Pagination](../pagination) class to determine the search offset. The last few lines search with Pagination's items_per_page and offset values to return a page of results based on the current page the user is on. + + $query = DB::select()->from('users'); + + //only search for these fields + $form_inputs = array('first_name', 'last_name', 'email'); + foreach ($form_inputs as $name) + { + $value = Arr::get($_GET, $name, FALSE); + if ($value !== FALSE AND $value != '') + { + $query->where($name, 'like', '%'.$value.'%'); + } + } + + //copy the query & execute it + $pagination_query = clone $query; + $count = $pagination_query->select('COUNT("*") AS mycount')->execute()->get('mycount'); + + //pass the total item count to Pagination + $config = Kohana::config('pagination'); + $pagination = Pagination::factory(array( + 'total_items' => $count, + 'current_page' => array('source' => 'route', 'key' => 'page'), + 'items_per_page' => 20, + 'view' => 'pagination/pretty', + 'auto_hide' => TRUE, + )); + $page_links = $pagination->render(); + + //search for results starting at the offset calculated by the Pagination class + $query->order_by('last_name', 'asc') + ->order_by('first_name', 'asc') + ->limit($pagination->items_per_page) + ->offset($pagination->offset); + $results = $query->execute()->as_array(); + +## Having + +TODO: example goes here + +[!!] We could use more examples on this page. \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/index.md b/includes/kohana/modules/database/guide/database/index.md new file mode 100644 index 0000000..162651d --- /dev/null +++ b/includes/kohana/modules/database/guide/database/index.md @@ -0,0 +1,17 @@ +# Database + +Kohana 3.0 comes with a robust module for working with databases. By default, the database module supports drivers for [MySQL](http://php.net/mysql) and [PDO](http://php.net/pdo), but new drivers can be made for other database servers. + +The database module is included with the Kohana 3.0 install, but needs to be enabled before you can use it. To enable, open your `application/bootstrap.php` file and modify the call to [Kohana::modules] by including the database module like so: + + Kohana::modules(array( + ... + 'database' => MODPATH.'database', + ... + )); + +Next, you will then need to [configure](config) the database module to connect to your database. + +Once that is done then you can make [queries](query) and use the [results](results). + +The database module also provides a [config driver](../api/Kohana_Config_Database) (for storing [configuration](../kohana/files/config) in the database) and a [session driver](Session_Database). diff --git a/includes/kohana/modules/database/guide/database/menu.md b/includes/kohana/modules/database/guide/database/menu.md new file mode 100644 index 0000000..e3f2c7a --- /dev/null +++ b/includes/kohana/modules/database/guide/database/menu.md @@ -0,0 +1,7 @@ +## [Database]() +- [Configuration](config) +- [Querying](query) + - [Prepared Statements](query/prepared) + - [Query Builder](query/builder) +- [Results](results) +- [Examples](examples) \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/query.md b/includes/kohana/modules/database/guide/database/query.md new file mode 100644 index 0000000..2e9bd41 --- /dev/null +++ b/includes/kohana/modules/database/guide/database/query.md @@ -0,0 +1,5 @@ +# Making Queries + +There are two different ways to make queries. The simplest way to make a query is to use [Database_Query], via [DB::query], to manually create queries. These queries are called [prepared statements](query/prepared) and allow you to set query parameters which are automatically escaped. The second way to make a query is by building the query using method calls. This is done using the [query builder](query/builder). + +[!!] All queries are run using the `execute` method, which accepts a [Database] object or instance name. See [Database_Query::execute] for more information. \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/query/builder.md b/includes/kohana/modules/database/guide/database/query/builder.md new file mode 100644 index 0000000..ec11b1a --- /dev/null +++ b/includes/kohana/modules/database/guide/database/query/builder.md @@ -0,0 +1,253 @@ +# Query Builder + +Creating queries dynamically using objects and methods allows queries to be written very quickly in an agnostic way. Query building also adds identifier (table and column name) quoting, as well as value quoting. + +[!!] At this time, it is not possible to combine query building with prepared statements. + +## Select + +Each type of database query is represented by a different class, each with their own methods. For instance, to create a SELECT query, we use [DB::select] which is a shortcut to return a new [Database_Query_Builder_Select] object: + + $query = DB::select(); + +Query Builder methods return a reference to itself so that method chaining may be used. Select queries ussually require a table and they are referenced using the `from()` method. The `from()` method takes one parameter which can be the table name (string), an array of two strings (table name and alias), or an object (See Subqueries in the Advanced Queries section below). + + $query = DB::select()->from('users'); + +Limiting the results of queries is done using the `where()`, `and_where()` and `or_where()` methods. These methods take three parameters: a column, an operator, and a value. + + $query = DB::select()->from('users')->where('username', '=', 'john'); + +Multiple `where()` methods may be used to string together multiple clauses connected by the boolean operator in the method's prefix. The `where()` method is a wrapper that just calls `and_where()`. + + $query = DB::select()->from('users')->where('username', '=', 'john')->or_where('username', '=', 'jane'); + +You can use any operator you want. Examples include `IN`, `BETWEEN`, `>`, `=<`, `!=`, etc. Use an array for operators that require more than one value. + + $query = DB::select()->from('users')->where('logins', '<=', 1); + + $query = DB::select()->from('users')->where('logins', '>', 50); + + $query = DB::select()->from('users')->where('username', 'IN', array('john','mark','matt')); + + $query = DB::select()->from('users')->where('joindate', 'BETWEEN', array($then, $now)); + +By default, [DB::select] will select all columns (`SELECT * ...`), but you can also specify which columns you want returned by passing parameters to [DB::select]: + + $query = DB::select('username', 'password')->from('users')->where('username', '=', 'john'); + +Now take a minute to look at what this method chain is doing. First, we create a new selection object using the [DB::select] method. Next, we set table(s) using the `from()` method. Last, we search for a specific records using the `where()` method. We can display the SQL that will be executed by casting the query to a string: + + echo Kohana::debug((string) $query); + // Should display: + // SELECT `username`, `password` FROM `users` WHERE `username` = 'john' + +Notice how the column and table names are automatically escaped, as well as the values? This is one of the key benefits of using the query builder. + +### Select - AS (column aliases) + +It is also possible to create `AS` aliases when selecting, by passing an array as each parameter to [DB::select]: + + $query = DB::select(array('username', 'u'), array('password', 'p'))->from('users'); + +This query would generate the following SQL: + + SELECT `username` AS `u`, `password` AS `p` FROM `users` + +### Select - DISTINCT + +Unique column values may be turned on or off (default) by passing TRUE or FALSE, respectively, to the `distinct()` method. + + $query = DB::select('username')->distinct(TRUE)->from('posts'); + +This query would generate the following SQL: + + SELECT DISTINCT `username` FROM `posts` + +### Select - LIMIT & OFFSET + +When querying large sets of data, it is often better to limit the results and page through the data one chunk at a time. This is done using the `limit()` and `offset()` methods. + + $query = DB::select()->from(`posts`)->limit(10)->offset(30); + +This query would generate the following SQL: + + SELECT * FROM `posts` LIMIT 10 OFFSET 30 + +### Select - ORDER BY + +Often you will want the results in a particular order and rather than sorting the results, it's better to have the results returned to you in the correct order. You can do this by using the order_by() method. It takes the column name and an optional direction string as the parameters. Multiple `order_by()` methods can be used to add additional sorting capability. + + $query = DB::select()->from(`posts`)->order_by(`published`, `DESC`); + +This query would generate the following SQL: + + SELECT * FROM `posts` ORDER BY `published` DESC + +[!!] For a complete list of methods available while building a select query see [Database_Query_Builder_Select]. + +## Insert + +To create records into the database, use [DB::insert] to create an INSERT query, using `values()` to pass in the data: + + $query = DB::insert('users', array('username', 'password'))->values(array('fred', 'p@5sW0Rd')); + +This query would generate the following SQL: + + INSERT INTO `users` (`username`, `password`) VALUES ('fred', 'p@5sW0Rd') + +[!!] For a complete list of methods available while building an insert query see [Database_Query_Builder_Insert]. + +## Update + +To modify an existing record, use [DB::update] to create an UPDATE query: + + $query = DB::update('users')->set(array('username' => 'jane'))->where('username', '=', 'john'); + +This query would generate the following SQL: + + UPDATE `users` SET `username` = 'jane' WHERE `username` = 'john' + +[!!] For a complete list of methods available while building an update query see [Database_Query_Builder_Update]. + +## Delete + +To remove an existing record, use [DB::delete] to create a DELETE query: + + $query = DB::delete('users')->where('username', 'IN', array('john', 'jane')); + +This query would generate the following SQL: + + DELETE FROM `users` WHERE `username` IN ('john', 'jane') + +[!!] For a complete list of methods available while building a delete query see [Database_Query_Builder_Delete]. + +## Advanced Queries + +### Joins + +Multiple tables can be joined using the `join()` and `on()` methods. The `join()` method takes two parameters. The first is either a table name, an array containing the table and alias, or an object (subquery or expression). The second parameter is the join type: LEFT, RIGHT, INNER, etc. + +The `on()` method sets the conditions for the previous `join()` method and is very similar to the `where()` method in that it takes three parameters; left column (name or object), an operator, and the right column (name or object). Multiple `on()` methods may be used to supply multiple conditions and they will be appended with an 'AND' operator. + + // This query will find all the posts related to "smith" with JOIN + $query = DB::select('authors.name', 'posts.content')->from('authors')->join('posts')->on('authors.id', '=', 'posts.author_id')->where('authors.name', '=', 'smith'); + +This query would generate the following SQL: + + SELECT `authors`.`name`, `posts`.`content` FROM `authors` JOIN `posts` ON (`authors`.`id` = `posts`.`author_id`) WHERE `authors`.`name` = 'smith' + +If you want to do a LEFT, RIGHT or INNER JOIN you would do it like this `join('colum_name', 'type_of_join')`: + + // This query will find all the posts related to "smith" with LEFT JOIN + $query = DB::select()->from('authors')->join('posts', 'LEFT')->on('authors.id', '=', 'posts.author_id')->where('authors.name', '=', 'smith'); + +This query would generate the following SQL: + + SELECT `authors`.`name`, `posts`.`content` FROM `authors` LEFT JOIN `posts` ON (`authors`.`id` = `posts`.`author_id`) WHERE `authors`.`name` = 'smith' + +[!!] When joining multiple tables with similar column names, it's best to prefix the columns with the table name or table alias to avoid errors. Ambiguous column names should also be aliased so that they can be referenced easier. + +### Database Functions + +Eventually you will probably run into a situation where you need to call `COUNT` or some other database function within your query. The query builder supports these functions in two ways. The first is by using quotes within aliases: + + $query = DB::select(array('COUNT("username")', 'total_users'))->from('users'); + +This looks almost exactly the same as a standard `AS` alias, but note how the column name is wrapped in double quotes. Any time a double-quoted value appears inside of a column name, **only** the part inside the double quotes will be escaped. This query would generate the following SQL: + + SELECT COUNT(`username`) AS `total_users` FROM `users` + +[!!] When building complex queries and you need to get a count of the total rows that will be returned, build the expression with an empty column list first. Then clone the query and add the COUNT function to one copy and the columns list to the other. This will cut down on the total lines of code and make updating the query easier. + + $query = DB::select()->from('users') + ->join('posts')->on('posts.username', '=', 'users.username') + ->where('users.active', '=', TRUE) + ->where('posts.created', '>=', $yesterday); + + $total = clone $query; + $total->select(array('COUNT( DISTINCT "username")', 'unique_users')); + $query->select('posts.username')->distinct(); + +### Aggregate Functions + +Aggregate functions like `COUNT()`, `SUM()`, `AVG()`, etc. will most likely be used with the `group_by()` and possibly the `having()` methods in order to group and filter the results on a set of columns. + + $query = DB::select('username', array('COUNT("id")', 'total_posts') + ->from('posts')->group_by('username')->having('total_posts', '>=', 10); + +This will generate the following query: + + SELECT `username`, COUNT(`id`) AS `total_posts` FROM `posts` GROUP BY `username` HAVING `total_posts` >= 10 + +### Subqueries + +Query Builder objects can be passed as parameters to many of the methods to create subqueries. Let's take the previous example query and pass it to a new query. + + $sub = DB::select('username', array('COUNT("id")', 'total_posts') + ->from('posts')->group_by('username')->having('total_posts', '>=', 10); + + $query = DB::select('profiles.*', 'posts.total_posts')->from('profiles') + ->join(array($sub, 'posts'), 'INNER')->on('profiles.username', '=', 'posts.username'); + +This will generate the following query: + + SELECT `profiles`.*, `posts`.`total_posts` FROM `profiles` INNER JOIN + ( SELECT `username`, COUNT(`id`) AS `total_posts` FROM `posts` GROUP BY `username` HAVING `total_posts` >= 10 ) AS posts + ON `profiles`.`username` = `posts`.`username` + +Insert queries can also use a select query for the input values + + $sub = DB::select('username', array('COUNT("id")', 'total_posts') + ->from('posts')->group_by('username')->having('total_posts', '>=', 10); + + $query = DB::insert('post_totals', array('username', 'posts'))->select($sub); + +This will generate the following query: + + INSERT INTO `post_totals` (`username`, `posts`) + SELECT `username`, COUNT(`id`) AS `total_posts` FROM `posts` GROUP BY `username` HAVING `total_posts` >= 10 + +### Boolean Operators and Nested Clauses + +Multiple Where and Having clauses are added to the query with Boolean operators connecting each expression. The default operator for both methods is AND which is the same as the and_ prefixed method. The OR operator can be specified by prefixing the methods with or_. Where and Having clauses can be nested or grouped by post fixing either method with _open and then followed by a method with a _close. + + $query = DB::select()->from('users') + ->where_open() + ->or_where('id', 'IN', $expired) + ->and_where_open() + ->where('last_login', '<=', $last_month) + ->or_where('last_login', 'IS', NULL) + ->and_where_close() + ->where_close() + ->and_where('removed','IS', NULL); + +This will generate the following query: + + SELECT * FROM `users` WHERE ( `id` IN (1, 2, 3, 5) OR ( `last_login` <= 1276020805 OR `last_login` IS NULL ) ) AND `removed` IS NULL + +### Database Expressions + +There are cases were you need a complex expression or other database functions, which you don't want the Query Builder to try and escape. In these cases, you will need to use a database expression created with [DB::expr]. **A database expression is taken as direct input and no escaping is performed.** + + $query = DB::update('users')->set(array('login_count' => DB::expr('login_count + 1')))->where('id', '=', $id); + +This will generate the following query, assuming `$id = 45`: + + UPDATE `users` SET `login_count` = `login_count` + 1 WHERE `id` = 45 + +Another example to calculate the distance of two geographical points: + + $query = DB::select(array(DB::expr('degrees(acos(sin(radians('.$lat.')) * sin(radians(`latitude`)) + cos(radians('.$lat.')) * cos(radians(`latitude`)) * cos(radians(abs('.$lng.' - `longitude`))))) * 69.172'), 'distance'))->from('locations'); + +[!!] You must validate or escape any user input inside of DB::expr as it will obviously not be escaped it for you. + +## Executing + +Once you are done building, you can execute the query using `execute()` and use [the results](results). + + $result = $query->execute(); + +To use a different database [config group](config) pass either the name or the config object to `execute()`. + + $result = $query->execute('config_name') \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/query/prepared.md b/includes/kohana/modules/database/guide/database/query/prepared.md new file mode 100644 index 0000000..53611b6 --- /dev/null +++ b/includes/kohana/modules/database/guide/database/query/prepared.md @@ -0,0 +1,67 @@ +# Prepared Statements + +Using prepared statements allows you to write SQL queries manually while still escaping the query values automatically to prevent [SQL injection](http://wikipedia.org/wiki/SQL_Injection). Creating a query is simple: + + $query = DB::query(Database::SELECT, 'SELECT * FROM users WHERE username = :user'); + +The [DB::query] method is just a shortcut that creates a new [Database_Query] class for us, to allow method chaining. The query contains a `:user` parameter, which we will get to in a second. + +The first parameter of [DB::query] is the type of query. It should be `Database::SELECT`, `Database::INSERT`, `Database::UPDATE`, or `Database::DELETE`. This is done for compatibility reasons for drivers, and to easily determine what `execute()` should return. + +The second parameter is the query itself. Rather than trying to concatenate your query and variables together, you should make use of [Database_Query::param]. This will make your queries much easier to mantain, and will escape the values to prevent [SQL injection](http://wikipedia.org/wiki/SQL_Injection). + +## Parameters + +Our example query earlier contains a `:user` parameter, which we can assign to a value using [Database_Query::param] like so: + + $query->param(':user', 'john'); + +[!!] Parameter names can be any unique string, as they are replaced using [strtr](http://php.net/strtr). It is highly recommended to **not** use dollars signs as parameter names to prevent confusion. Colons are commonly used. + +You can also update the `:user` parameter by calling [Database_Query::param] again: + + $query->param(':user', $_GET['search']); + +If you want to set multiple parameters at once, you can use [Database_Query::parameters]. + + $query = DB::query(Database::SELECT, 'SELECT * FROM users WHERE username = :user AND status = :status'); + + $query->parameters(array( + ':user' => 'john', + ':status' => 'active', + )); + +It is also possible to bind a parameter to a variable, using a [variable reference]((http://php.net/language.references.whatdo)). This can be extremely useful when running the same query many times: + + $query = DB::query(Database::INSERT, 'INSERT INTO users (username, password) VALUES (:user, :pass)') + ->bind(':user', $username) + ->bind(':pass', $password); + + foreach ($new_users as $username => $password) + { + $query->execute(); + } + +In the above example, the variables `$username` and `$password` are changed for every loop of the `foreach` statement. When the parameter changes, it effectively changes the `:user` and `:pass` query parameters. Careful parameter binding can save a lot of code when it is used properly. + +The only difference between `param()` and `bind()` is that `bind()` passes the variable by reference rather than by assignment (copied), so future changes to the variable can be "seen" by the query. + +[!!] Although all parameters are escaped to prevent SQL injection, it is still a good idea to validate/sanitize your input. + +## Display the raw query + +If you want to display the SQL that will be executed, simply cast the object to a string: + + echo Kohana::debug((string) $query); + // Should display: + // SELECT * FROM users WHERE username = 'john' + +## Executing + +Once you have assigned something to each of the parameters, you can execute the query using `execute()` and use [the results](results). + + $result = $query->execute(); + +To use a different database [config group](config) pass either the name or the config object to `execute()`. + + $result = $query->execute('config_name') \ No newline at end of file diff --git a/includes/kohana/modules/database/guide/database/results.md b/includes/kohana/modules/database/guide/database/results.md new file mode 100644 index 0000000..653aacc --- /dev/null +++ b/includes/kohana/modules/database/guide/database/results.md @@ -0,0 +1,105 @@ +# Results + +## Execute + +Once you have a query object built, either through a prepared statement or through the builder, you must then `execute()` the query and retrieve the results. Depending on the query type used, the results returned will vary. + +## Select + +[DB::select] will return a [Database_Result] object which you can then iterate over. This example shows how you can iterate through the [Database_Result] using a foreach. + + $results = DB::select()->from('users')->where('verified', '=', 0)->execute(); + foreach($results as $user) + { + // Send reminder email to $user['email'] + echo $user['email']." needs to verify his/her account\n"; + } + +### Select - `as_object()` and `as_assoc()` + +When iterating over a result set, the default type will be an associative array with the column names or aliases as the keys. As an option, before calling `execute()`, you can specify to return the result rows as an object by using the `as_object()` method. The `as_object()` method takes one parameter, the name of the class of your choice, but will default to TRUE which uses the `stdClass`. Here is the example again using `stdClass`. + + $results = DB::select()->from('users')->where('verified', '=', 0)->as_object()->execute(); + foreach($results as $user) + { + // Send reminder email to $user->email + echo $user->email." needs to verify his/her account\n"; + } + +[!!] The method `as_assoc()` will remove the object name and return the results set back to an associative array. Since this is the default, this method is seldom required. + +### Select - `as_array()` + +Sometimes you will require the results as a pure array rather than as an object. The `Database_Result` method `as_array()` will return an array of all rows. + + $results = DB::select('id', 'email')->from('users')->execute(); + $users = $results->as_array(); + foreach($users as $user) + { + echo 'User ID: '.$user['id']; + echo 'User Email: '.$user['email']; + } + +It also accepts two parameters that can be very helpful: `$key` and `$value`. When passing a value to `$key` you will index the resulting array by the column specified. + + $results = DB::select('id', 'email')->from('users')->execute(); + $users = $results->as_array('id'); + foreach($users as $id => $user) + { + echo 'User ID: '.$id; + echo 'User Email: '.$user['email']; + } + +The second parameter, `$value`, will reference the column specified and return that value rather than the whole row. This is particularly useful when making `"; +var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, +parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= +false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= +s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, +applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; +else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, +a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== +w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, +cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= +c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); +a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, +function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); +k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), +C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B=0){a.type= +e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& +f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; +if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", +e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, +"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, +d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, +e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); +t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| +g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, +CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, +g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, +text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, +setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return hl[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= +h[3];l=0;for(m=h.length;l=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== +"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, +h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& +q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML=""; +if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="

";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); +(function(){var g=s.createElement("div");g.innerHTML="
";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: +function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f0)for(var j=d;j0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= +{},i;if(f&&a.length){e=0;for(var o=a.length;e-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== +"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", +d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? +a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== +1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/"},F={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div
","
"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= +c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, +wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, +prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, +this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); +return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, +""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); +return this}else{e=0;for(var j=d.length;e0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", +""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]===""&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= +c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? +c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= +function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= +Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, +"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= +a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= +a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=//gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== +"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("
").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, +serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), +function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, +global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& +e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? +"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== +false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= +false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", +c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| +d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); +g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== +1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== +"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; +if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== +"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| +c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; +this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= +this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, +e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b
"; +a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); +c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, +d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- +f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": +"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in +e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window); \ No newline at end of file diff --git a/includes/kohana/modules/userguide/media/guide/js/kodoc.js b/includes/kohana/modules/userguide/media/guide/js/kodoc.js new file mode 100644 index 0000000..70d8b48 --- /dev/null +++ b/includes/kohana/modules/userguide/media/guide/js/kodoc.js @@ -0,0 +1,97 @@ +$(document).ready(function() +{ + +// Syntax highlighter + + $('pre:not(.debug) code').each(function() + { + $(this).addClass('brush: php, class-name: highlighted'); + }); + + SyntaxHighlighter.config.tagName = 'code'; + // Don't show the toolbar or line-numbers. + SyntaxHighlighter.defaults.gutter = false; + SyntaxHighlighter.all(); + + // Any link that has the current page as its href should be class="current" + $('a[href="'+ window.location.pathname +'"]').addClass('current'); + + // Breadcrumbs magic + $('#breadcrumb li.last').each(function() + { + var $this = $(this); + var $topics = $('#topics li').has('a.current').slice(0, -1); + + $topics.each(function() + { + // Create a copy of the menu link + var $crumb = $(this).children('a:first, span:not(.toggle):first').clone(); + + // Insert the menu link into the breadcrumbs + $('
  • ').html($crumb).insertBefore($this); + }); + }); + + // Collapsing menus + $('#topics li:has(li)').each(function() + { + var $this = $(this); + var toggle = $(''); + var menu = $this.find('>ul,>ol'); + + toggle.click(function() + { + if (menu.is(':visible')) + { + menu.stop(true, true).slideUp('fast'); + toggle.html('+'); + } + else + { + menu.stop(true, true).slideDown('fast'); + toggle.html('–'); + } + }); + + $this.find('>span').click(function() + { + // Menu without a link + toggle.click(); + }); + + if ( ! $this.is(':has(a.current)')) + { + menu.hide(); + } + + toggle.html(menu.is(':visible') ? '–' : '+').prependTo($this); + }); + +// Show source links + + $('#kodoc-main .method-source').each(function() + { + var self = $(this); + var togg = $(' [show]').appendTo($('h4', self)); + var code = self.find('pre').hide(); + + togg.toggle(function() + { + togg.html('[hide]'); + code.stop(true, true).slideDown(); + }, + function() + { + togg.html('[show]'); + code.stop(true, true).slideUp(); + }); + }); + + // "Link to this" link that appears when you hover over a header + $('#body') + .find('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]') + .append(function(){ + var $this = $(this); + return ''; + }); +}); diff --git a/includes/kohana/modules/userguide/media/guide/js/shBrushPhp.js b/includes/kohana/modules/userguide/media/guide/js/shBrushPhp.js new file mode 100644 index 0000000..95e6e43 --- /dev/null +++ b/includes/kohana/modules/userguide/media/guide/js/shBrushPhp.js @@ -0,0 +1,88 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +;(function() +{ + // CommonJS + typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; + + function Brush() + { + var funcs = 'abs acos acosh addcslashes addslashes ' + + 'array_change_key_case array_chunk array_combine array_count_values array_diff '+ + 'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+ + 'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+ + 'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+ + 'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+ + 'array_push array_rand array_reduce array_reverse array_search array_shift '+ + 'array_slice array_splice array_sum array_udiff array_udiff_assoc '+ + 'array_udiff_uassoc array_uintersect array_uintersect_assoc '+ + 'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+ + 'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+ + 'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+ + 'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+ + 'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+ + 'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+ + 'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+ + 'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+ + 'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+ + 'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+ + 'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+ + 'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+ + 'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+ + 'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+ + 'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+ + 'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+ + 'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+ + 'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+ + 'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+ + 'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+ + 'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+ + 'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+ + 'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+ + 'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+ + 'strtoupper strtr strval substr substr_compare'; + + var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' + + 'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' + + 'function include include_once global goto if implements interface instanceof namespace new ' + + 'old_function or private protected public return require require_once static switch ' + + 'throw try use var while xor '; + + var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__'; + + this.regexList = [ + { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments + { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments + { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings + { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings + { regex: /\$\w+/g, css: 'variable' }, // variables + { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions + { regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants + { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword + ]; + + this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags); + }; + + Brush.prototype = new SyntaxHighlighter.Highlighter(); + Brush.aliases = ['php']; + + SyntaxHighlighter.brushes.Php = Brush; + + // CommonJS + typeof(exports) != 'undefined' ? exports.Brush = Brush : null; +})(); diff --git a/includes/kohana/modules/userguide/media/guide/js/shCore.js b/includes/kohana/modules/userguide/media/guide/js/shCore.js new file mode 100644 index 0000000..b47b645 --- /dev/null +++ b/includes/kohana/modules/userguide/media/guide/js/shCore.js @@ -0,0 +1,17 @@ +/** + * SyntaxHighlighter + * http://alexgorbatchev.com/SyntaxHighlighter + * + * SyntaxHighlighter is donationware. If you are using it, please donate. + * http://alexgorbatchev.com/SyntaxHighlighter/donate.html + * + * @version + * 3.0.83 (July 02 2010) + * + * @copyright + * Copyright (C) 2004-2010 Alex Gorbatchev. + * + * @license + * Dual licensed under the MIT and GPL licenses. + */ +eval(function(p,a,c,k,e,d){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('K M;I(M)1S 2U("2a\'t 4k M 4K 2g 3l 4G 4H");(6(){6 r(f,e){I(!M.1R(f))1S 3m("3s 15 4R");K a=f.1w;f=M(f.1m,t(f)+(e||""));I(a)f.1w={1m:a.1m,19:a.19?a.19.1a(0):N};H f}6 t(f){H(f.1J?"g":"")+(f.4s?"i":"")+(f.4p?"m":"")+(f.4v?"x":"")+(f.3n?"y":"")}6 B(f,e,a,b){K c=u.L,d,h,g;v=R;5K{O(;c--;){g=u[c];I(a&g.3r&&(!g.2p||g.2p.W(b))){g.2q.12=e;I((h=g.2q.X(f))&&h.P===e){d={3k:g.2b.W(b,h,a),1C:h};1N}}}}5v(i){1S i}5q{v=11}H d}6 p(f,e,a){I(3b.Z.1i)H f.1i(e,a);O(a=a||0;a-1},3d:6(g){e+=g}};c1&&p(e,"")>-1){a=15(J.1m,n.Q.W(t(J),"g",""));n.Q.W(f.1a(e.P),a,6(){O(K c=1;c<14.L-2;c++)I(14[c]===1d)e[c]=1d})}I(J.1w&&J.1w.19)O(K b=1;be.P&&J.12--}H e};I(!D)15.Z.1A=6(f){(f=n.X.W(J,f))&&J.1J&&!f[0].L&&J.12>f.P&&J.12--;H!!f};1r.Z.1C=6(f){M.1R(f)||(f=15(f));I(f.1J){K e=n.1C.1p(J,14);f.12=0;H e}H f.X(J)};1r.Z.Q=6(f,e){K a=M.1R(f),b,c;I(a&&1j e.58()==="3f"&&e.1i("${")===-1&&y)H n.Q.1p(J,14);I(a){I(f.1w)b=f.1w.19}Y f+="";I(1j e==="6")c=n.Q.W(J,f,6(){I(b){14[0]=1f 1r(14[0]);O(K d=0;dd.L-3;){i=1r.Z.1a.W(g,-1)+i;g=1Q.3i(g/10)}H(g?d[g]||"":"$")+i}Y{g=+i;I(g<=d.L-3)H d[g];g=b?p(b,i):-1;H g>-1?d[g+1]:h}})})}I(a&&f.1J)f.12=0;H c};1r.Z.1e=6(f,e){I(!M.1R(f))H n.1e.1p(J,14);K a=J+"",b=[],c=0,d,h;I(e===1d||+e<0)e=5D;Y{e=1Q.3i(+e);I(!e)H[]}O(f=M.3c(f);d=f.X(a);){I(f.12>c){b.U(a.1a(c,d.P));d.L>1&&d.P=e)1N}f.12===d.P&&f.12++}I(c===a.L){I(!n.1A.W(f,"")||h)b.U("")}Y b.U(a.1a(c));H b.L>e?b.1a(0,e):b};M.1h(/\\(\\?#[^)]*\\)/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"});M.1h(/\\((?!\\?)/,6(){J.19.U(N);H"("});M.1h(/\\(\\?<([$\\w]+)>/,6(f){J.19.U(f[1]);J.2N=R;H"("});M.1h(/\\\\k<([\\w$]+)>/,6(f){K e=p(J.19,f[1]);H e>-1?"\\\\"+(e+1)+(3R(f.2S.3a(f.P+f[0].L))?"":"(?:)"):f[0]});M.1h(/\\[\\^?]/,6(f){H f[0]==="[]"?"\\\\b\\\\B":"[\\\\s\\\\S]"});M.1h(/^\\(\\?([5A]+)\\)/,6(f){J.3d(f[1]);H""});M.1h(/(?:\\s+|#.*)+/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"},M.1B,6(){H J.2K("x")});M.1h(/\\./,6(){H"[\\\\s\\\\S]"},M.1B,6(){H J.2K("s")})})();1j 2e!="1d"&&(2e.M=M);K 1v=6(){6 r(a,b){a.1l.1i(b)!=-1||(a.1l+=" "+b)}6 t(a){H a.1i("3e")==0?a:"3e"+a}6 B(a){H e.1Y.2A[t(a)]}6 p(a,b,c){I(a==N)H N;K d=c!=R?a.3G:[a.2G],h={"#":"1c",".":"1l"}[b.1o(0,1)]||"3h",g,i;g=h!="3h"?b.1o(1):b.5u();I((a[h]||"").1i(g)!=-1)H a;O(a=0;d&&a\'+c+""});H a}6 n(a,b){a.1e("\\n");O(K c="",d=0;d<50;d++)c+=" ";H a=v(a,6(h){I(h.1i("\\t")==-1)H h;O(K g=0;(g=h.1i("\\t"))!=-1;)h=h.1o(0,g)+c.1o(0,b-g%b)+h.1o(g+1,h.L);H h})}6 x(a){H a.Q(/^\\s+|\\s+$/g,"")}6 D(a,b){I(a.Pb.P)H 1;Y I(a.Lb.L)H 1;H 0}6 y(a,b){6 c(k){H k[0]}O(K d=N,h=[],g=b.2D?b.2D:c;(d=b.1I.X(a))!=N;){K i=g(d,b);I(1j i=="3f")i=[1f e.2L(i,d.P,b.23)];h=h.1O(i)}H h}6 E(a){K b=/(.*)((&1G;|&1y;).*)/;H a.Q(e.3A.3M,6(c){K d="",h=N;I(h=b.X(c)){c=h[1];d=h[2]}H\'\'+c+""+d})}6 z(){O(K a=1E.36("1k"),b=[],c=0;c<1z 4I="1Z://2y.3L.3K/4L/5L"><3J><4N 1Z-4M="5G-5M" 6K="2O/1z; 6J=6I-8" /><1t>6L 1v<3B 1L="25-6M:6Q,6P,6O,6N-6F;6y-2f:#6x;2f:#6w;25-22:6v;2O-3D:3C;">1v3v 3.0.76 (72 73 3x)1Z://3u.2w/1v70 17 6U 71.6T 6X-3x 6Y 6D.6t 61 60 J 1k, 5Z 5R 5V <2R/>5U 5T 5S!\'}},1Y:{2j:N,2A:{}},1U:{},3A:{6n:/\\/\\*[\\s\\S]*?\\*\\//2c,6m:/\\/\\/.*$/2c,6l:/#.*$/2c,6k:/"([^\\\\"\\n]|\\\\.)*"/g,6o:/\'([^\\\\\'\\n]|\\\\.)*\'/g,6p:1f M(\'"([^\\\\\\\\"]|\\\\\\\\.)*"\',"3z"),6s:1f M("\'([^\\\\\\\\\']|\\\\\\\\.)*\'","3z"),6q:/(&1y;|<)!--[\\s\\S]*?--(&1G;|>)/2c,3M:/\\w+:\\/\\/[\\w-.\\/?%&=:@;]*/g,6a:{18:/(&1y;|<)\\?=?/g,1b:/\\?(&1G;|>)/g},69:{18:/(&1y;|<)%=?/g,1b:/%(&1G;|>)/g},6d:{18:/(&1y;|<)\\s*1k.*?(&1G;|>)/2T,1b:/(&1y;|<)\\/\\s*1k\\s*(&1G;|>)/2T}},16:{1H:6(a){6 b(i,k){H e.16.2o(i,k,e.13.1x[k])}O(K c=\'\',d=e.16.2x,h=d.2X,g=0;g";H c},2o:6(a,b,c){H\'<2W>\'+c+""},2b:6(a){K b=a.1F,c=b.1l||"";b=B(p(b,".20",R).1c);K d=6(h){H(h=15(h+"6f(\\\\w+)").X(c))?h[1]:N}("6g");b&&d&&e.16.2x[d].2B(b);a.3N()},2x:{2X:["21","2P"],21:{1H:6(a){I(a.V("2l")!=R)H"";K b=a.V("1t");H e.16.2o(a,"21",b?b:e.13.1x.21)},2B:6(a){a=1E.6j(t(a.1c));a.1l=a.1l.Q("47","")}},2P:{2B:6(){K a="68=0";a+=", 18="+(31.30-33)/2+", 32="+(31.2Z-2Y)/2+", 30=33, 2Z=2Y";a=a.Q(/^,/,"");a=1P.6Z("","38",a);a.2C();K b=a.1E;b.6W(e.13.1x.37);b.6V();a.2C()}}}},35:6(a,b){K c;I(b)c=[b];Y{c=1E.36(e.13.34);O(K d=[],h=0;h(.*?))\\\\]$"),s=1f M("(?<27>[\\\\w-]+)\\\\s*:\\\\s*(?<1T>[\\\\w-%#]+|\\\\[.*?\\\\]|\\".*?\\"|\'.*?\')\\\\s*;?","g");(j=s.X(k))!=N;){K o=j.1T.Q(/^[\'"]|[\'"]$/g,"");I(o!=N&&m.1A(o)){o=m.X(o);o=o.2V.L>0?o.2V.1e(/\\s*,\\s*/):[]}l[j.27]=o}g={1F:g,1n:C(i,l)};g.1n.1D!=N&&d.U(g)}H d},1M:6(a,b){K c=J.35(a,b),d=N,h=e.13;I(c.L!==0)O(K g=0;g")==o-3){m=m.4h(0,o-3);s=R}l=s?m:l}I((i.1t||"")!="")k.1t=i.1t;k.1D=j;d.2Q(k);b=d.2F(l);I((i.1c||"")!="")b.1c=i.1c;i.2G.74(b,i)}}},2E:6(a){w(1P,"4k",6(){e.1M(a)})}};e.2E=e.2E;e.1M=e.1M;e.2L=6(a,b,c){J.1T=a;J.P=b;J.L=a.L;J.23=c;J.1V=N};e.2L.Z.1q=6(){H J.1T};e.4l=6(a){6 b(j,l){O(K m=0;md)1N;Y I(g.P==c.P&&g.L>c.L)a[b]=N;Y I(g.P>=c.P&&g.P\'+c+""},3Q:6(a,b){K c="",d=a.1e("\\n").L,h=2u(J.V("2i-1s")),g=J.V("2z-1s-2t");I(g==R)g=(h+d-1).1q().L;Y I(3R(g)==R)g=0;O(K i=0;i\'+j+"":"")+i)}H a},4f:6(a){H a?"<4a>"+a+"":""},4b:6(a,b){6 c(l){H(l=l?l.1V||g:g)?l+" ":""}O(K d=0,h="",g=J.V("1D",""),i=0;i|&1y;2R\\s*\\/?&1G;/2T;I(e.13.46==R)b=b.Q(h,"\\n");I(e.13.44==R)b=b.Q(h,"");b=b.1e("\\n");h=/^\\s*/;g=4Q;O(K i=0;i0;i++){K k=b[i];I(x(k).L!=0){k=h.X(k);I(k==N){a=a;1N a}g=1Q.4q(k[0].L,g)}}I(g>0)O(i=0;i\'+(J.V("16")?e.16.1H(J):"")+\'<3Z 5z="0" 5H="0" 5J="0">\'+J.4f(J.V("1t"))+"<3T><3P>"+(1u?\'<2d 1g="1u">\'+J.3Q(a)+"":"")+\'<2d 1g="17">\'+b+""},2F:6(a){I(a===N)a="";J.17=a;K b=J.3Y("T");b.3X=J.1H(a);J.V("16")&&w(p(b,".16"),"5c",e.16.2b);J.V("3V-17")&&w(p(b,".17"),"56",f);H b},2Q:6(a){J.1c=""+1Q.5d(1Q.5n()*5k).1q();e.1Y.2A[t(J.1c)]=J;J.1n=C(e.2v,a||{});I(J.V("2k")==R)J.1n.16=J.1n.1u=11},5j:6(a){a=a.Q(/^\\s+|\\s+$/g,"").Q(/\\s+/g,"|");H"\\\\b(?:"+a+")\\\\b"},5f:6(a){J.28={18:{1I:a.18,23:"1k"},1b:{1I:a.1b,23:"1k"},17:1f M("(?<18>"+a.18.1m+")(?<17>.*?)(?<1b>"+a.1b.1m+")","5o")}}};H e}();1j 2e!="1d"&&(2e.1v=1v);',62,441,'||||||function|||||||||||||||||||||||||||||||||||||return|if|this|var|length|XRegExp|null|for|index|replace|true||div|push|getParam|call|exec|else|prototype||false|lastIndex|config|arguments|RegExp|toolbar|code|left|captureNames|slice|right|id|undefined|split|new|class|addToken|indexOf|typeof|script|className|source|params|substr|apply|toString|String|line|title|gutter|SyntaxHighlighter|_xregexp|strings|lt|html|test|OUTSIDE_CLASS|match|brush|document|target|gt|getHtml|regex|global|join|style|highlight|break|concat|window|Math|isRegExp|throw|value|brushes|brushName|space|alert|vars|http|syntaxhighlighter|expandSource|size|css|case|font|Fa|name|htmlScript|dA|can|handler|gm|td|exports|color|in|href|first|discoveredBrushes|light|collapse|object|cache|getButtonHtml|trigger|pattern|getLineHtml|nbsp|numbers|parseInt|defaults|com|items|www|pad|highlighters|execute|focus|func|all|getDiv|parentNode|navigator|INSIDE_CLASS|regexList|hasFlag|Match|useScriptTags|hasNamedCapture|text|help|init|br|input|gi|Error|values|span|list|250|height|width|screen|top|500|tagName|findElements|getElementsByTagName|aboutDialog|_blank|appendChild|charAt|Array|copyAsGlobal|setFlag|highlighter_|string|attachEvent|nodeName|floor|backref|output|the|TypeError|sticky|Za|iterate|freezeTokens|scope|type|textarea|alexgorbatchev|version|margin|2010|005896|gs|regexLib|body|center|align|noBrush|require|childNodes|DTD|xhtml1|head|org|w3|url|preventDefault|container|tr|getLineNumbersHtml|isNaN|userAgent|tbody|isLineHighlighted|quick|void|innerHTML|create|table|links|auto|smart|tab|stripBrs|tabs|bloggerMode|collapsed|plain|getCodeLinesHtml|caption|getMatchesHtml|findMatches|figureOutLineNumbers|removeNestedMatches|getTitleHtml|brushNotHtmlScript|substring|createElement|Highlighter|load|HtmlScript|Brush|pre|expand|multiline|min|Can|ignoreCase|find|blur|extended|toLowerCase|aliases|addEventListener|innerText|textContent|wasn|select|createTextNode|removeChild|option|same|frame|xmlns|dtd|twice|1999|equiv|meta|htmlscript|transitional|1E3|expected|PUBLIC|DOCTYPE|on|W3C|XHTML|TR|EN|Transitional||configured|srcElement|Object|after|run|dblclick|matchChain|valueOf|constructor|default|switch|click|round|execAt|forHtmlScript|token|gimy|functions|getKeywords|1E6|escape|within|random|sgi|another|finally|supply|MSIE|ie|toUpperCase|catch|returnValue|definition|event|border|imsx|constructing|one|Infinity|from|when|Content|cellpadding|flags|cellspacing|try|xhtml|Type|spaces|2930402|hosted_button_id|lastIndexOf|donate|active|development|keep|to|xclick|_s|Xml|please|like|you|paypal|cgi|cmd|webscr|bin|highlighted|scrollbars|aspScriptTags|phpScriptTags|sort|max|scriptScriptTags|toolbar_item|_|command|command_|number|getElementById|doubleQuotedString|singleLinePerlComments|singleLineCComments|multiLineCComments|singleQuotedString|multiLineDoubleQuotedString|xmlComments|alt|multiLineSingleQuotedString|If|https|1em|000|fff|background|5em|xx|bottom|75em|Gorbatchev|large|serif|CDATA|continue|utf|charset|content|About|family|sans|Helvetica|Arial|Geneva|3em|nogutter|Copyright|syntax|close|write|2004|Alex|open|JavaScript|highlighter|July|02|replaceChild|offset|83'.split('|'),0,{})) diff --git a/includes/kohana/modules/userguide/media/guide/js/sizzle.js b/includes/kohana/modules/userguide/media/guide/js/sizzle.js new file mode 100644 index 0000000..c52b77d --- /dev/null +++ b/includes/kohana/modules/userguide/media/guide/js/sizzle.js @@ -0,0 +1,1068 @@ +/*! + * Sizzle CSS Selector Engine - v1.0 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function(){ + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function(selector, context, results, seed) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context), + soFar = selector, ret, cur, pop, i; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec(""); + m = chunker.exec(soFar); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set ); + } + } + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray(set); + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function(results){ + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort(sortOrder); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[i-1] ) { + results.splice(i--, 1); + } + } + } + } + + return results; +}; + +Sizzle.matches = function(expr, set){ + return Sizzle(expr, null, null, set); +}; + +Sizzle.find = function(expr, context, isXML){ + var set; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var type = Expr.order[i], match; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice(1,1); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace(/\\/g, ""); + set = Expr.find[ type ]( match, context, isXML ); + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = context.getElementsByTagName("*"); + } + + return {set: set, expr: expr}; +}; + +Sizzle.filter = function(expr, set, inplace, not){ + var old = expr, result = [], curLoop = set, match, anyFound, + isXMLFilter = set && set[0] && Sizzle.isXML(set[0]); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + var filter = Expr.filter[ type ], found, item, left = match[1]; + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + } else { + curLoop[i] = false; + } + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + leftMatch: {}, + attrMap: { + "class": "className", + "for": "htmlFor" + }, + attrHandle: { + href: function(elem){ + return elem.getAttribute("href"); + } + }, + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !/\W/.test(part), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + ">": function(checkSet, part){ + var isPartStr = typeof part === "string", + elem, i = 0, l = checkSet.length; + + if ( isPartStr && !/\W/.test(part) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + "": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck, nodeCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); + }, + "~": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck, nodeCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); + } + }, + find: { + ID: function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? [m] : []; + } + }, + NAME: function(match, context){ + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], results = context.getElementsByName(match[1]); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + TAG: function(match, context){ + return context.getElementsByTagName(match[1]); + } + }, + preFilter: { + CLASS: function(match, curLoop, inplace, result, not, isXML){ + match = " " + match[1].replace(/\\/g, "") + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + ID: function(match){ + return match[1].replace(/\\/g, ""); + }, + TAG: function(match, curLoop){ + return match[1].toLowerCase(); + }, + CHILD: function(match){ + if ( match[1] === "nth" ) { + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + ATTR: function(match, curLoop, inplace, result, not, isXML){ + var name = match[1].replace(/\\/g, ""); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + PSEUDO: function(match, curLoop, inplace, result, not){ + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + if ( !inplace ) { + result.push.apply( result, ret ); + } + return false; + } + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + POS: function(match){ + match.unshift( true ); + return match; + } + }, + filters: { + enabled: function(elem){ + return elem.disabled === false && elem.type !== "hidden"; + }, + disabled: function(elem){ + return elem.disabled === true; + }, + checked: function(elem){ + return elem.checked === true; + }, + selected: function(elem){ + // Accessing this property makes selected-by-default + // options in Safari work properly + elem.parentNode.selectedIndex; + return elem.selected === true; + }, + parent: function(elem){ + return !!elem.firstChild; + }, + empty: function(elem){ + return !elem.firstChild; + }, + has: function(elem, i, match){ + return !!Sizzle( match[3], elem ).length; + }, + header: function(elem){ + return (/h\d/i).test( elem.nodeName ); + }, + text: function(elem){ + return "text" === elem.type; + }, + radio: function(elem){ + return "radio" === elem.type; + }, + checkbox: function(elem){ + return "checkbox" === elem.type; + }, + file: function(elem){ + return "file" === elem.type; + }, + password: function(elem){ + return "password" === elem.type; + }, + submit: function(elem){ + return "submit" === elem.type; + }, + image: function(elem){ + return "image" === elem.type; + }, + reset: function(elem){ + return "reset" === elem.type; + }, + button: function(elem){ + return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; + }, + input: function(elem){ + return (/input|select|textarea|button/i).test(elem.nodeName); + } + }, + setFilters: { + first: function(elem, i){ + return i === 0; + }, + last: function(elem, i, match, array){ + return i === array.length - 1; + }, + even: function(elem, i){ + return i % 2 === 0; + }, + odd: function(elem, i){ + return i % 2 === 1; + }, + lt: function(elem, i, match){ + return i < match[3] - 0; + }, + gt: function(elem, i, match){ + return i > match[3] - 0; + }, + nth: function(elem, i, match){ + return match[3] - 0 === i; + }, + eq: function(elem, i, match){ + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function(elem, match, i, array){ + var name = match[1], filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + } else { + Sizzle.error( "Syntax error, unrecognized expression: " + name ); + } + }, + CHILD: function(elem, match){ + var type = match[1], node = elem; + switch (type) { + case 'only': + case 'first': + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + if ( type === "first" ) { + return true; + } + node = elem; + case 'last': + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + return true; + case 'nth': + var first = match[2], last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + if ( first === 0 ) { + return diff === 0; + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + ID: function(elem, match){ + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + TAG: function(elem, match){ + return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; + }, + CLASS: function(elem, match){ + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + ATTR: function(elem, match){ + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + POS: function(elem, match, i, array){ + var name = match[2], filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function(array, results) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch(e){ + makeArray = function(array, results) { + var ret = results || [], i = 0; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.compareDocumentPosition ? -1 : 1; + } + + var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( "sourceIndex" in document.documentElement ) { + sortOrder = function( a, b ) { + if ( !a.sourceIndex || !b.sourceIndex ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.sourceIndex ? -1 : 1; + } + + var ret = a.sourceIndex - b.sourceIndex; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( document.createRange ) { + sortOrder = function( a, b ) { + if ( !a.ownerDocument || !b.ownerDocument ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.ownerDocument ? -1 : 1; + } + + var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); + aRange.setStart(a, 0); + aRange.setEnd(a, 0); + bRange.setStart(b, 0); + bRange.setEnd(b, 0); + var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} + +// Utility function for retreiving the text value of an array of DOM nodes +Sizzle.getText = function( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += Sizzle.getText( elem.childNodes ); + } + } + + return ret; +}; + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(); + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + var root = document.documentElement; + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; + } + }; + + Expr.filter.ID = function(elem, match){ + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + root = form = null; // release memory in IE +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function(match, context){ + var results = context.getElementsByTagName(match[1]); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + Expr.attrHandle.href = function(elem){ + return elem.getAttribute("href", 2); + }; + } + + div = null; // release memory in IE +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, div = document.createElement("div"); + div.innerHTML = "

    "; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function(query, context, extra, seed){ + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) { + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(e){} + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + div = null; // release memory in IE + })(); +} + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
    "; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function(match, context, isXML) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + div = null; // release memory in IE +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +Sizzle.contains = document.compareDocumentPosition ? function(a, b){ + return !!(a.compareDocumentPosition(b) & 16); +} : function(a, b){ + return a !== b && (a.contains ? a.contains(b) : true); +}; + +Sizzle.isXML = function(elem){ + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function(selector, context){ + var tmpSet = [], later = "", match, + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE + +window.Sizzle = Sizzle; + +})(); diff --git a/includes/kohana/modules/userguide/media/guide/userguide/contrib-github-edit.png b/includes/kohana/modules/userguide/media/guide/userguide/contrib-github-edit.png new file mode 100755 index 0000000000000000000000000000000000000000..b90eb91a2994f4289f85899fba6f70a9ced1b671 GIT binary patch literal 9681 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 literal 0 HcmV?d00001 diff --git a/includes/kohana/modules/userguide/media/guide/userguide/contrib-github-fork.png b/includes/kohana/modules/userguide/media/guide/userguide/contrib-github-fork.png new file mode 100755 index 0000000000000000000000000000000000000000..a557b834137080af100beca13a787d652862bace GIT binary patch literal 8278 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 YPaAUG{B0TnhyDO*aRsp&5yPPW2hao!M*si- literal 0 HcmV?d00001 diff --git a/includes/kohana/modules/userguide/media/guide/userguide/contrib-github-pull.png b/includes/kohana/modules/userguide/media/guide/userguide/contrib-github-pull.png new file mode 100755 index 0000000000000000000000000000000000000000..e2bc6021aaa555dcbdb6f174220a7101dd366819 GIT binary patch literal 8839 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 array( + 'de-de' => 'Deutsch', + 'en-us' => 'English', + 'es-es' => 'Español', + 'zh-cn' => '简体中文', + 'ru-ru' => 'Русский', + 'fr-fr' => 'Français', + 'he-il' => 'עברית', + 'nl' => 'Nederlands', + ), +); diff --git a/includes/kohana/modules/userguide/vendor/markdown/License.text b/includes/kohana/modules/userguide/vendor/markdown/License.text new file mode 100755 index 0000000..52c868b --- /dev/null +++ b/includes/kohana/modules/userguide/vendor/markdown/License.text @@ -0,0 +1,36 @@ +PHP Markdown & Extra +Copyright (c) 2004-2008 Michel Fortin + +All rights reserved. + +Based on Markdown +Copyright (c) 2003-2006 John Gruber + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name "Markdown" nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as +is" and any express or implied warranties, including, but not limited +to, the implied warranties of merchantability and fitness for a +particular purpose are disclaimed. In no event shall the copyright owner +or contributors be liable for any direct, indirect, incidental, special, +exemplary, or consequential damages (including, but not limited to, +procurement of substitute goods or services; loss of use, data, or +profits; or business interruption) however caused and on any theory of +liability, whether in contract, strict liability, or tort (including +negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. diff --git a/includes/kohana/modules/userguide/vendor/markdown/markdown.php b/includes/kohana/modules/userguide/vendor/markdown/markdown.php new file mode 100755 index 0000000..b649f6c --- /dev/null +++ b/includes/kohana/modules/userguide/vendor/markdown/markdown.php @@ -0,0 +1,2909 @@ + +# +# Original Markdown +# Copyright (c) 2004-2006 John Gruber +# +# + + +define( 'MARKDOWN_VERSION', "1.0.1m" ); # Sat 21 Jun 2008 +define( 'MARKDOWNEXTRA_VERSION', "1.2.3" ); # Wed 31 Dec 2008 + + +# +# Global default settings: +# + +# Change to ">" for HTML output +@define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />"); + +# Define the width of a tab for code blocks. +@define( 'MARKDOWN_TAB_WIDTH', 4 ); + +# Optional title attribute for footnote links and backlinks. +@define( 'MARKDOWN_FN_LINK_TITLE', "" ); +@define( 'MARKDOWN_FN_BACKLINK_TITLE', "" ); + +# Optional class attribute for footnote links and backlinks. +@define( 'MARKDOWN_FN_LINK_CLASS', "" ); +@define( 'MARKDOWN_FN_BACKLINK_CLASS', "" ); + + +# +# WordPress settings: +# + +# Change to false to remove Markdown from posts and/or comments. +@define( 'MARKDOWN_WP_POSTS', true ); +@define( 'MARKDOWN_WP_COMMENTS', true ); + + + +### Standard Function Interface ### + +@define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' ); + +function Markdown($text) { +# +# Initialize the parser and return the result of its transform method. +# + # Setup static parser variable. + static $parser; + if (!isset($parser)) { + $parser_class = MARKDOWN_PARSER_CLASS; + $parser = new $parser_class; + } + + # Transform text using parser. + return $parser->transform($text); +} + + +### WordPress Plugin Interface ### + +/* +Plugin Name: Markdown Extra +Plugin URI: http://www.michelf.com/projects/php-markdown/ +Description: Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More... +Version: 1.2.2 +Author: Michel Fortin +Author URI: http://www.michelf.com/ +*/ + +if (isset($wp_version)) { + # More details about how it works here: + # + + # Post content and excerpts + # - Remove WordPress paragraph generator. + # - Run Markdown on excerpt, then remove all tags. + # - Add paragraph tag around the excerpt, but remove it for the excerpt rss. + if (MARKDOWN_WP_POSTS) { + remove_filter('the_content', 'wpautop'); + remove_filter('the_content_rss', 'wpautop'); + remove_filter('the_excerpt', 'wpautop'); + add_filter('the_content', 'mdwp_MarkdownPost', 6); + add_filter('the_content_rss', 'mdwp_MarkdownPost', 6); + add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6); + add_filter('get_the_excerpt', 'trim', 7); + add_filter('the_excerpt', 'mdwp_add_p'); + add_filter('the_excerpt_rss', 'mdwp_strip_p'); + + remove_filter('content_save_pre', 'balanceTags', 50); + remove_filter('excerpt_save_pre', 'balanceTags', 50); + add_filter('the_content', 'balanceTags', 50); + add_filter('get_the_excerpt', 'balanceTags', 9); + } + + # Add a footnote id prefix to posts when inside a loop. + function mdwp_MarkdownPost($text) { + static $parser; + if (!$parser) { + $parser_class = MARKDOWN_PARSER_CLASS; + $parser = new $parser_class; + } + if (is_single() || is_page() || is_feed()) { + $parser->fn_id_prefix = ""; + } else { + $parser->fn_id_prefix = get_the_ID() . "."; + } + return $parser->transform($text); + } + + # Comments + # - Remove WordPress paragraph generator. + # - Remove WordPress auto-link generator. + # - Scramble important tags before passing them to the kses filter. + # - Run Markdown on excerpt then remove paragraph tags. + if (MARKDOWN_WP_COMMENTS) { + remove_filter('comment_text', 'wpautop', 30); + remove_filter('comment_text', 'make_clickable'); + add_filter('pre_comment_content', 'Markdown', 6); + add_filter('pre_comment_content', 'mdwp_hide_tags', 8); + add_filter('pre_comment_content', 'mdwp_show_tags', 12); + add_filter('get_comment_text', 'Markdown', 6); + add_filter('get_comment_excerpt', 'Markdown', 6); + add_filter('get_comment_excerpt', 'mdwp_strip_p', 7); + + global $mdwp_hidden_tags, $mdwp_placeholders; + $mdwp_hidden_tags = explode(' ', + '

     
  • '); + $mdwp_placeholders = explode(' ', str_rot13( + 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '. + 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli')); + } + + function mdwp_add_p($text) { + if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) { + $text = '

    '.$text.'

    '; + $text = preg_replace('{\n{2,}}', "

    \n\n

    ", $text); + } + return $text; + } + + function mdwp_strip_p($t) { return preg_replace('{}i', '', $t); } + + function mdwp_hide_tags($text) { + global $mdwp_hidden_tags, $mdwp_placeholders; + return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text); + } + function mdwp_show_tags($text) { + global $mdwp_hidden_tags, $mdwp_placeholders; + return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text); + } +} + + +### bBlog Plugin Info ### + +function identify_modifier_markdown() { + return array( + 'name' => 'markdown', + 'type' => 'modifier', + 'nicename' => 'PHP Markdown Extra', + 'description' => 'A text-to-HTML conversion tool for web writers', + 'authors' => 'Michel Fortin and John Gruber', + 'licence' => 'GPL', + 'version' => MARKDOWNEXTRA_VERSION, + 'help' => 'Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More...', + ); +} + + +### Smarty Modifier Interface ### + +function smarty_modifier_markdown($text) { + return Markdown($text); +} + + +### Textile Compatibility Mode ### + +# Rename this file to "classTextile.php" and it can replace Textile everywhere. + +if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) { + # Try to include PHP SmartyPants. Should be in the same directory. + @include_once 'smartypants.php'; + # Fake Textile class. It calls Markdown instead. + class Textile { + function TextileThis($text, $lite='', $encode='') { + if ($lite == '' && $encode == '') $text = Markdown($text); + if (function_exists('SmartyPants')) $text = SmartyPants($text); + return $text; + } + # Fake restricted version: restrictions are not supported for now. + function TextileRestricted($text, $lite='', $noimage='') { + return $this->TextileThis($text, $lite); + } + # Workaround to ensure compatibility with TextPattern 4.0.3. + function blockLite($text) { return $text; } + } +} + + + +# +# Markdown Parser Class +# + +class Markdown_Parser { + + # Regex to match balanced [brackets]. + # Needed to insert a maximum bracked depth while converting to PHP. + var $nested_brackets_depth = 6; + var $nested_brackets_re; + + var $nested_url_parenthesis_depth = 4; + var $nested_url_parenthesis_re; + + # Table of hash values for escaped characters: + var $escape_chars = '\`*_{}[]()>#+-.!'; + var $escape_chars_re; + + # Change to ">" for HTML output. + var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; + var $tab_width = MARKDOWN_TAB_WIDTH; + + # Change to `true` to disallow markup or entities. + var $no_markup = false; + var $no_entities = false; + + # Predefined urls and titles for reference links and images. + var $predef_urls = array(); + var $predef_titles = array(); + + + function Markdown_Parser() { + # + # Constructor function. Initialize appropriate member variables. + # + $this->_initDetab(); + $this->prepareItalicsAndBold(); + + $this->nested_brackets_re = + str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). + str_repeat('\])*', $this->nested_brackets_depth); + + $this->nested_url_parenthesis_re = + str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). + str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); + + $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; + + # Sort document, block, and span gamut in ascendent priority order. + asort($this->document_gamut); + asort($this->block_gamut); + asort($this->span_gamut); + } + + + # Internal hashes used during transformation. + var $urls = array(); + var $titles = array(); + var $html_hashes = array(); + + # Status flag to avoid invalid nesting. + var $in_anchor = false; + + + function setup() { + # + # Called before the transformation process starts to setup parser + # states. + # + # Clear global hashes. + $this->urls = $this->predef_urls; + $this->titles = $this->predef_titles; + $this->html_hashes = array(); + + $in_anchor = false; + } + + function teardown() { + # + # Called after the transformation process to clear any variable + # which may be taking up memory unnecessarly. + # + $this->urls = array(); + $this->titles = array(); + $this->html_hashes = array(); + } + + + function transform($text) { + # + # Main function. Performs some preprocessing on the input text + # and pass it through the document gamut. + # + $this->setup(); + + # Remove UTF-8 BOM and marker character in input, if present. + $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); + + # Standardize line endings: + # DOS to Unix and Mac to Unix + $text = preg_replace('{\r\n?}', "\n", $text); + + # Make sure $text ends with a couple of newlines: + $text .= "\n\n"; + + # Convert all tabs to spaces. + $text = $this->detab($text); + + # Turn block-level HTML blocks into hash entries + $text = $this->hashHTMLBlocks($text); + + # Strip any lines consisting only of spaces and tabs. + # This makes subsequent regexen easier to write, because we can + # match consecutive blank lines with /\n+/ instead of something + # contorted like /[ ]*\n+/ . + $text = preg_replace('/^[ ]+$/m', '', $text); + + # Run document gamut methods. + foreach ($this->document_gamut as $method => $priority) { + $text = $this->$method($text); + } + + $this->teardown(); + + return $text . "\n"; + } + + var $document_gamut = array( + # Strip link definitions, store in hashes. + "stripLinkDefinitions" => 20, + + "runBasicBlockGamut" => 30, + ); + + + function stripLinkDefinitions($text) { + # + # Strips link definitions from text, stores the URLs and titles in + # hash references. + # + $less_than_tab = $this->tab_width - 1; + + # Link defs are in the form: ^[id]: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 + [ ]* + \n? # maybe *one* newline + [ ]* + ? # url = $2 + [ ]* + \n? # maybe one newline + [ ]* + (?: + (?<=\s) # lookbehind for whitespace + ["(] + (.*?) # title = $3 + [")] + [ ]* + )? # title is optional + (?:\n+|\Z) + }xm', + array(&$this, '_stripLinkDefinitions_callback'), + $text); + return $text; + } + function _stripLinkDefinitions_callback($matches) { + $link_id = strtolower($matches[1]); + $this->urls[$link_id] = $matches[2]; + $this->titles[$link_id] =& $matches[3]; + return ''; # String that will replace the block + } + + + function hashHTMLBlocks($text) { + if ($this->no_markup) return $text; + + $less_than_tab = $this->tab_width - 1; + + # Hashify HTML blocks: + # We only want to do this for block-level HTML tags, such as headers, + # lists, and tables. That's because we still want to wrap

    s around + # "paragraphs" that are wrapped in non-block-level tags, such as anchors, + # phrase emphasis, and spans. The list of tags we're looking for is + # hard-coded: + # + # * List "a" is made of tags which can be both inline or block-level. + # These will be treated block-level when the start tag is alone on + # its line, otherwise they're not matched here and will be taken as + # inline later. + # * List "b" is made of tags which are always block-level; + # + $block_tags_a_re = 'ins|del'; + $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. + 'script|noscript|form|fieldset|iframe|math'; + + # Regular expression for the content of a block tag. + $nested_tags_level = 4; + $attr = ' + (?> # optional tag attributes + \s # starts with whitespace + (?> + [^>"/]+ # text outside quotes + | + /+(?!>) # slash not followed by ">" + | + "[^"]*" # text inside double quotes (tolerate ">") + | + \'[^\']*\' # text inside single quotes (tolerate ">") + )* + )? + '; + $content = + str_repeat(' + (?> + [^<]+ # content without tag + | + <\2 # nested opening tag + '.$attr.' # attributes + (?> + /> + | + >', $nested_tags_level). # end of opening tag + '.*?'. # last level nested tag content + str_repeat(' + # closing nested tag + ) + | + <(?!/\2\s*> # other tags with a different name + ) + )*', + $nested_tags_level); + $content2 = str_replace('\2', '\3', $content); + + # First, look for nested blocks, e.g.: + #

    + #
    + # tags for inner block must be indented. + #
    + #
    + # + # The outermost tags must start at the left margin for this to match, and + # the inner nested divs must be indented. + # We need to do this before the next, more liberal match, because the next + # match will start at the first `
    ` and stop at the first `
    `. + $text = preg_replace_callback('{(?> + (?> + (?<=\n\n) # Starting after a blank line + | # or + \A\n? # the beginning of the doc + ) + ( # save in $1 + + # Match from `\n` to `\n`, handling nested tags + # in between. + + [ ]{0,'.$less_than_tab.'} + <('.$block_tags_b_re.')# start tag = $2 + '.$attr.'> # attributes followed by > and \n + '.$content.' # content, support nesting + # the matching end tag + [ ]* # trailing spaces/tabs + (?=\n+|\Z) # followed by a newline or end of document + + | # Special version for tags of group a. + + [ ]{0,'.$less_than_tab.'} + <('.$block_tags_a_re.')# start tag = $3 + '.$attr.'>[ ]*\n # attributes followed by > + '.$content2.' # content, support nesting + # the matching end tag + [ ]* # trailing spaces/tabs + (?=\n+|\Z) # followed by a newline or end of document + + | # Special case just for
    . It was easier to make a special + # case than to make the other regex more complicated. + + [ ]{0,'.$less_than_tab.'} + <(hr) # start tag = $2 + '.$attr.' # attributes + /?> # the matching end tag + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + | # Special case for standalone HTML comments: + + [ ]{0,'.$less_than_tab.'} + (?s: + + ) + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + | # PHP and ASP-style processor instructions ( + ) + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + ) + )}Sxmi', + array(&$this, '_hashHTMLBlocks_callback'), + $text); + + return $text; + } + function _hashHTMLBlocks_callback($matches) { + $text = $matches[1]; + $key = $this->hashBlock($text); + return "\n\n$key\n\n"; + } + + + function hashPart($text, $boundary = 'X') { + # + # Called whenever a tag must be hashed when a function insert an atomic + # element in the text stream. Passing $text to through this function gives + # a unique text-token which will be reverted back when calling unhash. + # + # The $boundary argument specify what character should be used to surround + # the token. By convension, "B" is used for block elements that needs not + # to be wrapped into paragraph tags at the end, ":" is used for elements + # that are word separators and "X" is used in the general case. + # + # Swap back any tag hash found in $text so we do not have to `unhash` + # multiple times at the end. + $text = $this->unhash($text); + + # Then hash the block. + static $i = 0; + $key = "$boundary\x1A" . ++$i . $boundary; + $this->html_hashes[$key] = $text; + return $key; # String that will replace the tag. + } + + + function hashBlock($text) { + # + # Shortcut function for hashPart with block-level boundaries. + # + return $this->hashPart($text, 'B'); + } + + + var $block_gamut = array( + # + # These are all the transformations that form block-level + # tags like paragraphs, headers, and list items. + # + "doHeaders" => 10, + "doHorizontalRules" => 20, + + "doLists" => 40, + "doCodeBlocks" => 50, + "doBlockQuotes" => 60, + ); + + function runBlockGamut($text) { + # + # Run block gamut tranformations. + # + # We need to escape raw HTML in Markdown source before doing anything + # else. This need to be done for each block, and not only at the + # begining in the Markdown function since hashed blocks can be part of + # list items and could have been indented. Indented blocks would have + # been seen as a code block in a previous pass of hashHTMLBlocks. + $text = $this->hashHTMLBlocks($text); + + return $this->runBasicBlockGamut($text); + } + + function runBasicBlockGamut($text) { + # + # Run block gamut tranformations, without hashing HTML blocks. This is + # useful when HTML blocks are known to be already hashed, like in the first + # whole-document pass. + # + foreach ($this->block_gamut as $method => $priority) { + $text = $this->$method($text); + } + + # Finally form paragraph and restore hashed blocks. + $text = $this->formParagraphs($text); + + return $text; + } + + + function doHorizontalRules($text) { + # Do Horizontal Rules: + return preg_replace( + '{ + ^[ ]{0,3} # Leading space + ([-*_]) # $1: First marker + (?> # Repeated marker group + [ ]{0,2} # Zero, one, or two spaces. + \1 # Marker character + ){2,} # Group repeated at least twice + [ ]* # Tailing spaces + $ # End of line. + }mx', + "\n".$this->hashBlock("empty_element_suffix")."\n", + $text); + } + + + var $span_gamut = array( + # + # These are all the transformations that occur *within* block-level + # tags like paragraphs, headers, and list items. + # + # Process character escapes, code spans, and inline HTML + # in one shot. + "parseSpan" => -30, + + # Process anchor and image tags. Images must come first, + # because ![foo][f] looks like an anchor. + "doImages" => 10, + "doAnchors" => 20, + + # Make links out of things like `` + # Must come after doAnchors, because you can use < and > + # delimiters in inline links like [this](). + "doAutoLinks" => 30, + "encodeAmpsAndAngles" => 40, + + "doItalicsAndBold" => 50, + "doHardBreaks" => 60, + ); + + function runSpanGamut($text) { + # + # Run span gamut tranformations. + # + foreach ($this->span_gamut as $method => $priority) { + $text = $this->$method($text); + } + + return $text; + } + + + function doHardBreaks($text) { + # Do hard breaks: + return preg_replace_callback('/ {2,}\n/', + array(&$this, '_doHardBreaks_callback'), $text); + } + function _doHardBreaks_callback($matches) { + return $this->hashPart("empty_element_suffix\n"); + } + + + function doAnchors($text) { + # + # Turn Markdown link shortcuts into XHTML tags. + # + if ($this->in_anchor) return $text; + $this->in_anchor = true; + + # + # First, handle reference-style links: [link text] [id] + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ('.$this->nested_brackets_re.') # link text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + ) + }xs', + array(&$this, '_doAnchors_reference_callback'), $text); + + # + # Next, inline-style links: [link text](url "optional title") + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ('.$this->nested_brackets_re.') # link text = $2 + \] + \( # literal paren + [ ]* + (?: + <(\S*)> # href = $3 + | + ('.$this->nested_url_parenthesis_re.') # href = $4 + ) + [ ]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # Title = $7 + \6 # matching quote + [ ]* # ignore any spaces/tabs between closing quote and ) + )? # title is optional + \) + ) + }xs', + array(&$this, '_DoAnchors_inline_callback'), $text); + + # + # Last, handle reference-style shortcuts: [link text] + # These must come last in case you've also got [link test][1] + # or [link test](/foo) + # +// $text = preg_replace_callback('{ +// ( # wrap whole match in $1 +// \[ +// ([^\[\]]+) # link text = $2; can\'t contain [ or ] +// \] +// ) +// }xs', +// array(&$this, '_doAnchors_reference_callback'), $text); + + $this->in_anchor = false; + return $text; + } + function _doAnchors_reference_callback($matches) { + $whole_match = $matches[1]; + $link_text = $matches[2]; + $link_id =& $matches[3]; + + if ($link_id == "") { + # for shortcut links like [this][] or [this]. + $link_id = $link_text; + } + + # lower-case and turn embedded newlines into spaces + $link_id = strtolower($link_id); + $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); + + if (isset($this->urls[$link_id])) { + $url = $this->urls[$link_id]; + $url = $this->encodeAttribute($url); + + $result = "titles[$link_id] ) ) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + $result = $this->hashPart($result); + } + else { + $result = $whole_match; + } + return $result; + } + function _doAnchors_inline_callback($matches) { + $whole_match = $matches[1]; + $link_text = $this->runSpanGamut($matches[2]); + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + + $url = $this->encodeAttribute($url); + + $result = "encodeAttribute($title); + $result .= " title=\"$title\""; + } + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + + return $this->hashPart($result); + } + + + function doImages($text) { + # + # Turn Markdown image shortcuts into tags. + # + # + # First, handle reference-style labeled images: ![alt text][id] + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + ('.$this->nested_brackets_re.') # alt text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + + ) + }xs', + array(&$this, '_doImages_reference_callback'), $text); + + # + # Next, handle inline images: ![alt text](url "optional title") + # Don't forget: encode * and _ + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + ('.$this->nested_brackets_re.') # alt text = $2 + \] + \s? # One optional whitespace character + \( # literal paren + [ ]* + (?: + <(\S*)> # src url = $3 + | + ('.$this->nested_url_parenthesis_re.') # src url = $4 + ) + [ ]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # title = $7 + \6 # matching quote + [ ]* + )? # title is optional + \) + ) + }xs', + array(&$this, '_doImages_inline_callback'), $text); + + return $text; + } + function _doImages_reference_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $link_id = strtolower($matches[3]); + + if ($link_id == "") { + $link_id = strtolower($alt_text); # for shortcut links like ![this][]. + } + + $alt_text = $this->encodeAttribute($alt_text); + if (isset($this->urls[$link_id])) { + $url = $this->encodeAttribute($this->urls[$link_id]); + $result = "\"$alt_text\"";titles[$link_id])) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + $result .= $this->empty_element_suffix; + $result = $this->hashPart($result); + } + else { + # If there's no such link ID, leave intact: + $result = $whole_match; + } + + return $result; + } + function _doImages_inline_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + + $alt_text = $this->encodeAttribute($alt_text); + $url = $this->encodeAttribute($url); + $result = "\"$alt_text\"";encodeAttribute($title); + $result .= " title=\"$title\""; # $title already quoted + } + $result .= $this->empty_element_suffix; + + return $this->hashPart($result); + } + + + function doHeaders($text) { + # Setext-style headers: + # Header 1 + # ======== + # + # Header 2 + # -------- + # + $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', + array(&$this, '_doHeaders_callback_setext'), $text); + + # atx-style headers: + # # Header 1 + # ## Header 2 + # ## Header 2 with closing hashes ## + # ... + # ###### Header 6 + # + $text = preg_replace_callback('{ + ^(\#{1,6}) # $1 = string of #\'s + [ ]* + (.+?) # $2 = Header text + [ ]* + \#* # optional closing #\'s (not counted) + \n+ + }xm', + array(&$this, '_doHeaders_callback_atx'), $text); + + return $text; + } + function _doHeaders_callback_setext($matches) { + # Terrible hack to check we haven't found an empty list item. + if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) + return $matches[0]; + + $level = $matches[2]{0} == '=' ? 1 : 2; + $block = "".$this->runSpanGamut($matches[1]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + function _doHeaders_callback_atx($matches) { + $level = strlen($matches[1]); + $block = "".$this->runSpanGamut($matches[2]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + + function doLists($text) { + # + # Form HTML ordered (numbered) and unordered (bulleted) lists. + # + $less_than_tab = $this->tab_width - 1; + + # Re-usable patterns to match list item bullets and number markers: + $marker_ul_re = '[*+-]'; + $marker_ol_re = '\d+[.]'; + $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; + + $markers_relist = array($marker_ul_re, $marker_ol_re); + + foreach ($markers_relist as $marker_re) { + # Re-usable pattern to match any entirel ul or ol list: + $whole_list_re = ' + ( # $1 = whole list + ( # $2 + [ ]{0,'.$less_than_tab.'} + ('.$marker_re.') # $3 = first list item marker + [ ]+ + ) + (?s:.+?) + ( # $4 + \z + | + \n{2,} + (?=\S) + (?! # Negative lookahead for another list item marker + [ ]* + '.$marker_re.'[ ]+ + ) + ) + ) + '; // mx + + # We use a different prefix before nested lists than top-level lists. + # See extended comment in _ProcessListItems(). + + if ($this->list_level) { + $text = preg_replace_callback('{ + ^ + '.$whole_list_re.' + }mx', + array(&$this, '_doLists_callback'), $text); + } + else { + $text = preg_replace_callback('{ + (?:(?<=\n)\n|\A\n?) # Must eat the newline + '.$whole_list_re.' + }mx', + array(&$this, '_doLists_callback'), $text); + } + } + + return $text; + } + function _doLists_callback($matches) { + # Re-usable patterns to match list item bullets and number markers: + $marker_ul_re = '[*+-]'; + $marker_ol_re = '\d+[.]'; + $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; + + $list = $matches[1]; + $list_type = preg_match("/$marker_ul_re/", $matches[3]) ? "ul" : "ol"; + + $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); + + $list .= "\n"; + $result = $this->processListItems($list, $marker_any_re); + + $result = $this->hashBlock("<$list_type>\n" . $result . ""); + return "\n". $result ."\n\n"; + } + + var $list_level = 0; + + function processListItems($list_str, $marker_any_re) { + # + # Process the contents of a single ordered or unordered list, splitting it + # into individual list items. + # + # The $this->list_level global keeps track of when we're inside a list. + # Each time we enter a list, we increment it; when we leave a list, + # we decrement. If it's zero, we're not in a list anymore. + # + # We do this because when we're not inside a list, we want to treat + # something like this: + # + # I recommend upgrading to version + # 8. Oops, now this line is treated + # as a sub-list. + # + # As a single paragraph, despite the fact that the second line starts + # with a digit-period-space sequence. + # + # Whereas when we're inside a list (or sub-list), that line will be + # treated as the start of a sub-list. What a kludge, huh? This is + # an aspect of Markdown's syntax that's hard to parse perfectly + # without resorting to mind-reading. Perhaps the solution is to + # change the syntax rules such that sub-lists must start with a + # starting cardinal number; e.g. "1." or "a.". + + $this->list_level++; + + # trim trailing blank lines: + $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); + + $list_str = preg_replace_callback('{ + (\n)? # leading line = $1 + (^[ ]*) # leading whitespace = $2 + ('.$marker_any_re.' # list marker and space = $3 + (?:[ ]+|(?=\n)) # space only required if item is not empty + ) + ((?s:.*?)) # list item text = $4 + (?:(\n+(?=\n))|\n) # tailing blank line = $5 + (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) + }xm', + array(&$this, '_processListItems_callback'), $list_str); + + $this->list_level--; + return $list_str; + } + function _processListItems_callback($matches) { + $item = $matches[4]; + $leading_line =& $matches[1]; + $leading_space =& $matches[2]; + $marker_space = $matches[3]; + $tailing_blank_line =& $matches[5]; + + if ($leading_line || $tailing_blank_line || + preg_match('/\n{2,}/', $item)) + { + # Replace marker with the appropriate whitespace indentation + $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; + $item = $this->runBlockGamut($this->outdent($item)."\n"); + } + else { + # Recursion for sub-lists: + $item = $this->doLists($this->outdent($item)); + $item = preg_replace('/\n+$/', '', $item); + $item = $this->runSpanGamut($item); + } + + return "
  • " . $item . "
  • \n"; + } + + + function doCodeBlocks($text) { + # + # Process Markdown `
    ` blocks.
    +	#
    +		$text = preg_replace_callback('{
    +				(?:\n\n|\A\n?)
    +				(	            # $1 = the code block -- one or more lines, starting with a space/tab
    +				  (?>
    +					[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
    +					.*\n+
    +				  )+
    +				)
    +				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
    +			}xm',
    +			array(&$this, '_doCodeBlocks_callback'), $text);
    +
    +		return $text;
    +	}
    +	function _doCodeBlocks_callback($matches) {
    +		$codeblock = $matches[1];
    +
    +		$codeblock = $this->outdent($codeblock);
    +		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
    +
    +		# trim leading newlines and trailing newlines
    +		$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
    +
    +		$codeblock = "
    $codeblock\n
    "; + return "\n\n".$this->hashBlock($codeblock)."\n\n"; + } + + + function makeCodeSpan($code) { + # + # Create a code span markup for $code. Called from handleSpanToken. + # + $code = htmlspecialchars(trim($code), ENT_NOQUOTES); + return $this->hashPart("$code"); + } + + + var $em_relist = array( + '' => '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(?em_relist as $em => $em_re) { + foreach ($this->strong_relist as $strong => $strong_re) { + # Construct list of allowed token expressions. + $token_relist = array(); + if (isset($this->em_strong_relist["$em$strong"])) { + $token_relist[] = $this->em_strong_relist["$em$strong"]; + } + $token_relist[] = $em_re; + $token_relist[] = $strong_re; + + # Construct master expression from list. + $token_re = '{('. implode('|', $token_relist) .')}'; + $this->em_strong_prepared_relist["$em$strong"] = $token_re; + } + } + } + + function doItalicsAndBold($text) { + $token_stack = array(''); + $text_stack = array(''); + $em = ''; + $strong = ''; + $tree_char_em = false; + + while (1) { + # + # Get prepared regular expression for seraching emphasis tokens + # in current context. + # + $token_re = $this->em_strong_prepared_relist["$em$strong"]; + + # + # Each loop iteration seach for the next emphasis token. + # Each token is then passed to handleSpanToken. + # + $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); + $text_stack[0] .= $parts[0]; + $token =& $parts[1]; + $text =& $parts[2]; + + if (empty($token)) { + # Reached end of text span: empty stack without emitting. + # any more emphasis. + while ($token_stack[0]) { + $text_stack[1] .= array_shift($token_stack); + $text_stack[0] .= array_shift($text_stack); + } + break; + } + + $token_len = strlen($token); + if ($tree_char_em) { + # Reached closing marker while inside a three-char emphasis. + if ($token_len == 3) { + # Three-char closing marker, close em and strong. + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $em = ''; + $strong = ''; + } else { + # Other closing marker: close one em or strong and + # change current token state to match the other + $token_stack[0] = str_repeat($token{0}, 3-$token_len); + $tag = $token_len == 2 ? "strong" : "em"; + $span = $text_stack[0]; + $span = $this->runSpanGamut($span); + $span = "<$tag>$span"; + $text_stack[0] = $this->hashPart($span); + $$tag = ''; # $$tag stands for $em or $strong + } + $tree_char_em = false; + } else if ($token_len == 3) { + if ($em) { + # Reached closing marker for both em and strong. + # Closing strong marker: + for ($i = 0; $i < 2; ++$i) { + $shifted_token = array_shift($token_stack); + $tag = strlen($shifted_token) == 2 ? "strong" : "em"; + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "<$tag>$span"; + $text_stack[0] .= $this->hashPart($span); + $$tag = ''; # $$tag stands for $em or $strong + } + } else { + # Reached opening three-char emphasis marker. Push on token + # stack; will be handled by the special condition above. + $em = $token{0}; + $strong = "$em$em"; + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $tree_char_em = true; + } + } else if ($token_len == 2) { + if ($strong) { + # Unwind any dangling emphasis marker: + if (strlen($token_stack[0]) == 1) { + $text_stack[1] .= array_shift($token_stack); + $text_stack[0] .= array_shift($text_stack); + } + # Closing strong marker: + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $strong = ''; + } else { + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $strong = $token; + } + } else { + # Here $token_len == 1 + if ($em) { + if (strlen($token_stack[0]) == 1) { + # Closing emphasis marker: + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $em = ''; + } else { + $text_stack[0] .= $token; + } + } else { + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $em = $token; + } + } + } + return $text_stack[0]; + } + + + function doBlockQuotes($text) { + $text = preg_replace_callback('/ + ( # Wrap whole match in $1 + (?> + ^[ ]*>[ ]? # ">" at the start of a line + .+\n # rest of the first line + (.+\n)* # subsequent consecutive lines + \n* # blanks + )+ + ) + /xm', + array(&$this, '_doBlockQuotes_callback'), $text); + + return $text; + } + function _doBlockQuotes_callback($matches) { + $bq = $matches[1]; + # trim one level of quoting - trim whitespace-only lines + $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); + $bq = $this->runBlockGamut($bq); # recurse + + $bq = preg_replace('/^/m', " ", $bq); + # These leading spaces cause problem with
     content, 
    +		# so we need to fix that:
    +		$bq = preg_replace_callback('{(\s*
    .+?
    )}sx', + array(&$this, '_DoBlockQuotes_callback2'), $bq); + + return "\n". $this->hashBlock("
    \n$bq\n
    ")."\n\n"; + } + function _doBlockQuotes_callback2($matches) { + $pre = $matches[1]; + $pre = preg_replace('/^ /m', '', $pre); + return $pre; + } + + + function formParagraphs($text) { + # + # Params: + # $text - string to process with html

    tags + # + # Strip leading and trailing lines: + $text = preg_replace('/\A\n+|\n+\z/', '', $text); + + $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); + + # + # Wrap

    tags and unhashify HTML blocks + # + foreach ($grafs as $key => $value) { + if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { + # Is a paragraph. + $value = $this->runSpanGamut($value); + $value = preg_replace('/^([ ]*)/', "

    ", $value); + $value .= "

    "; + $grafs[$key] = $this->unhash($value); + } + else { + # Is a block. + # Modify elements of @grafs in-place... + $graf = $value; + $block = $this->html_hashes[$graf]; + $graf = $block; +// if (preg_match('{ +// \A +// ( # $1 =
    tag +//
    ]* +// \b +// markdown\s*=\s* ([\'"]) # $2 = attr quote char +// 1 +// \2 +// [^>]* +// > +// ) +// ( # $3 = contents +// .* +// ) +// (
    ) # $4 = closing tag +// \z +// }xs', $block, $matches)) +// { +// list(, $div_open, , $div_content, $div_close) = $matches; +// +// # We can't call Markdown(), because that resets the hash; +// # that initialization code should be pulled into its own sub, though. +// $div_content = $this->hashHTMLBlocks($div_content); +// +// # Run document gamut methods on the content. +// foreach ($this->document_gamut as $method => $priority) { +// $div_content = $this->$method($div_content); +// } +// +// $div_open = preg_replace( +// '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); +// +// $graf = $div_open . "\n" . $div_content . "\n" . $div_close; +// } + $grafs[$key] = $graf; + } + } + + return implode("\n\n", $grafs); + } + + + function encodeAttribute($text) { + # + # Encode text for a double-quoted HTML attribute. This function + # is *not* suitable for attributes enclosed in single quotes. + # + $text = $this->encodeAmpsAndAngles($text); + $text = str_replace('"', '"', $text); + return $text; + } + + + function encodeAmpsAndAngles($text) { + # + # Smart processing for ampersands and angle brackets that need to + # be encoded. Valid character entities are left alone unless the + # no-entities mode is set. + # + if ($this->no_entities) { + $text = str_replace('&', '&', $text); + } else { + # Ampersand-encoding based entirely on Nat Irons's Amputator + # MT plugin: + $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', + '&', $text);; + } + # Encode remaining <'s + $text = str_replace('<', '<', $text); + + return $text; + } + + + function doAutoLinks($text) { + $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', + array(&$this, '_doAutoLinks_url_callback'), $text); + + # Email addresses: + $text = preg_replace_callback('{ + < + (?:mailto:)? + ( + [-.\w\x80-\xFF]+ + \@ + [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ + ) + > + }xi', + array(&$this, '_doAutoLinks_email_callback'), $text); + + return $text; + } + function _doAutoLinks_url_callback($matches) { + $url = $this->encodeAttribute($matches[1]); + $link = "$url"; + return $this->hashPart($link); + } + function _doAutoLinks_email_callback($matches) { + $address = $matches[1]; + $link = $this->encodeEmailAddress($address); + return $this->hashPart($link); + } + + + function encodeEmailAddress($addr) { + # + # Input: an email address, e.g. "foo@example.com" + # + # Output: the email address as a mailto link, with each character + # of the address encoded as either a decimal or hex entity, in + # the hopes of foiling most address harvesting spam bots. E.g.: + # + #

    foo@exampl + # e.com

    + # + # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. + # With some optimizations by Milian Wolff. + # + $addr = "mailto:" . $addr; + $chars = preg_split('/(? $char) { + $ord = ord($char); + # Ignore non-ascii chars. + if ($ord < 128) { + $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. + # roughly 10% raw, 45% hex, 45% dec + # '@' *must* be encoded. I insist. + if ($r > 90 && $char != '@') /* do nothing */; + else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; + else $chars[$key] = '&#'.$ord.';'; + } + } + + $addr = implode('', $chars); + $text = implode('', array_slice($chars, 7)); # text without `mailto:` + $addr = "$text"; + + return $addr; + } + + + function parseSpan($str) { + # + # Take the string $str and parse it into tokens, hashing embeded HTML, + # escaped characters and handling code spans. + # + $output = ''; + + $span_re = '{ + ( + \\\\'.$this->escape_chars_re.' + | + (?no_markup ? '' : ' + | + # comment + | + <\?.*?\?> | <%.*?%> # processing instruction + | + <[/!$]?[-a-zA-Z0-9:]+ # regular tags + (?> + \s + (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* + )? + > + ').' + ) + }xs'; + + while (1) { + # + # Each loop iteration seach for either the next tag, the next + # openning code span marker, or the next escaped character. + # Each token is then passed to handleSpanToken. + # + $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); + + # Create token from text preceding tag. + if ($parts[0] != "") { + $output .= $parts[0]; + } + + # Check if we reach the end. + if (isset($parts[1])) { + $output .= $this->handleSpanToken($parts[1], $parts[2]); + $str = $parts[2]; + } + else { + break; + } + } + + return $output; + } + + + function handleSpanToken($token, &$str) { + # + # Handle $token provided by parseSpan by determining its nature and + # returning the corresponding value that should replace it. + # + switch ($token{0}) { + case "\\": + return $this->hashPart("&#". ord($token{1}). ";"); + case "`": + # Search for end marker in remaining text. + if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', + $str, $matches)) + { + $str = $matches[2]; + $codespan = $this->makeCodeSpan($matches[1]); + return $this->hashPart($codespan); + } + return $token; // return as text since no ending marker found. + default: + return $this->hashPart($token); + } + } + + + function outdent($text) { + # + # Remove one level of line-leading tabs or spaces + # + return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); + } + + + # String length function for detab. `_initDetab` will create a function to + # hanlde UTF-8 if the default function does not exist. + var $utf8_strlen = 'mb_strlen'; + + function detab($text) { + # + # Replace tabs with the appropriate amount of space. + # + # For each line we separate the line in blocks delemited by + # tab characters. Then we reconstruct every line by adding the + # appropriate number of space between each blocks. + + $text = preg_replace_callback('/^.*\t.*$/m', + array(&$this, '_detab_callback'), $text); + + return $text; + } + function _detab_callback($matches) { + $line = $matches[0]; + $strlen = $this->utf8_strlen; # strlen function for UTF-8. + + # Split in blocks. + $blocks = explode("\t", $line); + # Add each blocks to the line. + $line = $blocks[0]; + unset($blocks[0]); # Do not add first block twice. + foreach ($blocks as $block) { + # Calculate amount of space, insert spaces, insert block. + $amount = $this->tab_width - + $strlen($line, 'UTF-8') % $this->tab_width; + $line .= str_repeat(" ", $amount) . $block; + } + return $line; + } + function _initDetab() { + # + # Check for the availability of the function in the `utf8_strlen` property + # (initially `mb_strlen`). If the function is not available, create a + # function that will loosely count the number of UTF-8 characters with a + # regular expression. + # + if (function_exists($this->utf8_strlen)) return; + $this->utf8_strlen = create_function('$text', 'return preg_match_all( + "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", + $text, $m);'); + } + + + function unhash($text) { + # + # Swap back in all the tags hashed by _HashHTMLBlocks. + # + return preg_replace_callback('/(.)\x1A[0-9]+\1/', + array(&$this, '_unhash_callback'), $text); + } + function _unhash_callback($matches) { + return $this->html_hashes[$matches[0]]; + } + +} + + +# +# Markdown Extra Parser Class +# + +class MarkdownExtra_Parser extends Markdown_Parser { + + # Prefix for footnote ids. + var $fn_id_prefix = ""; + + # Optional title attribute for footnote links and backlinks. + var $fn_link_title = MARKDOWN_FN_LINK_TITLE; + var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE; + + # Optional class attribute for footnote links and backlinks. + var $fn_link_class = MARKDOWN_FN_LINK_CLASS; + var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS; + + # Predefined abbreviations. + var $predef_abbr = array(); + + + function MarkdownExtra_Parser() { + # + # Constructor function. Initialize the parser object. + # + # Add extra escapable characters before parent constructor + # initialize the table. + $this->escape_chars .= ':|'; + + # Insert extra document, block, and span transformations. + # Parent constructor will do the sorting. + $this->document_gamut += array( + "doFencedCodeBlocks" => 5, + "stripFootnotes" => 15, + "stripAbbreviations" => 25, + "appendFootnotes" => 50, + ); + $this->block_gamut += array( + "doFencedCodeBlocks" => 5, + "doTables" => 15, + "doDefLists" => 45, + ); + $this->span_gamut += array( + "doFootnotes" => 5, + "doAbbreviations" => 70, + ); + + parent::Markdown_Parser(); + } + + + # Extra variables used during extra transformations. + var $footnotes = array(); + var $footnotes_ordered = array(); + var $abbr_desciptions = array(); + var $abbr_word_re = ''; + + # Give the current footnote number. + var $footnote_counter = 1; + + + function setup() { + # + # Setting up Extra-specific variables. + # + parent::setup(); + + $this->footnotes = array(); + $this->footnotes_ordered = array(); + $this->abbr_desciptions = array(); + $this->abbr_word_re = ''; + $this->footnote_counter = 1; + + foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { + if ($this->abbr_word_re) + $this->abbr_word_re .= '|'; + $this->abbr_word_re .= preg_quote($abbr_word); + $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); + } + } + + function teardown() { + # + # Clearing Extra-specific variables. + # + $this->footnotes = array(); + $this->footnotes_ordered = array(); + $this->abbr_desciptions = array(); + $this->abbr_word_re = ''; + + parent::teardown(); + } + + + ### HTML Block Parser ### + + # Tags that are always treated as block tags: + var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend'; + + # Tags treated as block tags only if the opening tag is alone on it's line: + var $context_block_tags_re = 'script|noscript|math|ins|del'; + + # Tags where markdown="1" default to span mode: + var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; + + # Tags which must not have their contents modified, no matter where + # they appear: + var $clean_tags_re = 'script|math'; + + # Tags that do not need to be closed. + var $auto_close_tags_re = 'hr|img'; + + + function hashHTMLBlocks($text) { + # + # Hashify HTML Blocks and "clean tags". + # + # We only want to do this for block-level HTML tags, such as headers, + # lists, and tables. That's because we still want to wrap

    s around + # "paragraphs" that are wrapped in non-block-level tags, such as anchors, + # phrase emphasis, and spans. The list of tags we're looking for is + # hard-coded. + # + # This works by calling _HashHTMLBlocks_InMarkdown, which then calls + # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" + # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back + # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. + # These two functions are calling each other. It's recursive! + # + # + # Call the HTML-in-Markdown hasher. + # + list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); + + return $text; + } + function _hashHTMLBlocks_inMarkdown($text, $indent = 0, + $enclosing_tag_re = '', $span = false) + { + # + # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. + # + # * $indent is the number of space to be ignored when checking for code + # blocks. This is important because if we don't take the indent into + # account, something like this (which looks right) won't work as expected: + # + #

    + #
    + # Hello World. <-- Is this a Markdown code block or text? + #
    <-- Is this a Markdown code block or a real tag? + #
    + # + # If you don't like this, just don't indent the tag on which + # you apply the markdown="1" attribute. + # + # * If $enclosing_tag_re is not empty, stops at the first unmatched closing + # tag with that name. Nested tags supported. + # + # * If $span is true, text inside must treated as span. So any double + # newline will be replaced by a single newline so that it does not create + # paragraphs. + # + # Returns an array of that form: ( processed text , remaining text ) + # + if ($text === '') return array('', ''); + + # Regex to check for the presense of newlines around a block tag. + $newline_before_re = '/(?:^\n?|\n\n)*$/'; + $newline_after_re = + '{ + ^ # Start of text following the tag. + (?>[ ]*)? # Optional comment. + [ ]*\n # Must be followed by newline. + }xs'; + + # Regex to match any tag. + $block_tag_re = + '{ + ( # $2: Capture hole tag. + # Tag name. + '.$this->block_tags_re.' | + '.$this->context_block_tags_re.' | + '.$this->clean_tags_re.' | + (?!\s)'.$enclosing_tag_re.' + ) + (?: + (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. + (?> + ".*?" | # Double quotes (can contain `>`) + \'.*?\' | # Single quotes (can contain `>`) + .+? # Anything but quotes and `>`. + )*? + )? + > # End of tag. + | + # HTML Comment + | + <\?.*?\?> | <%.*?%> # Processing instruction + | + # CData Block + | + # Code span marker + `+ + '. ( !$span ? ' # If not in span. + | + # Indented code block + (?> ^[ ]*\n? | \n[ ]*\n ) + [ ]{'.($indent+4).'}[^\n]* \n + (?> + (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n + )* + | + # Fenced code block marker + (?> ^ | \n ) + [ ]{'.($indent).'}~~~+[ ]*\n + ' : '' ). ' # End (if not is span). + ) + }xs'; + + + $depth = 0; # Current depth inside the tag tree. + $parsed = ""; # Parsed text that will be returned. + + # + # Loop through every tag until we find the closing tag of the parent + # or loop until reaching the end of text if no parent tag specified. + # + do { + # + # Split the text using the first $tag_match pattern found. + # Text before pattern will be first in the array, text after + # pattern will be at the end, and between will be any catches made + # by the pattern. + # + $parts = preg_split($block_tag_re, $text, 2, + PREG_SPLIT_DELIM_CAPTURE); + + # If in Markdown span mode, add a empty-string span-level hash + # after each newline to prevent triggering any block element. + if ($span) { + $void = $this->hashPart("", ':'); + $newline = "$void\n"; + $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; + } + + $parsed .= $parts[0]; # Text before current tag. + + # If end of $text has been reached. Stop loop. + if (count($parts) < 3) { + $text = ""; + break; + } + + $tag = $parts[1]; # Tag to handle. + $text = $parts[2]; # Remaining text after current tag. + $tag_re = preg_quote($tag); # For use in a regular expression. + + # + # Check for: Code span marker + # + if ($tag{0} == "`") { + # Find corresponding end marker. + $tag_re = preg_quote($tag); + if (preg_match('{^(?>.+?|\n(?!\n))*?(?.*\n)+?'.$tag_re.' *\n}', $text, + $matches)) + { + # End marker found: pass text unchanged until marker. + $parsed .= $tag . $matches[0]; + $text = substr($text, strlen($matches[0])); + } + else { + # No end marker: just skip it. + $parsed .= $tag; + } + } + } + # + # Check for: Opening Block level tag or + # Opening Context Block tag (like ins and del) + # used as a block tag (tag is alone on it's line). + # + else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) || + ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) && + preg_match($newline_before_re, $parsed) && + preg_match($newline_after_re, $text) ) + ) + { + # Need to parse tag and following text using the HTML parser. + list($block_text, $text) = + $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); + + # Make sure it stays outside of any paragraph by adding newlines. + $parsed .= "\n\n$block_text\n\n"; + } + # + # Check for: Clean tag (like script, math) + # HTML Comments, processing instructions. + # + else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) || + $tag{1} == '!' || $tag{1} == '?') + { + # Need to parse tag and following text using the HTML parser. + # (don't check for markdown attribute) + list($block_text, $text) = + $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); + + $parsed .= $block_text; + } + # + # Check for: Tag with same name as enclosing tag. + # + else if ($enclosing_tag_re !== '' && + # Same name as enclosing tag. + preg_match('{^= 0); + + return array($parsed, $text); + } + function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { + # + # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags. + # + # * Calls $hash_method to convert any blocks. + # * Stops when the first opening tag closes. + # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed. + # (it is not inside clean tags) + # + # Returns an array of that form: ( processed text , remaining text ) + # + if ($text === '') return array('', ''); + + # Regex to match `markdown` attribute inside of a tag. + $markdown_attr_re = ' + { + \s* # Eat whitespace before the `markdown` attribute + markdown + \s*=\s* + (?> + (["\']) # $1: quote delimiter + (.*?) # $2: attribute value + \1 # matching delimiter + | + ([^\s>]*) # $3: unquoted attribute value + ) + () # $4: make $3 always defined (avoid warnings) + }xs'; + + # Regex to match any tag. + $tag_re = '{ + ( # $2: Capture hole tag. + + ".*?" | # Double quotes (can contain `>`) + \'.*?\' | # Single quotes (can contain `>`) + .+? # Anything but quotes and `>`. + )*? + )? + > # End of tag. + | + # HTML Comment + | + <\?.*?\?> | <%.*?%> # Processing instruction + | + # CData Block + ) + }xs'; + + $original_text = $text; # Save original text in case of faliure. + + $depth = 0; # Current depth inside the tag tree. + $block_text = ""; # Temporary text holder for current text. + $parsed = ""; # Parsed text that will be returned. + + # + # Get the name of the starting tag. + # (This pattern makes $base_tag_name_re safe without quoting.) + # + if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) + $base_tag_name_re = $matches[1]; + + # + # Loop through every tag until we find the corresponding closing tag. + # + do { + # + # Split the text using the first $tag_match pattern found. + # Text before pattern will be first in the array, text after + # pattern will be at the end, and between will be any catches made + # by the pattern. + # + $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); + + if (count($parts) < 3) { + # + # End of $text reached with unbalenced tag(s). + # In that case, we return original text unchanged and pass the + # first character as filtered to prevent an infinite loop in the + # parent function. + # + return array($original_text{0}, substr($original_text, 1)); + } + + $block_text .= $parts[0]; # Text before current tag. + $tag = $parts[1]; # Tag to handle. + $text = $parts[2]; # Remaining text after current tag. + + # + # Check for: Auto-close tag (like
    ) + # Comments and Processing Instructions. + # + if (preg_match('{^auto_close_tags_re.')\b}', $tag) || + $tag{1} == '!' || $tag{1} == '?') + { + # Just add the tag to the block as if it was text. + $block_text .= $tag; + } + else { + # + # Increase/decrease nested tag count. Only do so if + # the tag's name match base tag's. + # + if (preg_match('{^mode = $attr_m[2] . $attr_m[3]; + $span_mode = $this->mode == 'span' || $this->mode != 'block' && + preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag); + + # Calculate indent before tag. + if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { + $strlen = $this->utf8_strlen; + $indent = $strlen($matches[1], 'UTF-8'); + } else { + $indent = 0; + } + + # End preceding block with this tag. + $block_text .= $tag; + $parsed .= $this->$hash_method($block_text); + + # Get enclosing tag name for the ParseMarkdown function. + # (This pattern makes $tag_name_re safe without quoting.) + preg_match('/^<([\w:$]*)\b/', $tag, $matches); + $tag_name_re = $matches[1]; + + # Parse the content using the HTML-in-Markdown parser. + list ($block_text, $text) + = $this->_hashHTMLBlocks_inMarkdown($text, $indent, + $tag_name_re, $span_mode); + + # Outdent markdown text. + if ($indent > 0) { + $block_text = preg_replace("/^[ ]{1,$indent}/m", "", + $block_text); + } + + # Append tag content to parsed text. + if (!$span_mode) $parsed .= "\n\n$block_text\n\n"; + else $parsed .= "$block_text"; + + # Start over a new block. + $block_text = ""; + } + else $block_text .= $tag; + } + + } while ($depth > 0); + + # + # Hash last block text that wasn't processed inside the loop. + # + $parsed .= $this->$hash_method($block_text); + + return array($parsed, $text); + } + + + function hashClean($text) { + # + # Called whenever a tag must be hashed when a function insert a "clean" tag + # in $text, it pass through this function and is automaticaly escaped, + # blocking invalid nested overlap. + # + return $this->hashPart($text, 'C'); + } + + + function doHeaders($text) { + # + # Redefined to add id attribute support. + # + # Setext-style headers: + # Header 1 {#header1} + # ======== + # + # Header 2 {#header2} + # -------- + # + $text = preg_replace_callback( + '{ + (^.+?) # $1: Header text + (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute + [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer + }mx', + array(&$this, '_doHeaders_callback_setext'), $text); + + # atx-style headers: + # # Header 1 {#header1} + # ## Header 2 {#header2} + # ## Header 2 with closing hashes ## {#header3} + # ... + # ###### Header 6 {#header2} + # + $text = preg_replace_callback('{ + ^(\#{1,6}) # $1 = string of #\'s + [ ]* + (.+?) # $2 = Header text + [ ]* + \#* # optional closing #\'s (not counted) + (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute + [ ]* + \n+ + }xm', + array(&$this, '_doHeaders_callback_atx'), $text); + + return $text; + } + function _doHeaders_attr($attr) { + if (empty($attr)) return ""; + return " id=\"$attr\""; + } + function _doHeaders_callback_setext($matches) { + if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) + return $matches[0]; + $level = $matches[3]{0} == '=' ? 1 : 2; + $attr = $this->_doHeaders_attr($id =& $matches[2]); + $block = "".$this->runSpanGamut($matches[1]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + function _doHeaders_callback_atx($matches) { + $level = strlen($matches[1]); + $attr = $this->_doHeaders_attr($id =& $matches[3]); + $block = "".$this->runSpanGamut($matches[2]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + + function doTables($text) { + # + # Form HTML tables. + # + $less_than_tab = $this->tab_width - 1; + # + # Find tables with leading pipe. + # + # | Header 1 | Header 2 + # | -------- | -------- + # | Cell 1 | Cell 2 + # | Cell 3 | Cell 4 + # + $text = preg_replace_callback(' + { + ^ # Start of a line + [ ]{0,'.$less_than_tab.'} # Allowed whitespace. + [|] # Optional leading pipe (present) + (.+) \n # $1: Header row (at least one pipe) + + [ ]{0,'.$less_than_tab.'} # Allowed whitespace. + [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline + + ( # $3: Cells + (?> + [ ]* # Allowed whitespace. + [|] .* \n # Row content. + )* + ) + (?=\n|\Z) # Stop at final double newline. + }xm', + array(&$this, '_doTable_leadingPipe_callback'), $text); + + # + # Find tables without leading pipe. + # + # Header 1 | Header 2 + # -------- | -------- + # Cell 1 | Cell 2 + # Cell 3 | Cell 4 + # + $text = preg_replace_callback(' + { + ^ # Start of a line + [ ]{0,'.$less_than_tab.'} # Allowed whitespace. + (\S.*[|].*) \n # $1: Header row (at least one pipe) + + [ ]{0,'.$less_than_tab.'} # Allowed whitespace. + ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline + + ( # $3: Cells + (?> + .* [|] .* \n # Row content + )* + ) + (?=\n|\Z) # Stop at final double newline. + }xm', + array(&$this, '_DoTable_callback'), $text); + + return $text; + } + function _doTable_leadingPipe_callback($matches) { + $head = $matches[1]; + $underline = $matches[2]; + $content = $matches[3]; + + # Remove leading pipe for each row. + $content = preg_replace('/^ *[|]/m', '', $content); + + return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); + } + function _doTable_callback($matches) { + $head = $matches[1]; + $underline = $matches[2]; + $content = $matches[3]; + + # Remove any tailing pipes for each line. + $head = preg_replace('/[|] *$/m', '', $head); + $underline = preg_replace('/[|] *$/m', '', $underline); + $content = preg_replace('/[|] *$/m', '', $content); + + # Reading alignement from header underline. + $separators = preg_split('/ *[|] */', $underline); + foreach ($separators as $n => $s) { + if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"'; + else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"'; + else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"'; + else $attr[$n] = ''; + } + + # Parsing span elements, including code spans, character escapes, + # and inline HTML tags, so that pipes inside those gets ignored. + $head = $this->parseSpan($head); + $headers = preg_split('/ *[|] */', $head); + $col_count = count($headers); + + # Write column headers. + $text = "\n"; + $text .= "\n"; + $text .= "\n"; + foreach ($headers as $n => $header) + $text .= " ".$this->runSpanGamut(trim($header))."\n"; + $text .= "\n"; + $text .= "\n"; + + # Split content by row. + $rows = explode("\n", trim($content, "\n")); + + $text .= "\n"; + foreach ($rows as $row) { + # Parsing span elements, including code spans, character escapes, + # and inline HTML tags, so that pipes inside those gets ignored. + $row = $this->parseSpan($row); + + # Split row by cell. + $row_cells = preg_split('/ *[|] */', $row, $col_count); + $row_cells = array_pad($row_cells, $col_count, ''); + + $text .= "\n"; + foreach ($row_cells as $n => $cell) + $text .= " ".$this->runSpanGamut(trim($cell))."\n"; + $text .= "\n"; + } + $text .= "\n"; + $text .= "
    "; + + return $this->hashBlock($text) . "\n"; + } + + + function doDefLists($text) { + # + # Form HTML definition lists. + # + $less_than_tab = $this->tab_width - 1; + + # Re-usable pattern to match any entire dl list: + $whole_list_re = '(?> + ( # $1 = whole list + ( # $2 + [ ]{0,'.$less_than_tab.'} + ((?>.*\S.*\n)+) # $3 = defined term + \n? + [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition + ) + (?s:.+?) + ( # $4 + \z + | + \n{2,} + (?=\S) + (?! # Negative lookahead for another term + [ ]{0,'.$less_than_tab.'} + (?: \S.*\n )+? # defined term + \n? + [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition + ) + (?! # Negative lookahead for another definition + [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition + ) + ) + ) + )'; // mx + + $text = preg_replace_callback('{ + (?>\A\n?|(?<=\n\n)) + '.$whole_list_re.' + }mx', + array(&$this, '_doDefLists_callback'), $text); + + return $text; + } + function _doDefLists_callback($matches) { + # Re-usable patterns to match list item bullets and number markers: + $list = $matches[1]; + + # Turn double returns into triple returns, so that we can make a + # paragraph for the last item in a list, if necessary: + $result = trim($this->processDefListItems($list)); + $result = "
    \n" . $result . "\n
    "; + return $this->hashBlock($result) . "\n\n"; + } + + + function processDefListItems($list_str) { + # + # Process the contents of a single definition list, splitting it + # into individual term and definition list items. + # + $less_than_tab = $this->tab_width - 1; + + # trim trailing blank lines: + $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); + + # Process definition terms. + $list_str = preg_replace_callback('{ + (?>\A\n?|\n\n+) # leading line + ( # definition terms = $1 + [ ]{0,'.$less_than_tab.'} # leading whitespace + (?![:][ ]|[ ]) # negative lookahead for a definition + # mark (colon) or more whitespace. + (?> \S.* \n)+? # actual term (not whitespace). + ) + (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed + # with a definition mark. + }xm', + array(&$this, '_processDefListItems_callback_dt'), $list_str); + + # Process actual definitions. + $list_str = preg_replace_callback('{ + \n(\n+)? # leading line = $1 + ( # marker space = $2 + [ ]{0,'.$less_than_tab.'} # whitespace before colon + [:][ ]+ # definition mark (colon) + ) + ((?s:.+?)) # definition text = $3 + (?= \n+ # stop at next definition mark, + (?: # next term or end of text + [ ]{0,'.$less_than_tab.'} [:][ ] | +
    | \z + ) + ) + }xm', + array(&$this, '_processDefListItems_callback_dd'), $list_str); + + return $list_str; + } + function _processDefListItems_callback_dt($matches) { + $terms = explode("\n", trim($matches[1])); + $text = ''; + foreach ($terms as $term) { + $term = $this->runSpanGamut(trim($term)); + $text .= "\n
    " . $term . "
    "; + } + return $text . "\n"; + } + function _processDefListItems_callback_dd($matches) { + $leading_line = $matches[1]; + $marker_space = $matches[2]; + $def = $matches[3]; + + if ($leading_line || preg_match('/\n{2,}/', $def)) { + # Replace marker with the appropriate whitespace indentation + $def = str_repeat(' ', strlen($marker_space)) . $def; + $def = $this->runBlockGamut($this->outdent($def . "\n\n")); + $def = "\n". $def ."\n"; + } + else { + $def = rtrim($def); + $def = $this->runSpanGamut($this->outdent($def)); + } + + return "\n
    " . $def . "
    \n"; + } + + + function doFencedCodeBlocks($text) { + # + # Adding the fenced code block syntax to regular Markdown: + # + # ~~~ + # Code block + # ~~~ + # + $less_than_tab = $this->tab_width; + + $text = preg_replace_callback('{ + (?:\n|\A) + # 1: Opening marker + ( + ~{3,} # Marker: three tilde or more. + ) + [ ]* \n # Whitespace and newline following marker. + + # 2: Content + ( + (?> + (?!\1 [ ]* \n) # Not a closing marker. + .*\n+ + )+ + ) + + # Closing marker. + \1 [ ]* \n + }xm', + array(&$this, '_doFencedCodeBlocks_callback'), $text); + + return $text; + } + function _doFencedCodeBlocks_callback($matches) { + $codeblock = $matches[2]; + $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); + $codeblock = preg_replace_callback('/^\n+/', + array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock); + $codeblock = "
    $codeblock
    "; + return "\n\n".$this->hashBlock($codeblock)."\n\n"; + } + function _doFencedCodeBlocks_newlines($matches) { + return str_repeat("empty_element_suffix", + strlen($matches[0])); + } + + + # + # Redefining emphasis markers so that emphasis by underscore does not + # work in the middle of a word. + # + var $em_relist = array( + '' => '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? tags + # + # Strip leading and trailing lines: + $text = preg_replace('/\A\n+|\n+\z/', '', $text); + + $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); + + # + # Wrap

    tags and unhashify HTML blocks + # + foreach ($grafs as $key => $value) { + $value = trim($this->runSpanGamut($value)); + + # Check if this should be enclosed in a paragraph. + # Clean tag hashes & block tag hashes are left alone. + $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value); + + if ($is_p) { + $value = "

    $value

    "; + } + $grafs[$key] = $value; + } + + # Join grafs in one text, then unhash HTML tags. + $text = implode("\n\n", $grafs); + + # Finish by removing any tag hashes still present in $text. + $text = $this->unhash($text); + + return $text; + } + + + ### Footnotes + + function stripFootnotes($text) { + # + # Strips link definitions from text, stores the URLs and titles in + # hash references. + # + $less_than_tab = $this->tab_width - 1; + + # Link defs are in the form: [^id]: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1 + [ ]* + \n? # maybe *one* newline + ( # text = $2 (no blank lines allowed) + (?: + .+ # actual text + | + \n # newlines but + (?!\[\^.+?\]:\s)# negative lookahead for footnote marker. + (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed + # by non-indented content + )* + ) + }xm', + array(&$this, '_stripFootnotes_callback'), + $text); + return $text; + } + function _stripFootnotes_callback($matches) { + $note_id = $this->fn_id_prefix . $matches[1]; + $this->footnotes[$note_id] = $this->outdent($matches[2]); + return ''; # String that will replace the block + } + + + function doFootnotes($text) { + # + # Replace footnote references in $text [^id] with a special text-token + # which will be replaced by the actual footnote marker in appendFootnotes. + # + if (!$this->in_anchor) { + $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text); + } + return $text; + } + + + function appendFootnotes($text) { + # + # Append footnote list to text. + # + $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', + array(&$this, '_appendFootnotes_callback'), $text); + + if (!empty($this->footnotes_ordered)) { + $text .= "\n\n"; + $text .= "
    \n"; + $text .= "fn_backlink_class != "") { + $class = $this->fn_backlink_class; + $class = $this->encodeAttribute($class); + $attr .= " class=\"$class\""; + } + if ($this->fn_backlink_title != "") { + $title = $this->fn_backlink_title; + $title = $this->encodeAttribute($title); + $attr .= " title=\"$title\""; + } + $num = 0; + + while (!empty($this->footnotes_ordered)) { + $footnote = reset($this->footnotes_ordered); + $note_id = key($this->footnotes_ordered); + unset($this->footnotes_ordered[$note_id]); + + $footnote .= "\n"; # Need to append newline before parsing. + $footnote = $this->runBlockGamut("$footnote\n"); + $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', + array(&$this, '_appendFootnotes_callback'), $footnote); + + $attr = str_replace("%%", ++$num, $attr); + $note_id = $this->encodeAttribute($note_id); + + # Add backlink to last paragraph; create new paragraph if needed. + $backlink = ""; + if (preg_match('{

    $}', $footnote)) { + $footnote = substr($footnote, 0, -4) . " $backlink

    "; + } else { + $footnote .= "\n\n

    $backlink

    "; + } + + $text .= "
  • \n"; + $text .= $footnote . "\n"; + $text .= "
  • \n\n"; + } + + $text .= "\n"; + $text .= "
    "; + } + return $text; + } + function _appendFootnotes_callback($matches) { + $node_id = $this->fn_id_prefix . $matches[1]; + + # Create footnote marker only if it has a corresponding footnote *and* + # the footnote hasn't been used by another marker. + if (isset($this->footnotes[$node_id])) { + # Transfert footnote content to the ordered list. + $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; + unset($this->footnotes[$node_id]); + + $num = $this->footnote_counter++; + $attr = " rel=\"footnote\""; + if ($this->fn_link_class != "") { + $class = $this->fn_link_class; + $class = $this->encodeAttribute($class); + $attr .= " class=\"$class\""; + } + if ($this->fn_link_title != "") { + $title = $this->fn_link_title; + $title = $this->encodeAttribute($title); + $attr .= " title=\"$title\""; + } + + $attr = str_replace("%%", $num, $attr); + $node_id = $this->encodeAttribute($node_id); + + return + "". + "$num". + ""; + } + + return "[^".$matches[1]."]"; + } + + + ### Abbreviations ### + + function stripAbbreviations($text) { + # + # Strips abbreviations from text, stores titles in hash references. + # + $less_than_tab = $this->tab_width - 1; + + # Link defs are in the form: [id]*: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1 + (.*) # text = $2 (no blank lines allowed) + }xm', + array(&$this, '_stripAbbreviations_callback'), + $text); + return $text; + } + function _stripAbbreviations_callback($matches) { + $abbr_word = $matches[1]; + $abbr_desc = $matches[2]; + if ($this->abbr_word_re) + $this->abbr_word_re .= '|'; + $this->abbr_word_re .= preg_quote($abbr_word); + $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); + return ''; # String that will replace the block + } + + + function doAbbreviations($text) { + # + # Find defined abbreviations in text and wrap them in elements. + # + if ($this->abbr_word_re) { + // cannot use the /x modifier because abbr_word_re may + // contain significant spaces: + $text = preg_replace_callback('{'. + '(?abbr_word_re.')'. + '(?![\w\x1A])'. + '}', + array(&$this, '_doAbbreviations_callback'), $text); + } + return $text; + } + function _doAbbreviations_callback($matches) { + $abbr = $matches[0]; + if (isset($this->abbr_desciptions[$abbr])) { + $desc = $this->abbr_desciptions[$abbr]; + if (empty($desc)) { + return $this->hashPart("$abbr"); + } else { + $desc = $this->encodeAttribute($desc); + return $this->hashPart("$abbr"); + } + } else { + return $matches[0]; + } + } + +} + + +/* + +PHP Markdown Extra +================== + +Description +----------- + +This is a PHP port of the original Markdown formatter written in Perl +by John Gruber. This special "Extra" version of PHP Markdown features +further enhancements to the syntax for making additional constructs +such as tables and definition list. + +Markdown is a text-to-HTML filter; it translates an easy-to-read / +easy-to-write structured text format into HTML. Markdown's text format +is most similar to that of plain text email, and supports features such +as headers, *emphasis*, code blocks, blockquotes, and links. + +Markdown's syntax is designed not as a generic markup language, but +specifically to serve as a front-end to (X)HTML. You can use span-level +HTML tags anywhere in a Markdown document, and you can use block level +HTML tags (like
    and as well). + +For more information about Markdown's syntax, see: + + + + +Bugs +---- + +To file bug reports please send email to: + + + +Please include with your report: (1) the example input; (2) the output you +expected; (3) the output Markdown actually produced. + + +Version History +--------------- + +See the readme file for detailed release notes for this version. + + +Copyright and License +--------------------- + +PHP Markdown & Extra +Copyright (c) 2004-2008 Michel Fortin + +All rights reserved. + +Based on Markdown +Copyright (c) 2003-2006 John Gruber + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name "Markdown" nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as +is" and any express or implied warranties, including, but not limited +to, the implied warranties of merchantability and fitness for a +particular purpose are disclaimed. In no event shall the copyright owner +or contributors be liable for any direct, indirect, incidental, special, +exemplary, or consequential damages (including, but not limited to, +procurement of substitute goods or services; loss of use, data, or +profits; or business interruption) however caused and on any theory of +liability, whether in contract, strict liability, or tort (including +negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + +*/ +?> \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/api/class.php b/includes/kohana/modules/userguide/views/userguide/api/class.php new file mode 100644 index 0000000..f102b7f --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/api/class.php @@ -0,0 +1,103 @@ +

    + modifiers, $doc->class->name ?> + class; ?> + getParentClass()): ?> +
    extends uri(array('class' => $parent->name)), $parent->name) ?> + +

    + +description ?> + +tags): ?> +
    +tags as $name => $set): ?> +
    + +
    + + +
    + + +

    +class->getFilename()): ?> +Class declared in on line class->getStartLine() ?>. + +Class is not declared in a file, it is probably an internal class->name).'.php', 'PHP class') ?>. + +

    + +
    +
    +

    +
      + constants): ?> + constants as $name => $value): ?> +
    • + + +
    • + +
    +
    +
    +

    + +
    +
    +

    + +
    +
    + +
    + +constants): ?> +
    +

    +
    +constants as $name => $value): ?> +

    +
    + +
    +
    + + +properties()): ?> +

    +
    +
    + +

    modifiers ?> type ?> $property->name ?>

    +
    description ?>
    +
    value ?>
    + +
    +
    + + +methods()): ?> +

    +
    + +set('doc', $method)->set('route', $route) ?> + +
    + diff --git a/includes/kohana/modules/userguide/views/userguide/api/menu.php b/includes/kohana/modules/userguide/views/userguide/api/menu.php new file mode 100644 index 0000000..4f4f22f --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/api/menu.php @@ -0,0 +1,18 @@ + +

    Modules

    + \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/api/method.php b/includes/kohana/modules/userguide/views/userguide/api/method.php new file mode 100644 index 0000000..16b8db7 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/api/method.php @@ -0,0 +1,45 @@ +
    + +method->getDeclaringClass(); ?> +

    + modifiers, $doc->method->name ?>( params ? $doc->params_short() : '' ?>) + (defined in uri(array('class' => $declares->name)), $declares->name) ?>) +

    + +
    +description ?> +
    + +params): ?> +

    Parameters

    +
      +params as $param): ?> +
    • +reference?'byref ':'').($param->type?$param->type:'unknown') ?> +name ?> +default?' = '.$param->default.'':'required' ?> +description?' - '.$param->description:'' ?> +
    • + +
    + + +tags) echo View::factory('userguide/api/tags')->set('tags', $doc->tags) ?> + +return): ?> +

    +
      +return as $set): list($type, $text) = $set; ?> +
    • + +
    + + +source): ?> +
    +

    +
    source) ?>
    +
    + + +
    diff --git a/includes/kohana/modules/userguide/views/userguide/api/tags.php b/includes/kohana/modules/userguide/views/userguide/api/tags.php new file mode 100644 index 0000000..18779ac --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/api/tags.php @@ -0,0 +1,6 @@ +

    Tags

    +
      + $set): ?> +
    • + +
    \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/api/toc.php b/includes/kohana/modules/userguide/views/userguide/api/toc.php new file mode 100644 index 0000000..7b0dd28 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/api/toc.php @@ -0,0 +1,75 @@ +

    + + + + + + +
    + + $methods): $link = $route->uri(array('class' => $class)) ?> +
    +

    +
      + +
    • + +
    +
    + + +
    diff --git a/includes/kohana/modules/userguide/views/userguide/error.php b/includes/kohana/modules/userguide/views/userguide/error.php new file mode 100644 index 0000000..1f7b97b --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/error.php @@ -0,0 +1,3 @@ +

    Kodoc -

    + +

    \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/examples/error.php b/includes/kohana/modules/userguide/views/userguide/examples/error.php new file mode 100644 index 0000000..81548ce --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/examples/error.php @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/examples/hello_world_error.php b/includes/kohana/modules/userguide/views/userguide/examples/hello_world_error.php new file mode 100644 index 0000000..d5dcf44 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/examples/hello_world_error.php @@ -0,0 +1,696 @@ + + +
    +

    Kohana_View_Exception [ 0 ]: The requested view site could not be found

    +
    +

    SYSPATH/classes/kohana/view.php [ 215 ]

    +
    210 	 */
    +
    +211 	public function set_filename($file)
    +212 	{
    +213 		if (($path = Kohana::find_file('views', $file)) === FALSE)
    +214 		{
    +215 			throw new Kohana_View_Exception('The requested view :file could not be found', array(
    +216 				':file' => $file,
    +
    +217 			));
    +218 		}
    +219 
    +220 		// Store the file path locally
    +
      +
    1. +

      + + + SYSPATH/classes/kohana/view.php [ 115 ] + + » + Kohana_View->set_filename(arguments) +

      +
    + + + + + +
    file
    string(4) "site"
    +
    + + + + +
  • +

    + + SYSPATH/classes/kohana/view.php [ 26 ] + + » + Kohana_View->__construct(arguments) +

    + + + +
  • +
  • +

    + + + SYSPATH/classes/kohana/controller/template.php [ 32 ] + + » + Kohana_View::factory(arguments) +

    + + + +
  • +
  • +

    + + {PHP internal call} + + » + Kohana_Controller_Template->before() +

    + +
  • +
  • +

    + + SYSPATH/classes/kohana/request.php [ 840 ] + + » + ReflectionMethod->invoke(arguments) +

    + + + +
  • +
  • +

    + + APPPATH/bootstrap.php [ 76 ] + + + » + Kohana_Request->execute() +

    + +
  • +
  • +

    + + DOCROOT/index.php [ 106 ] + + » + require(arguments) +

    + + + +
  • + +
    +

    Environment

    + +
    diff --git a/includes/kohana/modules/userguide/views/userguide/index.php b/includes/kohana/modules/userguide/views/userguide/index.php new file mode 100644 index 0000000..51edc15 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/index.php @@ -0,0 +1,20 @@ +

    User Guide

    + +

    The following modules have userguide pages:

    + + + + $options): ?> + +

    + uri(array('module' => $url)), $options['name']) ?> - + +

    + + + + + +

    I couldn't find any modules with userguide pages.

    + + \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/menu.php b/includes/kohana/modules/userguide/views/userguide/menu.php new file mode 100644 index 0000000..e813608 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/menu.php @@ -0,0 +1,17 @@ +

    Modules

    + + + +
      + $options): ?> + +
    • uri(array('module' => $url)), $options['name']) ?>
    • + + +
    + + + +

    No modules.

    + + \ No newline at end of file diff --git a/includes/kohana/modules/userguide/views/userguide/page-toc.php b/includes/kohana/modules/userguide/views/userguide/page-toc.php new file mode 100644 index 0000000..eacdba5 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/page-toc.php @@ -0,0 +1,10 @@ + +
    + + 1): ?> + + +
    + +
    + diff --git a/includes/kohana/modules/userguide/views/userguide/template.php b/includes/kohana/modules/userguide/views/userguide/template.php new file mode 100644 index 0000000..2ab8c24 --- /dev/null +++ b/includes/kohana/modules/userguide/views/userguide/template.php @@ -0,0 +1,108 @@ + + + + + +<?php echo $title ?> | Kohana <?php echo __('User Guide'); ?> + + $media) echo HTML::style($style, array('media' => $media), TRUE), "\n" ?> + + + + + + + + + +
    +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + + + +
    + + + Documentation comments powered by Disqus + +
    +
    +
    +
    + + + + + + + + diff --git a/includes/kohana/system/base.php b/includes/kohana/system/base.php new file mode 100644 index 0000000..c39bf4e --- /dev/null +++ b/includes/kohana/system/base.php @@ -0,0 +1,50 @@ + $username)); + * + * [!!] The target language is defined by [I18n::$lang]. The default source + * language is defined by [I18n::$source]. + * + * @uses I18n::get + * @param string text to translate + * @param array values to replace in the translated text + * @param string source language + * @return string + */ +function __($string, array $values = NULL, $source = NULL) +{ + if ( ! $source) + { + // Use the default source language + $source = I18n::$source; + } + + if ($source !== I18n::$lang) + { + // The message and target languages are different + // Get the translation for this message + $string = I18n::get($string); + } + + return empty($values) ? $string : strtr($string, $values); +} diff --git a/includes/kohana/system/classes/arr.php b/includes/kohana/system/classes/arr.php new file mode 100644 index 0000000..a279831 --- /dev/null +++ b/includes/kohana/system/classes/arr.php @@ -0,0 +1,3 @@ + 'john.doe')); + * + * // Returns FALSE + * Arr::is_assoc('foo', 'bar'); + * + * @param array array to check + * @return boolean + */ + public static function is_assoc(array $array) + { + // Keys of the array + $keys = array_keys($array); + + // If the array keys of the keys match the keys, then the array must + // not be associative (e.g. the keys array looked like {0:0, 1:1...}). + return array_keys($keys) !== $keys; + } + + /** + * Test if a value is an array with an additional check for array-like objects. + * + * // Returns TRUE + * Arr::is_array(array()); + * Arr::is_array(new ArrayObject); + * + * // Returns FALSE + * Arr::is_array(FALSE); + * Arr::is_array('not an array!'); + * Arr::is_array(Database::instance()); + * + * @param mixed value to check + * @return boolean + */ + public static function is_array($value) + { + if (is_array($value)) + { + // Definitely an array + return TRUE; + } + else + { + // Possibly a Traversable object, functionally the same as an array + return (is_object($value) AND $value instanceof Traversable); + } + } + + /** + * Gets a value from an array using a dot separated path. + * + * // Get the value of $array['foo']['bar'] + * $value = Arr::path($array, 'foo.bar'); + * + * Using a wildcard "*" will search intermediate arrays and return an array. + * + * // Get the values of "color" in theme + * $colors = Arr::path($array, 'theme.*.color'); + * + * // Using an array of keys + * $colors = Arr::path($array, array('theme', '*', 'color')); + * + * @param array array to search + * @param mixed key path string (delimiter separated) or array of keys + * @param mixed default value if the path is not set + * @param string key path delimiter + * @return mixed + */ + public static function path($array, $path, $default = NULL, $delimiter = NULL) + { + if ( ! Arr::is_array($array)) + { + // This is not an array! + return $default; + } + + if (is_array($path)) + { + // The path has already been separated into keys + $keys = $path; + } + else + { + if (array_key_exists($path, $array)) + { + // No need to do extra processing + return $array[$path]; + } + + if ($delimiter === NULL) + { + // Use the default delimiter + $delimiter = Arr::$delimiter; + } + + // Remove starting delimiters and spaces + $path = ltrim($path, "{$delimiter} "); + + // Remove ending delimiters, spaces, and wildcards + $path = rtrim($path, "{$delimiter} *"); + + // Split the keys by delimiter + $keys = explode($delimiter, $path); + } + + do + { + $key = array_shift($keys); + + if (ctype_digit($key)) + { + // Make the key an integer + $key = (int) $key; + } + + if (isset($array[$key])) + { + if ($keys) + { + if (Arr::is_array($array[$key])) + { + // Dig down into the next part of the path + $array = $array[$key]; + } + else + { + // Unable to dig deeper + break; + } + } + else + { + // Found the path requested + return $array[$key]; + } + } + elseif ($key === '*') + { + // Handle wildcards + + $values = array(); + foreach ($array as $arr) + { + if ($value = Arr::path($arr, implode('.', $keys))) + { + $values[] = $value; + } + } + + if ($values) + { + // Found the values requested + return $values; + } + else + { + // Unable to dig deeper + break; + } + } + else + { + // Unable to dig deeper + break; + } + } + while ($keys); + + // Unable to find the value requested + return $default; + } + + /** + * Fill an array with a range of numbers. + * + * // Fill an array with values 5, 10, 15, 20 + * $values = Arr::range(5, 20); + * + * @param integer stepping + * @param integer ending number + * @return array + */ + public static function range($step = 10, $max = 100) + { + if ($step < 1) + return array(); + + $array = array(); + for ($i = $step; $i <= $max; $i += $step) + { + $array[$i] = $i; + } + + return $array; + } + + /** + * Retrieve a single key from an array. If the key does not exist in the + * array, the default value will be returned instead. + * + * // Get the value "username" from $_POST, if it exists + * $username = Arr::get($_POST, 'username'); + * + * // Get the value "sorting" from $_GET, if it exists + * $sorting = Arr::get($_GET, 'sorting'); + * + * @param array array to extract from + * @param string key name + * @param mixed default value + * @return mixed + */ + public static function get($array, $key, $default = NULL) + { + return isset($array[$key]) ? $array[$key] : $default; + } + + /** + * Retrieves multiple keys from an array. If the key does not exist in the + * array, the default value will be added instead. + * + * // Get the values "username", "password" from $_POST + * $auth = Arr::extract($_POST, array('username', 'password')); + * + * @param array array to extract keys from + * @param array list of key names + * @param mixed default value + * @return array + */ + public static function extract($array, array $keys, $default = NULL) + { + $found = array(); + foreach ($keys as $key) + { + $found[$key] = isset($array[$key]) ? $array[$key] : $default; + } + + return $found; + } + + /** + * Retrieves muliple single-key values from a list of arrays. + * + * // Get all of the "id" values from a result + * $ids = Arr::pluck($result, 'id'); + * + * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...) + * + * @param array list of arrays to check + * @param string key to pluck + * @return array + */ + public static function pluck($array, $key) + { + $values = array(); + + foreach ($array as $row) + { + if (isset($row[$key])) + { + // Found a value in this row + $values[] = $row[$key]; + } + } + + return $values; + } + + /** + * Binary search algorithm. + * + * @deprecated Use [array_search](http://php.net/array_search) instead + * + * @param mixed the value to search for + * @param array an array of values to search in + * @param boolean sort the array now + * @return integer the index of the match + * @return FALSE no matching index found + */ + public static function binary_search($needle, $haystack, $sort = FALSE) + { + return array_search($needle, $haystack); + } + + /** + * Adds a value to the beginning of an associative array. + * + * // Add an empty value to the start of a select list + * Arr::unshift_assoc($array, 'none', 'Select a value'); + * + * @param array array to modify + * @param string array key name + * @param mixed array value + * @return array + */ + public static function unshift( array & $array, $key, $val) + { + $array = array_reverse($array, TRUE); + $array[$key] = $val; + $array = array_reverse($array, TRUE); + + return $array; + } + + /** + * Recursive version of [array_map](http://php.net/array_map), applies the + * same callback to all elements in an array, including sub-arrays. + * + * // Apply "strip_tags" to every element in the array + * $array = Arr::map('strip_tags', $array); + * + * [!!] Unlike `array_map`, this method requires a callback and will only map + * a single array. + * + * @param mixed callback applied to every element in the array + * @param array array to map + * @return array + */ + public static function map($callback, $array) + { + foreach ($array as $key => $val) + { + if (is_array($val)) + { + $array[$key] = Arr::map($callback, $val); + } + else + { + $array[$key] = call_user_func($callback, $val); + } + } + + return $array; + } + + /** + * Merges one or more arrays recursively and preserves all keys. + * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)! + * + * $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane')); + * $mary = array('name' => 'mary', 'children' => array('jane')); + * + * // John and Mary are married, merge them together + * $john = Arr::merge($john, $mary); + * + * // The output of $john will now be: + * array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane')) + * + * @param array initial array + * @param array array to merge + * @param array ... + * @return array + */ + public static function merge(array $a1, array $a2) + { + $result = array(); + for ($i = 0, $total = func_num_args(); $i < $total; $i++) + { + // Get the next array + $arr = func_get_arg($i); + + // Is the array associative? + $assoc = Arr::is_assoc($arr); + + foreach ($arr as $key => $val) + { + if (isset($result[$key])) + { + if (is_array($val) AND is_array($result[$key])) + { + if (Arr::is_assoc($val)) + { + // Associative arrays are merged recursively + $result[$key] = Arr::merge($result[$key], $val); + } + else + { + // Find the values that are not already present + $diff = array_diff($val, $result[$key]); + + // Indexed arrays are merged to prevent duplicates + $result[$key] = array_merge($result[$key], $diff); + } + } + else + { + if ($assoc) + { + // Associative values are replaced + $result[$key] = $val; + } + elseif ( ! in_array($val, $result, TRUE)) + { + // Indexed values are added only if they do not yet exist + $result[] = $val; + } + } + } + else + { + // New values are added + $result[$key] = $val; + } + } + } + + return $result; + } + + /** + * Overwrites an array with values from input arrays. + * Keys that do not exist in the first array will not be added! + * + * $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon'); + * $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer'); + * + * // Overwrite the values of $a1 with $a2 + * $array = Arr::overwrite($a1, $a2); + * + * // The output of $array will now be: + * array('name' => 'jack', 'mood' => 'happy', 'food' => 'bacon') + * + * @param array master array + * @param array input arrays that will overwrite existing values + * @return array + */ + public static function overwrite($array1, $array2) + { + foreach (array_intersect_key($array2, $array1) as $key => $value) + { + $array1[$key] = $value; + } + + if (func_num_args() > 2) + { + foreach (array_slice(func_get_args(), 2) as $array2) + { + foreach (array_intersect_key($array2, $array1) as $key => $value) + { + $array1[$key] = $value; + } + } + } + + return $array1; + } + + /** + * Creates a callable function and parameter list from a string representation. + * Note that this function does not validate the callback string. + * + * // Get the callback function and parameters + * list($func, $params) = Arr::callback('Foo::bar(apple,orange)'); + * + * // Get the result of the callback + * $result = call_user_func_array($func, $params); + * + * @param string callback string + * @return array function, params + */ + public static function callback($str) + { + // Overloaded as parts are found + $command = $params = NULL; + + // command[param,param] + if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match)) + { + // command + $command = $match[1]; + + if ($match[2] !== '') + { + // param,param + $params = preg_split('/(? array('one' => 'something'), 'two' => 'other'); + * + * // Flatten the array + * $array = Arr::flatten($array); + * + * // The array will now be + * array('one' => 'something', 'two' => 'other'); + * + * [!!] The keys of array values will be discarded. + * + * @param array array to flatten + * @return array + * @since 3.0.6 + */ + public static function flatten($array) + { + $flat = array(); + foreach ($array as $key => $value) + { + if (is_array($value)) + { + $flat += Arr::flatten($value); + } + else + { + $flat[$key] = $value; + } + } + return $flat; + } + +} // End arr diff --git a/includes/kohana/system/classes/kohana/cli.php b/includes/kohana/system/classes/kohana/cli.php new file mode 100644 index 0000000..415aea6 --- /dev/null +++ b/includes/kohana/system/classes/kohana/cli.php @@ -0,0 +1,75 @@ +attach($reader); // Try first + * $config->attach($reader, FALSE); // Try last + * + * @param object Kohana_Config_Reader instance + * @param boolean add the reader as the first used object + * @return $this + */ + public function attach(Kohana_Config_Reader $reader, $first = TRUE) + { + if ($first === TRUE) + { + // Place the log reader at the top of the stack + array_unshift($this->_readers, $reader); + } + else + { + // Place the reader at the bottom of the stack + $this->_readers[] = $reader; + } + + return $this; + } + + /** + * Detach a configuration reader. + * + * $config->detach($reader); + * + * @param object Kohana_Config_Reader instance + * @return $this + */ + public function detach(Kohana_Config_Reader $reader) + { + if (($key = array_search($reader, $this->_readers)) !== FALSE) + { + // Remove the writer + unset($this->_readers[$key]); + } + + return $this; + } + + /** + * Load a configuration group. Searches the readers in order until the + * group is found. If the group does not exist, an empty configuration + * array will be loaded using the first reader. + * + * $array = $config->load($name); + * + * @param string configuration group name + * @return object Kohana_Config_Reader + * @throws Kohana_Exception + */ + public function load($group) + { + foreach ($this->_readers as $reader) + { + if ($config = $reader->load($group)) + { + // Found a reader for this configuration group + return $config; + } + } + + // Reset the iterator + reset($this->_readers); + + if ( ! is_object($config = current($this->_readers))) + { + throw new Kohana_Exception('No configuration readers attached'); + } + + // Load the reader as an empty array + return $config->load($group, array()); + } + + /** + * Copy one configuration group to all of the other readers. + * + * $config->copy($name); + * + * @param string configuration group name + * @return $this + */ + public function copy($group) + { + // Load the configuration group + $config = $this->load($group); + + foreach ($this->_readers as $reader) + { + if ($config instanceof $reader) + { + // Do not copy the config to the same group + continue; + } + + // Load the configuration object + $object = $reader->load($group, array()); + + foreach ($config as $key => $value) + { + // Copy each value in the config + $object->offsetSet($key, $value); + } + } + + return $this; + } + +} // End Kohana_Config diff --git a/includes/kohana/system/classes/kohana/config/file.php b/includes/kohana/system/classes/kohana/config/file.php new file mode 100644 index 0000000..9015c28 --- /dev/null +++ b/includes/kohana/system/classes/kohana/config/file.php @@ -0,0 +1,60 @@ +_directory = trim($directory, '/'); + + // Load the empty array + parent::__construct(); + } + + /** + * Load and merge all of the configuration files in this group. + * + * $config->load($name); + * + * @param string configuration group name + * @param array configuration array + * @return $this clone of the current object + * @uses Kohana::load + */ + public function load($group, array $config = NULL) + { + if ($files = Kohana::find_file($this->_directory, $group, NULL, TRUE)) + { + // Initialize the config array + $config = array(); + + foreach ($files as $file) + { + // Merge each file to the configuration array + $config = Arr::merge($config, Kohana::load($file)); + } + } + + return parent::load($group, $config); + } + +} // End Kohana_Config diff --git a/includes/kohana/system/classes/kohana/config/reader.php b/includes/kohana/system/classes/kohana/config/reader.php new file mode 100644 index 0000000..098cdac --- /dev/null +++ b/includes/kohana/system/classes/kohana/config/reader.php @@ -0,0 +1,115 @@ +getArrayCopy()); + } + + /** + * Loads a configuration group. + * + * $config->load($name, $array); + * + * This method must be extended by all readers. After the group has been + * loaded, call `parent::load($group, $config)` for final preparation. + * + * @param string configuration group name + * @param array configuration array + * @return $this a clone of this object + */ + public function load($group, array $config = NULL) + { + if ($config === NULL) + { + return FALSE; + } + + // Clone the current object + $object = clone $this; + + // Set the group name + $object->_configuration_group = $group; + + // Swap the array with the actual configuration + $object->exchangeArray($config); + + return $object; + } + + /** + * Return the raw array that is being used for this object. + * + * $array = $config->as_array(); + * + * @return array + */ + public function as_array() + { + return $this->getArrayCopy(); + } + + /** + * Get a variable from the configuration or return the default value. + * + * $value = $config->get($key); + * + * @param string array key + * @param mixed default value + * @return mixed + */ + public function get($key, $default = NULL) + { + return $this->offsetExists($key) ? $this->offsetGet($key) : $default; + } + + /** + * Sets a value in the configuration array. + * + * $config->set($key, $new_value); + * + * @param string array key + * @param mixed array value + * @return $this + */ + public function set($key, $value) + { + $this->offsetSet($key, $value); + + return $this; + } + +} // End Kohana_Config_Reader diff --git a/includes/kohana/system/classes/kohana/controller.php b/includes/kohana/system/classes/kohana/controller.php new file mode 100644 index 0000000..4830ce1 --- /dev/null +++ b/includes/kohana/system/classes/kohana/controller.php @@ -0,0 +1,66 @@ +before(); + * $controller->action_bar(); + * $controller->after(); + * + * The controller action should add the output it creates to + * `$this->request->response`, typically in the form of a [View], during the + * "action" part of execution. + * + * @package Kohana + * @category Controller + * @author Kohana Team + * @copyright (c) 2008-2010 Kohana Team + * @license http://kohanaframework.org/license + */ +abstract class Kohana_Controller { + + /** + * @var Request Request that created the controller + */ + public $request; + + /** + * Creates a new controller instance. Each controller must be constructed + * with the request object that created it. + * + * @param Request Request that created the controller + * @return void + */ + public function __construct(Request $request) + { + // Assign the request to the controller + $this->request = $request; + } + + /** + * Automatically executed before the controller action. Can be used to set + * class properties, do authorization checks, and execute other custom code. + * + * @return void + */ + public function before() + { + // Nothing by default + } + + /** + * Automatically executed after the controller action. Can be used to apply + * transformation to the request response, add extra output, and execute + * other custom code. + * + * @return void + */ + public function after() + { + // Nothing by default + } + +} // End Controller diff --git a/includes/kohana/system/classes/kohana/controller/rest.php b/includes/kohana/system/classes/kohana/controller/rest.php new file mode 100644 index 0000000..e270e36 --- /dev/null +++ b/includes/kohana/system/classes/kohana/controller/rest.php @@ -0,0 +1,80 @@ + 'index', + 'PUT' => 'update', + 'POST' => 'create', + 'DELETE' => 'delete', + ); + + /** + * @var string requested action + */ + protected $_action_requested = ''; + + /** + * Checks the requested method against the available methods. If the method + * is supported, sets the request action from the map. If not supported, + * the "invalid" action will be called. + */ + public function before() + { + $this->_action_requested = $this->request->action; + + if ( ! isset($this->_action_map[Request::$method])) + { + $this->request->action = 'invalid'; + } + else + { + $this->request->action = $this->_action_map[Request::$method]; + } + + return parent::before(); + } + + /** + * Sends a 405 "Method Not Allowed" response and a list of allowed actions. + */ + public function action_invalid() + { + // Send the "Method Not Allowed" response + $this->request->status = 405; + $this->request->headers['Allow'] = implode(', ', array_keys($this->_action_map)); + } + +} // End REST diff --git a/includes/kohana/system/classes/kohana/controller/template.php b/includes/kohana/system/classes/kohana/controller/template.php new file mode 100644 index 0000000..76c4222 --- /dev/null +++ b/includes/kohana/system/classes/kohana/controller/template.php @@ -0,0 +1,50 @@ +auto_render === TRUE) + { + // Load the template + $this->template = View::factory($this->template); + } + + return parent::before(); + } + + /** + * Assigns the template [View] as the request response. + */ + public function after() + { + if ($this->auto_render === TRUE) + { + $this->request->response = $this->template; + } + + return parent::after(); + } + +} // End Controller_Template diff --git a/includes/kohana/system/classes/kohana/cookie.php b/includes/kohana/system/classes/kohana/cookie.php new file mode 100644 index 0000000..4be8f44 --- /dev/null +++ b/includes/kohana/system/classes/kohana/cookie.php @@ -0,0 +1,155 @@ + 'Fatal Error', + E_USER_ERROR => 'User Error', + E_PARSE => 'Parse Error', + E_WARNING => 'Warning', + E_USER_WARNING => 'User Warning', + E_STRICT => 'Strict', + E_NOTICE => 'Notice', + E_RECOVERABLE_ERROR => 'Recoverable Error', + ); + + /** + * @var string Current environment name + */ + public static $environment = Kohana::DEVELOPMENT; + + /** + * @var boolean True if Kohana is running from the command line + */ + public static $is_cli = FALSE; + + /** + * @var boolean True if Kohana is running on windows + */ + public static $is_windows = FALSE; + + /** + * @var boolean True if [magic quotes](http://php.net/manual/en/security.magicquotes.php) is enabled. + */ + public static $magic_quotes = FALSE; + + /** + * @var boolean Should errors and exceptions be logged + */ + public static $log_errors = FALSE; + + /** + * @var boolean TRUE if PHP safe mode is on + */ + public static $safe_mode = FALSE; + + /** + * @var string Character set of input and output. Set by [Kohana::init] + */ + public static $charset = 'utf-8'; + + /** + * @var string Base URL to the application. Set by [Kohana::init] + */ + public static $base_url = '/'; + + /** + * @var string Application index file, added to links generated by Kohana. Set by [Kohana::init] + */ + public static $index_file = 'index.php'; + + /** + * @var string Cache directory, used by [Kohana::cache]. Set by [Kohana::init] + */ + public static $cache_dir; + + /** + * @var integer Default lifetime for caching, in seconds, used by [Kohana::cache]. Set by [Kohana::init] + */ + public static $cache_life = 60; + + /** + * @var boolean Whether to use internal caching for [Kohana::find_file], does not apply to [Kohana::cache]. Set by [Kohana::init] + */ + public static $caching = FALSE; + + /** + * @var boolean Whether to enable [profiling](kohana/profiling). Set by [Kohana::init] + */ + public static $profiling = TRUE; + + /** + * @var boolean Enable Kohana catching and displaying PHP errors and exceptions. Set by [Kohana::init] + */ + public static $errors = TRUE; + + /** + * @var string Error rendering view when Kohana catches PHP errors and exceptions. Set by [Kohana::init] + */ + public static $error_view = 'kohana/error'; + + /** + * @var array Types of errors to display at shutdown + */ + public static $shutdown_errors = array(E_PARSE, E_ERROR, E_USER_ERROR); + + /** + * @var boolean escape quotes in Kohana::debug? + */ + public static $debug_escape_quotes = FALSE; + + /** + * @var Kohana_Log logging object + */ + public static $log; + + /** + * @var Kohana_Config config object + */ + public static $config; + + /** + * @var boolean Has [Kohana::init] been called? + */ + protected static $_init = FALSE; + + /** + * @var array Currently active modules + */ + protected static $_modules = array(); + + /** + * @var array Include paths that are used to find files + */ + protected static $_paths = array(APPPATH, SYSPATH); + + /** + * @var array File path cache, used when caching is true in [Kohana::init] + */ + protected static $_files = array(); + + /** + * @var boolean Has the file path cache changed during this execution? Used internally when when caching is true in [Kohana::init] + */ + protected static $_files_changed = FALSE; + + /** + * Initializes the environment: + * + * - Disables register_globals and magic_quotes_gpc + * - Determines the current environment + * - Set global settings + * - Sanitizes GET, POST, and COOKIE variables + * - Converts GET, POST, and COOKIE variables to the global character set + * + * The following settings can be set: + * + * Type | Setting | Description | Default Value + * ----------|------------|------------------------------------------------|--------------- + * `string` | base_url | The base URL for your application. This should be the *relative* path from your DOCROOT to your `index.php` file, in other words, if Kohana is in a subfolder, set this to the subfolder name, otherwise leave it as the default. **The leading slash is required**, trailing slash is optional. | `"/"` + * `string` | index_file | The name of the [front controller](http://en.wikipedia.org/wiki/Front_Controller_pattern). This is used by Kohana to generate relative urls like [HTML::anchor()] and [URL::base()]. This is usually `index.php`. To [remove index.php from your urls](tutorials/clean-urls), set this to `FALSE`. | `"index.php"` + * `string` | charset | Character set used for all input and output | `"utf-8"` + * `string` | cache_dir | Kohana's cache directory. Used by [Kohana::cache] for simple internal caching, like [Fragments](kohana/fragments) and **\[caching database queries](this should link somewhere)**. This has nothing to do with the [Cache module](cache). | `APPPATH."cache"` + * `integer` | cache_life | Lifetime, in seconds, of items cached by [Kohana::cache] | `60` + * `boolean` | errors | Should Kohana catch PHP errors and uncaught Exceptions and show the `error_view`. See [Error Handling](kohana/errors) for more info.

    Recommended setting: `TRUE` while developing, `FALSE` on production servers. | `TRUE` + * `string` | error_view | The view to use to display errors. Only used when `errors` is `TRUE`. | `"kohana/error"` + * `boolean` | profile | Whether to enable the [Profiler](kohana/profiling).

    Recommended setting: `TRUE` while developing, `FALSE` on production servers. | `TRUE` + * `boolean` | caching | Cache file locations to speed up [Kohana::find_file]. This has nothing to do with [Kohana::cache], [Fragments](kohana/fragments) or the [Cache module](cache).

    Recommended setting: `FALSE` while developing, `TRUE` on production servers. | `FALSE` + * + * @throws Kohana_Exception + * @param array Array of settings. See above. + * @return void + * @uses Kohana::globals + * @uses Kohana::sanitize + * @uses Kohana::cache + * @uses Profiler + */ + public static function init(array $settings = NULL) + { + if (Kohana::$_init) + { + // Do not allow execution twice + return; + } + + // Kohana is now initialized + Kohana::$_init = TRUE; + + if (isset($settings['profile'])) + { + // Enable profiling + Kohana::$profiling = (bool) $settings['profile']; + } + + // Start an output buffer + ob_start(); + + if (defined('E_DEPRECATED')) + { + // E_DEPRECATED only exists in PHP >= 5.3.0 + Kohana::$php_errors[E_DEPRECATED] = 'Deprecated'; + } + + if (isset($settings['errors'])) + { + // Enable error handling + Kohana::$errors = (bool) $settings['errors']; + } + + if (Kohana::$errors === TRUE) + { + // Enable Kohana exception handling, adds stack traces and error source. + set_exception_handler(array('Kohana', 'exception_handler')); + + // Enable Kohana error handling, converts all PHP errors to exceptions. + set_error_handler(array('Kohana', 'error_handler')); + } + + // Enable the Kohana shutdown handler, which catches E_FATAL errors. + register_shutdown_function(array('Kohana', 'shutdown_handler')); + + if (isset($settings['error_view'])) + { + if ( ! Kohana::find_file('views', $settings['error_view'])) + { + throw new Kohana_Exception('Error view file does not exist: views/:file', array( + ':file' => $settings['error_view'], + )); + } + + // Change the default error rendering + Kohana::$error_view = (string) $settings['error_view']; + } + + if (ini_get('register_globals')) + { + // Reverse the effects of register_globals + Kohana::globals(); + } + + // Determine if we are running in a command line environment + Kohana::$is_cli = (PHP_SAPI === 'cli'); + + // Determine if we are running in a Windows environment + Kohana::$is_windows = (DIRECTORY_SEPARATOR === '\\'); + + // Determine if we are running in safe mode + Kohana::$safe_mode = (bool) ini_get('safe_mode'); + + if (isset($settings['cache_dir'])) + { + if ( ! is_dir($settings['cache_dir'])) + { + try + { + // Create the cache directory + mkdir($settings['cache_dir'], 0755, TRUE); + + // Set permissions (must be manually set to fix umask issues) + chmod($settings['cache_dir'], 0755); + } + catch (Exception $e) + { + throw new Kohana_Exception('Could not create cache directory :dir', + array(':dir' => Kohana::debug_path($settings['cache_dir']))); + } + } + + // Set the cache directory path + Kohana::$cache_dir = realpath($settings['cache_dir']); + } + else + { + // Use the default cache directory + Kohana::$cache_dir = APPPATH.'cache'; + } + + if ( ! is_writable(Kohana::$cache_dir)) + { + throw new Kohana_Exception('Directory :dir must be writable', + array(':dir' => Kohana::debug_path(Kohana::$cache_dir))); + } + + if (isset($settings['cache_life'])) + { + // Set the default cache lifetime + Kohana::$cache_life = (int) $settings['cache_life']; + } + + if (isset($settings['caching'])) + { + // Enable or disable internal caching + Kohana::$caching = (bool) $settings['caching']; + } + + if (Kohana::$caching === TRUE) + { + // Load the file path cache + Kohana::$_files = Kohana::cache('Kohana::find_file()'); + } + + if (isset($settings['charset'])) + { + // Set the system character set + Kohana::$charset = strtolower($settings['charset']); + } + + if (function_exists('mb_internal_encoding')) + { + // Set the MB extension encoding to the same character set + mb_internal_encoding(Kohana::$charset); + } + + if (isset($settings['base_url'])) + { + // Set the base URL + Kohana::$base_url = rtrim($settings['base_url'], '/').'/'; + } + + if (isset($settings['index_file'])) + { + // Set the index file + Kohana::$index_file = trim($settings['index_file'], '/'); + } + + // Determine if the extremely evil magic quotes are enabled + Kohana::$magic_quotes = (bool) get_magic_quotes_gpc(); + + // Sanitize all request variables + $_GET = Kohana::sanitize($_GET); + $_POST = Kohana::sanitize($_POST); + $_COOKIE = Kohana::sanitize($_COOKIE); + + // Load the logger + Kohana::$log = Kohana_Log::instance(); + + // Load the config + Kohana::$config = Kohana_Config::instance(); + } + + /** + * Cleans up the environment: + * + * - Restore the previous error and exception handlers + * - Destroy the Kohana::$log and Kohana::$config objects + * + * @return void + */ + public static function deinit() + { + if (Kohana::$_init) + { + // Removed the autoloader + spl_autoload_unregister(array('Kohana', 'auto_load')); + + if (Kohana::$errors) + { + // Go back to the previous error handler + restore_error_handler(); + + // Go back to the previous exception handler + restore_exception_handler(); + } + + // Destroy objects created by init + Kohana::$log = Kohana::$config = NULL; + + // Reset internal storage + Kohana::$_modules = Kohana::$_files = array(); + Kohana::$_paths = array(APPPATH, SYSPATH); + + // Reset file cache status + Kohana::$_files_changed = FALSE; + + // Kohana is no longer initialized + Kohana::$_init = FALSE; + } + } + + /** + * Reverts the effects of the `register_globals` PHP setting by unsetting + * all global varibles except for the default super globals (GPCS, etc), + * which is a [potential security hole.][ref-wikibooks] + * + * This is called automatically by [Kohana::init] if `register_globals` is + * on. + * + * + * [ref-wikibooks]: http://en.wikibooks.org/wiki/PHP_Programming/Register_Globals + * + * @return void + */ + public static function globals() + { + if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS'])) + { + // Prevent malicious GLOBALS overload attack + echo "Global variable overload attack detected! Request aborted.\n"; + + // Exit with an error status + exit(1); + } + + // Get the variable names of all globals + $global_variables = array_keys($GLOBALS); + + // Remove the standard global variables from the list + $global_variables = array_diff($global_variables, array( + '_COOKIE', + '_ENV', + '_GET', + '_FILES', + '_POST', + '_REQUEST', + '_SERVER', + '_SESSION', + 'GLOBALS', + )); + + foreach ($global_variables as $name) + { + // Unset the global variable, effectively disabling register_globals + unset($GLOBALS[$name]); + } + } + + /** + * Recursively sanitizes an input variable: + * + * - Strips slashes if magic quotes are enabled + * - Normalizes all newlines to LF + * + * @param mixed any variable + * @return mixed sanitized variable + */ + public static function sanitize($value) + { + if (is_array($value) OR is_object($value)) + { + foreach ($value as $key => $val) + { + // Recursively clean each value + $value[$key] = Kohana::sanitize($val); + } + } + elseif (is_string($value)) + { + if (Kohana::$magic_quotes === TRUE) + { + // Remove slashes added by magic quotes + $value = stripslashes($value); + } + + if (strpos($value, "\r") !== FALSE) + { + // Standardize newlines + $value = str_replace(array("\r\n", "\r"), "\n", $value); + } + } + + return $value; + } + + /** + * Provides auto-loading support of classes that follow Kohana's [class + * naming conventions](kohana/conventions#class-names-and-file-location). + * See [Loading Classes](kohana/autoloading) for more information. + * + * Class names are converted to file names by making the class name + * lowercase and converting underscores to slashes: + * + * // Loads classes/my/class/name.php + * Kohana::auto_load('My_Class_Name'); + * + * You should never have to call this function, as simply calling a class + * will cause it to be called. + * + * This function must be enabled as an autoloader in the bootstrap: + * + * spl_autoload_register(array('Kohana', 'auto_load')); + * + * @param string class name + * @return boolean + */ + public static function auto_load($class) + { + try + { + // Transform the class name into a path + $file = str_replace('_', '/', strtolower($class)); + + if ($path = Kohana::find_file('classes', $file)) + { + // Load the class file + require $path; + + // Class has been found + return TRUE; + } + + // Class is not in the filesystem + return FALSE; + } + catch (Exception $e) + { + Kohana::exception_handler($e); + die; + } + } + + /** + * Changes the currently enabled modules. Module paths may be relative + * or absolute, but must point to a directory: + * + * Kohana::modules(array('modules/foo', MODPATH.'bar')); + * + * @param array list of module paths + * @return array enabled modules + */ + public static function modules(array $modules = NULL) + { + if ($modules === NULL) + { + // Not changing modules, just return the current set + return Kohana::$_modules; + } + + // Start a new list of include paths, APPPATH first + $paths = array(APPPATH); + + foreach ($modules as $name => $path) + { + if (is_dir($path)) + { + // Add the module to include paths + $paths[] = $modules[$name] = realpath($path).DIRECTORY_SEPARATOR; + } + else + { + // This module is invalid, remove it + unset($modules[$name]); + } + } + + // Finish the include paths by adding SYSPATH + $paths[] = SYSPATH; + + // Set the new include paths + Kohana::$_paths = $paths; + + // Set the current module list + Kohana::$_modules = $modules; + + foreach (Kohana::$_modules as $path) + { + $init = $path.'init'.EXT; + + if (is_file($init)) + { + // Include the module initialization file once + require_once $init; + } + } + + return Kohana::$_modules; + } + + /** + * Returns the the currently active include paths, including the + * application, system, and each module's path. + * + * @return array + */ + public static function include_paths() + { + return Kohana::$_paths; + } + + /** + * Searches for a file in the [Cascading Filesystem](kohana/files), and + * returns the path to the file that has the highest precedence, so that it + * can be included. + * + * When searching the "config", "messages", or "i18n" directories, or when + * the `$array` flag is set to true, an array of all the files that match + * that path in the [Cascading Filesystem](kohana/files) will be returned. + * These files will return arrays which must be merged together. + * + * If no extension is given, the default extension (`EXT` set in + * `index.php`) will be used. + * + * // Returns an absolute path to views/template.php + * Kohana::find_file('views', 'template'); + * + * // Returns an absolute path to media/css/style.css + * Kohana::find_file('media', 'css/style', 'css'); + * + * // Returns an array of all the "mimes" configuration files + * Kohana::find_file('config', 'mimes'); + * + * @param string directory name (views, i18n, classes, extensions, etc.) + * @param string filename with subdirectory + * @param string extension to search for + * @param boolean return an array of files? + * @return array a list of files when $array is TRUE + * @return string single file path + */ + public static function find_file($dir, $file, $ext = NULL, $array = FALSE) + { + if ($ext === NULL) + { + // Use the default extension + $ext = EXT; + } + elseif ($ext) + { + // Prefix the extension with a period + $ext = ".{$ext}"; + } + else + { + // Use no extension + $ext = ''; + } + + // Create a partial path of the filename + $path = $dir.DIRECTORY_SEPARATOR.$file.$ext; + + if (Kohana::$caching === TRUE AND isset(Kohana::$_files[$path])) + { + // This path has been cached + return Kohana::$_files[$path]; + } + + if (Kohana::$profiling === TRUE AND class_exists('Profiler', FALSE)) + { + // Start a new benchmark + $benchmark = Profiler::start('Kohana', __FUNCTION__); + } + + if ($array OR $dir === 'config' OR $dir === 'i18n' OR $dir === 'messages') + { + // Include paths must be searched in reverse + $paths = array_reverse(Kohana::$_paths); + + // Array of files that have been found + $found = array(); + + foreach ($paths as $dir) + { + if (is_file($dir.$path)) + { + // This path has a file, add it to the list + $found[] = $dir.$path; + } + } + } + else + { + // The file has not been found yet + $found = FALSE; + + foreach (Kohana::$_paths as $dir) + { + if (is_file($dir.$path)) + { + // A path has been found + $found = $dir.$path; + + // Stop searching + break; + } + } + } + + if (Kohana::$caching === TRUE) + { + // Add the path to the cache + Kohana::$_files[$path] = $found; + + // Files have been changed + Kohana::$_files_changed = TRUE; + } + + if (isset($benchmark)) + { + // Stop the benchmark + Profiler::stop($benchmark); + } + + return $found; + } + + /** + * Recursively finds all of the files in the specified directory at any + * location in the [Cascading Filesystem](kohana/files), and returns an + * array of all the files found, sorted alphabetically. + * + * // Find all view files. + * $views = Kohana::list_files('views'); + * + * @param string directory name + * @param array list of paths to search + * @return array + */ + public static function list_files($directory = NULL, array $paths = NULL) + { + if ($directory !== NULL) + { + // Add the directory separator + $directory .= DIRECTORY_SEPARATOR; + } + + if ($paths === NULL) + { + // Use the default paths + $paths = Kohana::$_paths; + } + + // Create an array for the files + $found = array(); + + foreach ($paths as $path) + { + if (is_dir($path.$directory)) + { + // Create a new directory iterator + $dir = new DirectoryIterator($path.$directory); + + foreach ($dir as $file) + { + // Get the file name + $filename = $file->getFilename(); + + if ($filename[0] === '.' OR $filename[strlen($filename)-1] === '~') + { + // Skip all hidden files and UNIX backup files + continue; + } + + // Relative filename is the array key + $key = $directory.$filename; + + if ($file->isDir()) + { + if ($sub_dir = Kohana::list_files($key, $paths)) + { + if (isset($found[$key])) + { + // Append the sub-directory list + $found[$key] += $sub_dir; + } + else + { + // Create a new sub-directory list + $found[$key] = $sub_dir; + } + } + } + else + { + if ( ! isset($found[$key])) + { + // Add new files to the list + $found[$key] = realpath($file->getPathName()); + } + } + } + } + } + + // Sort the results alphabetically + ksort($found); + + return $found; + } + + /** + * Loads a file within a totally empty scope and returns the output: + * + * $foo = Kohana::load('foo.php'); + * + * @param string + * @return mixed + */ + public static function load($file) + { + return include $file; + } + + /** + * Returns the configuration array for the requested group. See + * [configuration files](kohana/files/config) for more information. + * + * // Get all the configuration in config/database.php + * $config = Kohana::config('database'); + * + * // Get only the default connection configuration + * $default = Kohana::config('database.default') + * + * // Get only the hostname of the default connection + * $host = Kohana::config('database.default.connection.hostname') + * + * @param string group name + * @return Kohana_Config + */ + public static function config($group) + { + static $config; + + if (strpos($group, '.') !== FALSE) + { + // Split the config group and path + list ($group, $path) = explode('.', $group, 2); + } + + if ( ! isset($config[$group])) + { + // Load the config group into the cache + $config[$group] = Kohana::$config->load($group); + } + + if (isset($path)) + { + return Arr::path($config[$group], $path, NULL, '.'); + } + else + { + return $config[$group]; + } + } + + /** + * Provides simple file-based caching for strings and arrays: + * + * // Set the "foo" cache + * Kohana::cache('foo', 'hello, world'); + * + * // Get the "foo" cache + * $foo = Kohana::cache('foo'); + * + * All caches are stored as PHP code, generated with [var_export][ref-var]. + * Caching objects may not work as expected. Storing references or an + * object or array that has recursion will cause an E_FATAL. + * + * The cache directory and default cache lifetime is set by [Kohana::init] + * + * [ref-var]: http://php.net/var_export + * + * @throws Kohana_Exception + * @param string name of the cache + * @param mixed data to cache + * @param integer number of seconds the cache is valid for + * @return mixed for getting + * @return boolean for setting + */ + public static function cache($name, $data = NULL, $lifetime = NULL) + { + // Cache file is a hash of the name + $file = sha1($name).'.txt'; + + // Cache directories are split by keys to prevent filesystem overload + $dir = Kohana::$cache_dir.DIRECTORY_SEPARATOR.$file[0].$file[1].DIRECTORY_SEPARATOR; + + if ($lifetime === NULL) + { + // Use the default lifetime + $lifetime = Kohana::$cache_life; + } + + if ($data === NULL) + { + if (is_file($dir.$file)) + { + if ((time() - filemtime($dir.$file)) < $lifetime) + { + // Return the cache + try + { + return unserialize(file_get_contents($dir.$file)); + } + catch (Exception $e) + { + // Cache is corrupt, let return happen normally. + } + } + else + { + try + { + // Cache has expired + unlink($dir.$file); + } + catch (Exception $e) + { + // Cache has mostly likely already been deleted, + // let return happen normally. + } + } + } + + // Cache not found + return NULL; + } + + if ( ! is_dir($dir)) + { + // Create the cache directory + mkdir($dir, 0777, TRUE); + + // Set permissions (must be manually set to fix umask issues) + chmod($dir, 0777); + } + + // Force the data to be a string + $data = serialize($data); + + try + { + // Write the cache + return (bool) file_put_contents($dir.$file, $data, LOCK_EX); + } + catch (Exception $e) + { + // Failed to write cache + return FALSE; + } + } + + /** + * Get a message from a file. Messages are arbitary strings that are stored + * in the `messages/` directory and reference by a key. Translation is not + * performed on the returned values. See [message files](kohana/files/messages) + * for more information. + * + * // Get "username" from messages/text.php + * $username = Kohana::message('text', 'username'); + * + * @param string file name + * @param string key path to get + * @param mixed default value if the path does not exist + * @return string message string for the given path + * @return array complete message list, when no path is specified + * @uses Arr::merge + * @uses Arr::path + */ + public static function message($file, $path = NULL, $default = NULL) + { + static $messages; + + if ( ! isset($messages[$file])) + { + // Create a new message list + $messages[$file] = array(); + + if ($files = Kohana::find_file('messages', $file)) + { + foreach ($files as $f) + { + // Combine all the messages recursively + $messages[$file] = Arr::merge($messages[$file], Kohana::load($f)); + } + } + } + + if ($path === NULL) + { + // Return all of the messages + return $messages[$file]; + } + else + { + // Get a message using the path + return Arr::path($messages[$file], $path, $default); + } + } + + /** + * PHP error handler, converts all errors into ErrorExceptions. This handler + * respects error_reporting settings. + * + * @throws ErrorException + * @return TRUE + */ + public static function error_handler($code, $error, $file = NULL, $line = NULL) + { + if (error_reporting() & $code) + { + // This error is not suppressed by current error reporting settings + // Convert the error into an ErrorException + throw new ErrorException($error, $code, 0, $file, $line); + } + + // Do not execute the PHP error handler + return TRUE; + } + + /** + * Inline exception handler, displays the error message, source of the + * exception, and the stack trace of the error. + * + * @uses Kohana::exception_text + * @param object exception object + * @return boolean + */ + public static function exception_handler(Exception $e) + { + try + { + // Get the exception information + $type = get_class($e); + $code = $e->getCode(); + $message = $e->getMessage(); + $file = $e->getFile(); + $line = $e->getLine(); + + // Create a text version of the exception + $error = Kohana::exception_text($e); + + if (is_object(Kohana::$log)) + { + // Add this exception to the log + Kohana::$log->add(Kohana::ERROR, $error); + + // Make sure the logs are written + Kohana::$log->write(); + } + + if (Kohana::$is_cli) + { + // Just display the text of the exception + echo "\n{$error}\n"; + + return TRUE; + } + + // Get the exception backtrace + $trace = $e->getTrace(); + + if ($e instanceof ErrorException) + { + if (isset(Kohana::$php_errors[$code])) + { + // Use the human-readable error name + $code = Kohana::$php_errors[$code]; + } + + if (version_compare(PHP_VERSION, '5.3', '<')) + { + // Workaround for a bug in ErrorException::getTrace() that exists in + // all PHP 5.2 versions. @see http://bugs.php.net/bug.php?id=45895 + for ($i = count($trace) - 1; $i > 0; --$i) + { + if (isset($trace[$i - 1]['args'])) + { + // Re-position the args + $trace[$i]['args'] = $trace[$i - 1]['args']; + + // Remove the args + unset($trace[$i - 1]['args']); + } + } + } + } + + if ( ! headers_sent()) + { + // Make sure the proper content type is sent with a 500 status + header('Content-Type: text/html; charset='.Kohana::$charset, TRUE, 500); + } + + // Start an output buffer + ob_start(); + + // Include the exception HTML + include Kohana::find_file('views', Kohana::$error_view); + + // Display the contents of the output buffer + echo ob_get_clean(); + + return TRUE; + } + catch (Exception $e) + { + // Clean the output buffer if one exists + ob_get_level() and ob_clean(); + + // Display the exception text + echo Kohana::exception_text($e), "\n"; + + // Exit with an error status + exit(1); + } + } + + /** + * Catches errors that are not caught by the error handler, such as E_PARSE. + * + * @uses Kohana::exception_handler + * @return void + */ + public static function shutdown_handler() + { + if ( ! Kohana::$_init) + { + // Do not execute when not active + return; + } + + try + { + if (Kohana::$caching === TRUE AND Kohana::$_files_changed === TRUE) + { + // Write the file path cache + Kohana::cache('Kohana::find_file()', Kohana::$_files); + } + } + catch (Exception $e) + { + // Pass the exception to the handler + Kohana::exception_handler($e); + } + + if (Kohana::$errors AND $error = error_get_last() AND in_array($error['type'], Kohana::$shutdown_errors)) + { + // Clean the output buffer + ob_get_level() and ob_clean(); + + // Fake an exception for nice debugging + Kohana::exception_handler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line'])); + + // Shutdown now to avoid a "death loop" + exit(1); + } + } + + /** + * Get a single line of text representing the exception: + * + * Error [ Code ]: Message ~ File [ Line ] + * + * @param object Exception + * @return string + */ + public static function exception_text(Exception $e) + { + return sprintf('%s [ %s ]: %s ~ %s [ %d ]', + get_class($e), $e->getCode(), strip_tags($e->getMessage()), Kohana::debug_path($e->getFile()), $e->getLine()); + } + + /** + * Returns an HTML string of debugging information about any number of + * variables, each wrapped in a "pre" tag: + * + * // Displays the type and value of each variable + * echo Kohana::debug($foo, $bar, $baz); + * + * @param mixed variable to debug + * @param ... + * @return string + */ + public static function debug() + { + if (func_num_args() === 0) + return; + + // Get all passed variables + $variables = func_get_args(); + + $output = array(); + foreach ($variables as $var) + { + $output[] = Kohana::_dump($var, 1024); + } + + return '
    '.implode("\n", $output).'
    '; + } + + /** + * Returns an HTML string of information about a single variable. + * + * Borrows heavily on concepts from the Debug class of [Nette](http://nettephp.com/). + * + * @param mixed variable to dump + * @param integer maximum length of strings + * @return string + */ + public static function dump($value, $length = 128) + { + return Kohana::_dump($value, $length); + } + + /** + * Helper for Kohana::dump(), handles recursion in arrays and objects. + * + * @param mixed variable to dump + * @param integer maximum length of strings + * @param integer recursion level (internal) + * @return string + */ + protected static function _dump( & $var, $length = 128, $level = 0) + { + if ($var === NULL) + { + return 'NULL'; + } + elseif (is_bool($var)) + { + return 'bool '.($var ? 'TRUE' : 'FALSE'); + } + elseif (is_float($var)) + { + return 'float '.$var; + } + elseif (is_resource($var)) + { + if (($type = get_resource_type($var)) === 'stream' AND $meta = stream_get_meta_data($var)) + { + $meta = stream_get_meta_data($var); + + if (isset($meta['uri'])) + { + $file = $meta['uri']; + + if (function_exists('stream_is_local')) + { + // Only exists on PHP >= 5.2.4 + if (stream_is_local($file)) + { + $file = Kohana::debug_path($file); + } + } + + return 'resource('.$type.') '.htmlspecialchars($file, ENT_NOQUOTES, Kohana::$charset); + } + } + else + { + return 'resource('.$type.')'; + } + } + elseif (is_string($var)) + { + // Clean invalid multibyte characters. iconv is only invoked + // if there are non ASCII characters in the string, so this + // isn't too much of a hit. + $var = UTF8::clean($var, Kohana::$charset); + + if (UTF8::strlen($var) > $length) + { + // Encode the truncated string + $str = htmlspecialchars(UTF8::substr($var, 0, $length), ENT_NOQUOTES, Kohana::$charset).' …'; + } + else + { + // Encode the string + $str = htmlspecialchars($var, ENT_NOQUOTES, Kohana::$charset); + } + + if (Kohana::$debug_escape_quotes) + { + // Escape strings (for syntax highlighters, mostly) + $str = str_replace('"', '\\"', $str); + } + + return 'string('.strlen($var).') "'.$str.'"'; + } + elseif (is_array($var)) + { + $output = array(); + + // Indentation for this variable + $space = str_repeat($s = ' ', $level); + + static $marker; + + if ($marker === NULL) + { + // Make a unique marker + $marker = uniqid("\x00"); + } + + if (empty($var)) + { + // Do nothing + } + elseif (isset($var[$marker])) + { + $output[] = "(\n$space$s*RECURSION*\n$space)"; + } + elseif ($level < 5) + { + $output[] = "("; + + $var[$marker] = TRUE; + foreach ($var as $key => & $val) + { + if ($key === $marker) continue; + if ( ! is_int($key)) + { + $key = '"'.htmlspecialchars($key, ENT_NOQUOTES, self::$charset).'"'; + } + + $output[] = "$space$s$key => ".Kohana::_dump($val, $length, $level + 1); + } + unset($var[$marker]); + + $output[] = "$space)"; + } + else + { + // Depth too great + $output[] = "(\n$space$s...\n$space)"; + } + + return 'array('.count($var).') '.implode("\n", $output); + } + elseif (is_object($var)) + { + // Copy the object as an array + $array = (array) $var; + + $output = array(); + + // Indentation for this variable + $space = str_repeat($s = ' ', $level); + + $hash = spl_object_hash($var); + + // Objects that are being dumped + static $objects = array(); + + if (empty($var)) + { + // Do nothing + } + elseif (isset($objects[$hash])) + { + $output[] = "{\n$space$s*RECURSION*\n$space}"; + } + elseif ($level < 10) + { + $output[] = "{"; + + $objects[$hash] = TRUE; + foreach ($array as $key => & $val) + { + if ($key[0] === "\x00") + { + // Determine if the access is protected or protected + $access = ''.(($key[1] === '*') ? 'protected' : 'private').''; + + // Remove the access level from the variable name + $key = substr($key, strrpos($key, "\x00") + 1); + } + else + { + $access = 'public'; + } + + $output[] = "$space$s$access $key => ".Kohana::_dump($val, $length, $level + 1); + } + unset($objects[$hash]); + + $output[] = "$space}"; + } + else + { + // Depth too great + $output[] = "{\n$space$s...\n$space}"; + } + + return 'object '.get_class($var).'('.count($array).') '.implode("\n", $output); + } + else + { + return ''.gettype($var).' '.htmlspecialchars(print_r($var, TRUE), ENT_NOQUOTES, Kohana::$charset); + } + } + + /** + * Removes application, system, modpath, or docroot from a filename, + * replacing them with the plain text equivalents. Useful for debugging + * when you want to display a shorter path. + * + * // Displays SYSPATH/classes/kohana.php + * echo Kohana::debug_path(Kohana::find_file('classes', 'kohana')); + * + * @param string path to debug + * @return string + */ + public static function debug_path($file) + { + if (strpos($file, APPPATH) === 0) + { + $file = 'APPPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(APPPATH)); + } + elseif (strpos($file, SYSPATH) === 0) + { + $file = 'SYSPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(SYSPATH)); + } + elseif (strpos($file, MODPATH) === 0) + { + $file = 'MODPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(MODPATH)); + } + elseif (strpos($file, DOCROOT) === 0) + { + $file = 'DOCROOT'.DIRECTORY_SEPARATOR.substr($file, strlen(DOCROOT)); + } + + return $file; + } + + /** + * Returns an HTML string, highlighting a specific line of a file, with some + * number of lines padded above and below. + * + * // Highlights the current line of the current file + * echo Kohana::debug_source(__FILE__, __LINE__); + * + * @param string file to open + * @param integer line number to highlight + * @param integer number of padding lines + * @return string source of file + * @return FALSE file is unreadable + */ + public static function debug_source($file, $line_number, $padding = 5) + { + if ( ! $file OR ! is_readable($file)) + { + // Continuing will cause errors + return FALSE; + } + + // Open the file and set the line position + $file = fopen($file, 'r'); + $line = 0; + + // Set the reading range + $range = array('start' => $line_number - $padding, 'end' => $line_number + $padding); + + // Set the zero-padding amount for line numbers + $format = '% '.strlen($range['end']).'d'; + + $source = ''; + while (($row = fgets($file)) !== FALSE) + { + // Increment the line number + if (++$line > $range['end']) + break; + + if ($line >= $range['start']) + { + // Make the row safe for output + $row = htmlspecialchars($row, ENT_NOQUOTES, Kohana::$charset); + + // Trim whitespace and sanitize the row + $row = ''.sprintf($format, $line).' '.$row; + + if ($line === $line_number) + { + // Apply highlighting to this row + $row = ''.$row.''; + } + else + { + $row = ''.$row.''; + } + + // Add to the captured source + $source .= $row; + } + } + + // Close the file + fclose($file); + + return '
    '.$source.'
    '; + } + + /** + * Returns an array of HTML strings that represent each step in the backtrace. + * + * // Displays the entire current backtrace + * echo implode('
    ', Kohana::trace()); + * + * @param string path to debug + * @return string + */ + public static function trace(array $trace = NULL) + { + if ($trace === NULL) + { + // Start a new trace + $trace = debug_backtrace(); + } + + // Non-standard function calls + $statements = array('include', 'include_once', 'require', 'require_once'); + + $output = array(); + foreach ($trace as $step) + { + if ( ! isset($step['function'])) + { + // Invalid trace step + continue; + } + + if (isset($step['file']) AND isset($step['line'])) + { + // Include the source of this step + $source = Kohana::debug_source($step['file'], $step['line']); + } + + if (isset($step['file'])) + { + $file = $step['file']; + + if (isset($step['line'])) + { + $line = $step['line']; + } + } + + // function() + $function = $step['function']; + + if (in_array($step['function'], $statements)) + { + if (empty($step['args'])) + { + // No arguments + $args = array(); + } + else + { + // Sanitize the file path + $args = array(Kohana::debug_path($step['args'][0])); + } + } + elseif (isset($step['args'])) + { + if ( ! function_exists($step['function']) OR strpos($step['function'], '{closure}') !== FALSE) + { + // Introspection on closures or language constructs in a stack trace is impossible + $params = NULL; + } + else + { + if (isset($step['class'])) + { + if (method_exists($step['class'], $step['function'])) + { + $reflection = new ReflectionMethod($step['class'], $step['function']); + } + else + { + $reflection = new ReflectionMethod($step['class'], '__call'); + } + } + else + { + $reflection = new ReflectionFunction($step['function']); + } + + // Get the function parameters + $params = $reflection->getParameters(); + } + + $args = array(); + + foreach ($step['args'] as $i => $arg) + { + if (isset($params[$i])) + { + // Assign the argument by the parameter name + $args[$params[$i]->name] = $arg; + } + else + { + // Assign the argument by number + $args[$i] = $arg; + } + } + } + + if (isset($step['class'])) + { + // Class->method() or Class::method() + $function = $step['class'].$step['type'].$step['function']; + } + + $output[] = array( + 'function' => $function, + 'args' => isset($args) ? $args : NULL, + 'file' => isset($file) ? $file : NULL, + 'line' => isset($line) ? $line : NULL, + 'source' => isset($source) ? $source : NULL, + ); + + unset($function, $args, $file, $line, $source); + } + + return $output; + } + +} // End Kohana diff --git a/includes/kohana/system/classes/kohana/date.php b/includes/kohana/system/classes/kohana/date.php new file mode 100644 index 0000000..506dab4 --- /dev/null +++ b/includes/kohana/system/classes/kohana/date.php @@ -0,0 +1,566 @@ +. + * + * @param string timezone that to find the offset of + * @param string timezone used as the baseline + * @param mixed UNIX timestamp or date string + * @return integer + */ + public static function offset($remote, $local = NULL, $now = NULL) + { + if ($local === NULL) + { + // Use the default timezone + $local = date_default_timezone_get(); + } + + if (is_int($now)) + { + // Convert the timestamp into a string + $now = date(DateTime::RFC2822, $now); + } + + // Create timezone objects + $zone_remote = new DateTimeZone($remote); + $zone_local = new DateTimeZone($local); + + // Create date objects from timezones + $time_remote = new DateTime($now, $zone_remote); + $time_local = new DateTime($now, $zone_local); + + // Find the offset + $offset = $zone_remote->getOffset($time_remote) - $zone_local->getOffset($time_local); + + return $offset; + } + + /** + * Number of seconds in a minute, incrementing by a step. Typically used as + * a shortcut for generating a list that can used in a form. + * + * $seconds = Date::seconds(); // 01, 02, 03, ..., 58, 59, 60 + * + * @param integer amount to increment each step by, 1 to 30 + * @param integer start value + * @param integer end value + * @return array A mirrored (foo => foo) array from 1-60. + */ + public static function seconds($step = 1, $start = 0, $end = 60) + { + // Always integer + $step = (int) $step; + + $seconds = array(); + + for ($i = $start; $i < $end; $i += $step) + { + $seconds[$i] = sprintf('%02d', $i); + } + + return $seconds; + } + + /** + * Number of minutes in an hour, incrementing by a step. Typically used as + * a shortcut for generating a list that can be used in a form. + * + * $minutes = Date::minutes(); // 05, 10, 15, ..., 50, 55, 60 + * + * @uses Date::seconds + * @param integer amount to increment each step by, 1 to 30 + * @return array A mirrored (foo => foo) array from 1-60. + */ + public static function minutes($step = 5) + { + // Because there are the same number of minutes as seconds in this set, + // we choose to re-use seconds(), rather than creating an entirely new + // function. Shhhh, it's cheating! ;) There are several more of these + // in the following methods. + return Date::seconds($step); + } + + /** + * Number of hours in a day. Typically used as a shortcut for generating a + * list that can be used in a form. + * + * $hours = Date::hours(); // 01, 02, 03, ..., 10, 11, 12 + * + * @param integer amount to increment each step by + * @param boolean use 24-hour time + * @param integer the hour to start at + * @return array A mirrored (foo => foo) array from start-12 or start-23. + */ + public static function hours($step = 1, $long = FALSE, $start = NULL) + { + // Default values + $step = (int) $step; + $long = (bool) $long; + $hours = array(); + + // Set the default start if none was specified. + if ($start === NULL) + { + $start = ($long === FALSE) ? 1 : 0; + } + + $hours = array(); + + // 24-hour time has 24 hours, instead of 12 + $size = ($long === TRUE) ? 23 : 12; + + for ($i = $start; $i <= $size; $i += $step) + { + $hours[$i] = (string) $i; + } + + return $hours; + } + + /** + * Returns AM or PM, based on a given hour (in 24 hour format). + * + * $type = Date::ampm(12); // PM + * $type = Date::ampm(1); // AM + * + * @param integer number of the hour + * @return string + */ + public static function ampm($hour) + { + // Always integer + $hour = (int) $hour; + + return ($hour > 11) ? 'PM' : 'AM'; + } + + /** + * Adjusts a non-24-hour number into a 24-hour number. + * + * $hour = Date::adjust(3, 'pm'); // 15 + * + * @param integer hour to adjust + * @param string AM or PM + * @return string + */ + public static function adjust($hour, $ampm) + { + $hour = (int) $hour; + $ampm = strtolower($ampm); + + switch ($ampm) + { + case 'am': + if ($hour == 12) + { + $hour = 0; + } + break; + case 'pm': + if ($hour < 12) + { + $hour += 12; + } + break; + } + + return sprintf('%02d', $hour); + } + + /** + * Number of days in a given month and year. Typically used as a shortcut + * for generating a list that can be used in a form. + * + * Date::days(4, 2010); // 1, 2, 3, ..., 28, 29, 30 + * + * @param integer number of month + * @param integer number of year to check month, defaults to the current year + * @return array A mirrored (foo => foo) array of the days. + */ + public static function days($month, $year = FALSE) + { + static $months; + + if ($year === FALSE) + { + // Use the current year by default + $year = date('Y'); + } + + // Always integers + $month = (int) $month; + $year = (int) $year; + + // We use caching for months, because time functions are used + if (empty($months[$year][$month])) + { + $months[$year][$month] = array(); + + // Use date to find the number of days in the given month + $total = date('t', mktime(1, 0, 0, $month, 1, $year)) + 1; + + for ($i = 1; $i < $total; $i++) + { + $months[$year][$month][$i] = (string) $i; + } + } + + return $months[$year][$month]; + } + + /** + * Number of months in a year. Typically used as a shortcut for generating + * a list that can be used in a form. + * + * Date::months(); // 01, 02, 03, ..., 10, 11, 12 + * + * @uses Date::hours + * @return array A mirrored (foo => foo) array from 1-12. + */ + public static function months() + { + return Date::hours(); + } + + /** + * Returns an array of years between a starting and ending year. By default, + * the the current year - 5 and current year + 5 will be used. Typically used + * as a shortcut for generating a list that can be used in a form. + * + * $years = Date::years(2000, 2010); // 2000, 2001, ..., 2009, 2010 + * + * @param integer starting year (default is current year - 5) + * @param integer ending year (default is current year + 5) + * @return array + */ + public static function years($start = FALSE, $end = FALSE) + { + // Default values + $start = ($start === FALSE) ? (date('Y') - 5) : (int) $start; + $end = ($end === FALSE) ? (date('Y') + 5) : (int) $end; + + $years = array(); + + for ($i = $start; $i <= $end; $i++) + { + $years[$i] = (string) $i; + } + + return $years; + } + + /** + * Returns time difference between two timestamps, in human readable format. + * If the second timestamp is not given, the current time will be used. + * Also consider using [Date::fuzzy_span] when displaying a span. + * + * $span = Date::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2) + * $span = Date::span(60, 182, 'minutes'); // 2 + * + * @param integer timestamp to find the span of + * @param integer timestamp to use as the baseline + * @param string formatting string + * @return string when only a single output is requested + * @return array associative list of all outputs requested + */ + public static function span($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds') + { + // Normalize output + $output = trim(strtolower( (string) $output)); + + if ( ! $output) + { + // Invalid output + return FALSE; + } + + // Array with the output formats + $output = preg_split('/[^a-z]+/', $output); + + // Convert the list of outputs to an associative array + $output = array_combine($output, array_fill(0, count($output), 0)); + + // Make the output values into keys + extract(array_flip($output), EXTR_SKIP); + + if ($local === NULL) + { + // Calculate the span from the current time + $local = time(); + } + + // Calculate timespan (seconds) + $timespan = abs($remote - $local); + + if (isset($output['years'])) + { + $timespan -= Date::YEAR * ($output['years'] = (int) floor($timespan / Date::YEAR)); + } + + if (isset($output['months'])) + { + $timespan -= Date::MONTH * ($output['months'] = (int) floor($timespan / Date::MONTH)); + } + + if (isset($output['weeks'])) + { + $timespan -= Date::WEEK * ($output['weeks'] = (int) floor($timespan / Date::WEEK)); + } + + if (isset($output['days'])) + { + $timespan -= Date::DAY * ($output['days'] = (int) floor($timespan / Date::DAY)); + } + + if (isset($output['hours'])) + { + $timespan -= Date::HOUR * ($output['hours'] = (int) floor($timespan / Date::HOUR)); + } + + if (isset($output['minutes'])) + { + $timespan -= Date::MINUTE * ($output['minutes'] = (int) floor($timespan / Date::MINUTE)); + } + + // Seconds ago, 1 + if (isset($output['seconds'])) + { + $output['seconds'] = $timespan; + } + + if (count($output) === 1) + { + // Only a single output was requested, return it + return array_pop($output); + } + + // Return array + return $output; + } + + /** + * Returns the difference between a time and now in a "fuzzy" way. + * Displaying a fuzzy time instead of a date is usually faster to read and understand. + * + * $span = Date::fuzzy_span(time() - 10); // "moments ago" + * $span = Date::fuzzy_span(time() + 20); // "in moments" + * + * A second parameter is available to manually set the "local" timestamp, + * however this parameter shouldn't be needed in normal usage and is only + * included for unit tests + * + * @param integer "remote" timestamp + * @param integer "local" timestamp, defaults to time() + * @return string + */ + public static function fuzzy_span($timestamp, $local_timestamp = NULL) + { + $local_timestamp = ($local_timestamp === NULL) ? time() : (int) $local_timestamp; + + // Determine the difference in seconds + $offset = abs($local_timestamp - $timestamp); + + if ($offset <= Date::MINUTE) + { + $span = 'moments'; + } + elseif ($offset < (Date::MINUTE * 20)) + { + $span = 'a few minutes'; + } + elseif ($offset < Date::HOUR) + { + $span = 'less than an hour'; + } + elseif ($offset < (Date::HOUR * 4)) + { + $span = 'a couple of hours'; + } + elseif ($offset < Date::DAY) + { + $span = 'less than a day'; + } + elseif ($offset < (Date::DAY * 2)) + { + $span = 'about a day'; + } + elseif ($offset < (Date::DAY * 4)) + { + $span = 'a couple of days'; + } + elseif ($offset < Date::WEEK) + { + $span = 'less than a week'; + } + elseif ($offset < (Date::WEEK * 2)) + { + $span = 'about a week'; + } + elseif ($offset < Date::MONTH) + { + $span = 'less than a month'; + } + elseif ($offset < (Date::MONTH * 2)) + { + $span = 'about a month'; + } + elseif ($offset < (Date::MONTH * 4)) + { + $span = 'a couple of months'; + } + elseif ($offset < Date::YEAR) + { + $span = 'less than a year'; + } + elseif ($offset < (Date::YEAR * 2)) + { + $span = 'about a year'; + } + elseif ($offset < (Date::YEAR * 4)) + { + $span = 'a couple of years'; + } + elseif ($offset < (Date::YEAR * 8)) + { + $span = 'a few years'; + } + elseif ($offset < (Date::YEAR * 12)) + { + $span = 'about a decade'; + } + elseif ($offset < (Date::YEAR * 24)) + { + $span = 'a couple of decades'; + } + elseif ($offset < (Date::YEAR * 64)) + { + $span = 'several decades'; + } + else + { + $span = 'a long time'; + } + + if ($timestamp <= $local_timestamp) + { + // This is in the past + return $span.' ago'; + } + else + { + // This in the future + return 'in '.$span; + } + } + + /** + * Converts a UNIX timestamp to DOS format. There are very few cases where + * this is needed, but some binary formats use it (eg: zip files.) + * Converting the other direction is done using {@link Date::dos2unix}. + * + * $dos = Date::unix2dos($unix); + * + * @param integer UNIX timestamp + * @return integer + */ + public static function unix2dos($timestamp = FALSE) + { + $timestamp = ($timestamp === FALSE) ? getdate() : getdate($timestamp); + + if ($timestamp['year'] < 1980) + { + return (1 << 21 | 1 << 16); + } + + $timestamp['year'] -= 1980; + + // What voodoo is this? I have no idea... Geert can explain it though, + // and that's good enough for me. + return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 | + $timestamp['mday'] << 16 | $timestamp['hours'] << 11 | + $timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1); + } + + /** + * Converts a DOS timestamp to UNIX format.There are very few cases where + * this is needed, but some binary formats use it (eg: zip files.) + * Converting the other direction is done using {@link Date::unix2dos}. + * + * $unix = Date::dos2unix($dos); + * + * @param integer DOS timestamp + * @return integer + */ + public static function dos2unix($timestamp = FALSE) + { + $sec = 2 * ($timestamp & 0x1f); + $min = ($timestamp >> 5) & 0x3f; + $hrs = ($timestamp >> 11) & 0x1f; + $day = ($timestamp >> 16) & 0x1f; + $mon = ($timestamp >> 21) & 0x0f; + $year = ($timestamp >> 25) & 0x7f; + + return mktime($hrs, $min, $sec, $mon, $day, $year + 1980); + } + + /** + * Returns a date/time string with the specified timestamp format + * + * $time = Date::formatted_time('5 minutes ago'); + * + * @see http://php.net/manual/en/datetime.construct.php + * @param string datetime_str datetime string + * @param string timestamp_format timestamp format + * @return string + */ + public static function formatted_time($datetime_str = 'now', $timestamp_format = NULL, $timezone = NULL) + { + $timestamp_format = ($timestamp_format == NULL) ? Date::$timestamp_format : $timestamp_format; + $timezone = ($timezone === NULL) ? Date::$timezone : $timezone; + + $time = new DateTime($datetime_str, new DateTimeZone( + $timezone ? $timezone : date_default_timezone_get() + )); + + return $time->format($timestamp_format); + } + +} // End date diff --git a/includes/kohana/system/classes/kohana/encrypt.php b/includes/kohana/system/classes/kohana/encrypt.php new file mode 100644 index 0000000..c071f1d --- /dev/null +++ b/includes/kohana/system/classes/kohana/encrypt.php @@ -0,0 +1,213 @@ +$name; + + if ( ! isset($config['key'])) + { + // No default encryption key is provided! + throw new Kohana_Exception('No encryption key is defined in the encryption configuration group: :group', + array(':group' => $name)); + } + + if ( ! isset($config['mode'])) + { + // Add the default mode + $config['mode'] = MCRYPT_MODE_NOFB; + } + + if ( ! isset($config['cipher'])) + { + // Add the default cipher + $config['cipher'] = MCRYPT_RIJNDAEL_128; + } + + // Create a new instance + Encrypt::$instances[$name] = new Encrypt($config['key'], $config['mode'], $config['cipher']); + } + + return Encrypt::$instances[$name]; + } + + /** + * Creates a new mcrypt wrapper. + * + * @param string encryption key + * @param string mcrypt mode + * @param string mcrypt cipher + */ + public function __construct($key, $mode, $cipher) + { + // Find the max length of the key, based on cipher and mode + $size = mcrypt_get_key_size($cipher, $mode); + + if (isset($key[$size])) + { + // Shorten the key to the maximum size + $key = substr($key, 0, $size); + } + + // Store the key, mode, and cipher + $this->_key = $key; + $this->_mode = $mode; + $this->_cipher = $cipher; + + // Store the IV size + $this->_iv_size = mcrypt_get_iv_size($this->_cipher, $this->_mode); + } + + /** + * Encrypts a string and returns an encrypted string that can be decoded. + * + * $data = $encrypt->encode($data); + * + * The encrypted binary data is encoded using [base64](http://php.net/base64_encode) + * to convert it to a string. This string can be stored in a database, + * displayed, and passed using most other means without corruption. + * + * @param string data to be encrypted + * @return string + */ + public function encode($data) + { + // Set the rand type if it has not already been set + if (Encrypt::$_rand === NULL) + { + if (Kohana::$is_windows) + { + // Windows only supports the system random number generator + Encrypt::$_rand = MCRYPT_RAND; + } + else + { + if (defined('MCRYPT_DEV_URANDOM')) + { + // Use /dev/urandom + Encrypt::$_rand = MCRYPT_DEV_URANDOM; + } + elseif (defined('MCRYPT_DEV_RANDOM')) + { + // Use /dev/random + Encrypt::$_rand = MCRYPT_DEV_RANDOM; + } + else + { + // Use the system random number generator + Encrypt::$_rand = MCRYPT_RAND; + } + } + } + + if (Encrypt::$_rand === MCRYPT_RAND) + { + // The system random number generator must always be seeded each + // time it is used, or it will not produce true random results + mt_srand(); + } + + // Create a random initialization vector of the proper size for the current cipher + $iv = mcrypt_create_iv($this->_iv_size, Encrypt::$_rand); + + // Encrypt the data using the configured options and generated iv + $data = mcrypt_encrypt($this->_cipher, $this->_key, $data, $this->_mode, $iv); + + // Use base64 encoding to convert to a string + return base64_encode($iv.$data); + } + + /** + * Decrypts an encoded string back to its original value. + * + * $data = $encrypt->decode($data); + * + * @param string encoded string to be decrypted + * @return FALSE if decryption fails + * @return string + */ + public function decode($data) + { + // Convert the data back to binary + $data = base64_decode($data, TRUE); + + if ( ! $data) + { + // Invalid base64 data + return FALSE; + } + + // Extract the initialization vector from the data + $iv = substr($data, 0, $this->_iv_size); + + if ($this->_iv_size !== strlen($iv)) + { + // The iv is not the expected size + return FALSE; + } + + // Remove the iv from the data + $data = substr($data, $this->_iv_size); + + // Return the decrypted data, trimming the \0 padding bytes from the end of the data + return rtrim(mcrypt_decrypt($this->_cipher, $this->_key, $data, $this->_mode, $iv), "\0"); + } + +} // End Encrypt diff --git a/includes/kohana/system/classes/kohana/exception.php b/includes/kohana/system/classes/kohana/exception.php new file mode 100644 index 0000000..95ef633 --- /dev/null +++ b/includes/kohana/system/classes/kohana/exception.php @@ -0,0 +1,46 @@ + $user)); + * + * @param string error message + * @param array translation variables + * @param integer the exception code + * @return void + */ + public function __construct($message, array $variables = NULL, $code = 0) + { + // Set the message + $message = __($message, $variables); + + // Pass the message to the parent + parent::__construct($message, $code); + } + + /** + * Magic object-to-string method. + * + * echo $exception; + * + * @uses Kohana::exception_text + * @return string + */ + public function __toString() + { + return Kohana::exception_text($this); + } + +} // End Kohana_Exception diff --git a/includes/kohana/system/classes/kohana/feed.php b/includes/kohana/system/classes/kohana/feed.php new file mode 100644 index 0000000..6e3ea5c --- /dev/null +++ b/includes/kohana/system/classes/kohana/feed.php @@ -0,0 +1,176 @@ +getNamespaces(true); + + // Detect the feed type. RSS 1.0/2.0 and Atom 1.0 are supported. + $feed = isset($feed->channel) ? $feed->xpath('//item') : $feed->entry; + + $i = 0; + $items = array(); + + foreach ($feed as $item) + { + if ($limit > 0 AND $i++ === $limit) + break; + $item_fields = (array) $item; + + // get namespaced tags + foreach ($namespaces as $ns) + { + $item_fields += (array) $item->children($ns); + } + $items[] = $item_fields; + } + + return $items; + } + + /** + * Creates a feed from the given parameters. + * + * @param array feed information + * @param array items to add to the feed + * @param string define which format to use (only rss2 is supported) + * @param string define which encoding to use + * @return string + */ + public static function create($info, $items, $format = 'rss2', $encoding = 'UTF-8') + { + $info += array('title' => 'Generated Feed', 'link' => '', 'generator' => 'KohanaPHP'); + + $feed = ''; + $feed = simplexml_load_string($feed); + + foreach ($info as $name => $value) + { + if ($name === 'image') + { + // Create an image element + $image = $feed->channel->addChild('image'); + + if ( ! isset($value['link'], $value['url'], $value['title'])) + { + throw new Kohana_Exception('Feed images require a link, url, and title'); + } + + if (strpos($value['link'], '://') === FALSE) + { + // Convert URIs to URLs + $value['link'] = URL::site($value['link'], 'http'); + } + + if (strpos($value['url'], '://') === FALSE) + { + // Convert URIs to URLs + $value['url'] = URL::site($value['url'], 'http'); + } + + // Create the image elements + $image->addChild('link', $value['link']); + $image->addChild('url', $value['url']); + $image->addChild('title', $value['title']); + } + else + { + if (($name === 'pubDate' OR $name === 'lastBuildDate') AND (is_int($value) OR ctype_digit($value))) + { + // Convert timestamps to RFC 822 formatted dates + $value = date('r', $value); + } + elseif (($name === 'link' OR $name === 'docs') AND strpos($value, '://') === FALSE) + { + // Convert URIs to URLs + $value = URL::site($value, 'http'); + } + + // Add the info to the channel + $feed->channel->addChild($name, $value); + } + } + + foreach ($items as $item) + { + // Add the item to the channel + $row = $feed->channel->addChild('item'); + + foreach ($item as $name => $value) + { + if ($name === 'pubDate' AND (is_int($value) OR ctype_digit($value))) + { + // Convert timestamps to RFC 822 formatted dates + $value = date('r', $value); + } + elseif (($name === 'link' OR $name === 'guid') AND strpos($value, '://') === FALSE) + { + // Convert URIs to URLs + $value = URL::site($value, 'http'); + } + + // Add the info to the row + $row->addChild($name, $value); + } + } + + if (function_exists('dom_import_simplexml')) + { + // Convert the feed object to a DOM object + $feed = dom_import_simplexml($feed)->ownerDocument; + + // DOM generates more readable XML + $feed->formatOutput = TRUE; + + // Export the document as XML + $feed = $feed->saveXML(); + } + else + { + // Export the document as XML + $feed = $feed->asXML(); + } + + return $feed; + } + +} // End Feed diff --git a/includes/kohana/system/classes/kohana/file.php b/includes/kohana/system/classes/kohana/file.php new file mode 100644 index 0000000..066617d --- /dev/null +++ b/includes/kohana/system/classes/kohana/file.php @@ -0,0 +1,179 @@ +file($filename); + } + } + + if (ini_get('mime_magic.magicfile') AND function_exists('mime_content_type')) + { + // The mime_content_type function is only useful with a magic file + return mime_content_type($filename); + } + + if ( ! empty($extension)) + { + return File::mime_by_ext($extension); + } + + // Unable to find the mime-type + return FALSE; + } + + /** + * Return the mime type of an extension. + * + * $mime = File::mime_by_ext('png'); // "image/png" + * + * @param string extension: php, pdf, txt, etc + * @return string mime type on success + * @return FALSE on failure + */ + public static function mime_by_ext($extension) + { + // Load all of the mime types + $mimes = Kohana::config('mimes'); + + return isset($mimes[$extension]) ? $mimes[$extension][0] : FALSE; + } + + /** + * Split a file into pieces matching a specific size. Used when you need to + * split large files into smaller pieces for easy transmission. + * + * $count = File::split($file); + * + * @param string file to be split + * @param string directory to output to, defaults to the same directory as the file + * @param integer size, in MB, for each piece to be + * @return integer The number of pieces that were created + */ + public static function split($filename, $piece_size = 10) + { + // Open the input file + $file = fopen($filename, 'rb'); + + // Change the piece size to bytes + $piece_size = floor($piece_size * 1024 * 1024); + + // Write files in 8k blocks + $block_size = 1024 * 8; + + // Total number of peices + $peices = 0; + + while ( ! feof($file)) + { + // Create another piece + $peices += 1; + + // Create a new file piece + $piece = str_pad($peices, 3, '0', STR_PAD_LEFT); + $piece = fopen($filename.'.'.$piece, 'wb+'); + + // Number of bytes read + $read = 0; + + do + { + // Transfer the data in blocks + fwrite($piece, fread($file, $block_size)); + + // Another block has been read + $read += $block_size; + } + while ($read < $piece_size); + + // Close the piece + fclose($piece); + } + + // Close the file + fclose($file); + + return $peices; + } + + /** + * Join a split file into a whole file. Does the reverse of [File::split]. + * + * $count = File::join($file); + * + * @param string split filename, without .000 extension + * @param string output filename, if different then an the filename + * @return integer The number of pieces that were joined. + */ + public static function join($filename) + { + // Open the file + $file = fopen($filename, 'wb+'); + + // Read files in 8k blocks + $block_size = 1024 * 8; + + // Total number of peices + $pieces = 0; + + while (is_file($piece = $filename.'.'.str_pad($pieces + 1, 3, '0', STR_PAD_LEFT))) + { + // Read another piece + $pieces += 1; + + // Open the piece for reading + $piece = fopen($piece, 'rb'); + + while ( ! feof($piece)) + { + // Transfer the data in blocks + fwrite($file, fread($piece, $block_size)); + } + + // Close the peice + fclose($piece); + } + + return $pieces; + } + +} // End file diff --git a/includes/kohana/system/classes/kohana/form.php b/includes/kohana/system/classes/kohana/form.php new file mode 100644 index 0000000..27016de --- /dev/null +++ b/includes/kohana/system/classes/kohana/form.php @@ -0,0 +1,434 @@ + 'get')); + * + * // When "file" inputs are present, you must include the "enctype" + * echo Form::open(NULL, array('enctype' => 'multipart/form-data')); + * + * @param string form action, defaults to the current request URI + * @param array html attributes + * @return string + * @uses Request::instance + * @uses URL::site + * @uses HTML::attributes + */ + public static function open($action = NULL, array $attributes = NULL) + { + if ($action === NULL) + { + // Use the current URI + $action = Request::current()->uri; + } + + if ($action === '') + { + // Use only the base URI + $action = Kohana::$base_url; + } + elseif (strpos($action, '://') === FALSE) + { + // Make the URI absolute + $action = URL::site($action); + } + + // Add the form action to the attributes + $attributes['action'] = $action; + + // Only accept the default character set + $attributes['accept-charset'] = Kohana::$charset; + + if ( ! isset($attributes['method'])) + { + // Use POST method + $attributes['method'] = 'post'; + } + + return ''; + } + + /** + * Creates the closing form tag. + * + * echo Form::close(); + * + * @return string + */ + public static function close() + { + return ''; + } + + /** + * Creates a form input. If no type is specified, a "text" type input will + * be returned. + * + * echo Form::input('username', $username); + * + * @param string input name + * @param string input value + * @param array html attributes + * @return string + * @uses HTML::attributes + */ + public static function input($name, $value = NULL, array $attributes = NULL) + { + // Set the input name + $attributes['name'] = $name; + + // Set the input value + $attributes['value'] = $value; + + if ( ! isset($attributes['type'])) + { + // Default type is text + $attributes['type'] = 'text'; + } + + return ''; + } + + /** + * Creates a hidden form input. + * + * echo Form::hidden('csrf', $token); + * + * @param string input name + * @param string input value + * @param array html attributes + * @return string + * @uses Form::input + */ + public static function hidden($name, $value = NULL, array $attributes = NULL) + { + $attributes['type'] = 'hidden'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a password form input. + * + * echo Form::password('password'); + * + * @param string input name + * @param string input value + * @param array html attributes + * @return string + * @uses Form::input + */ + public static function password($name, $value = NULL, array $attributes = NULL) + { + $attributes['type'] = 'password'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a file upload form input. No input value can be specified. + * + * echo Form::file('image'); + * + * @param string input name + * @param array html attributes + * @return string + * @uses Form::input + */ + public static function file($name, array $attributes = NULL) + { + $attributes['type'] = 'file'; + + return Form::input($name, NULL, $attributes); + } + + /** + * Creates a checkbox form input. + * + * echo Form::checkbox('remember_me', 1, (bool) $remember); + * + * @param string input name + * @param string input value + * @param boolean checked status + * @param array html attributes + * @return string + * @uses Form::input + */ + public static function checkbox($name, $value = NULL, $checked = FALSE, array $attributes = NULL) + { + $attributes['type'] = 'checkbox'; + + if ($checked === TRUE) + { + // Make the checkbox active + $attributes['checked'] = 'checked'; + } + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a radio form input. + * + * echo Form::radio('like_cats', 1, $cats); + * echo Form::radio('like_cats', 0, ! $cats); + * + * @param string input name + * @param string input value + * @param boolean checked status + * @param array html attributes + * @return string + * @uses Form::input + */ + public static function radio($name, $value = NULL, $checked = FALSE, array $attributes = NULL) + { + $attributes['type'] = 'radio'; + + if ($checked === TRUE) + { + // Make the radio active + $attributes['checked'] = 'checked'; + } + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a textarea form input. + * + * echo Form::textarea('about', $about); + * + * @param string textarea name + * @param string textarea body + * @param array html attributes + * @param boolean encode existing HTML characters + * @return string + * @uses HTML::attributes + * @uses HTML::chars + */ + public static function textarea($name, $body = '', array $attributes = NULL, $double_encode = TRUE) + { + // Set the input name + $attributes['name'] = $name; + + // Add default rows and cols attributes (required) + $attributes += array('rows' => 10, 'cols' => 50); + + return ''.HTML::chars($body, $double_encode).''; + } + + /** + * Creates a select form input. + * + * echo Form::select('country', $countries, $country); + * + * [!!] Support for multiple selected options was added in v3.0.7. + * + * @param string input name + * @param array available options + * @param mixed selected option string, or an array of selected options + * @param array html attributes + * @return string + * @uses HTML::attributes + */ + public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL) + { + // Set the input name + $attributes['name'] = $name; + + if (is_array($selected)) + { + // This is a multi-select, god save us! + $attributes['multiple'] = 'multiple'; + } + + if ( ! is_array($selected)) + { + if ($selected === NULL) + { + // Use an empty array + $selected = array(); + } + else + { + // Convert the selected options to an array + $selected = array( (string) $selected); + } + } + + if (empty($options)) + { + // There are no options + $options = ''; + } + else + { + foreach ($options as $value => $name) + { + if (is_array($name)) + { + // Create a new optgroup + $group = array('label' => $value); + + // Create a new list of options + $_options = array(); + + foreach ($name as $_value => $_name) + { + // Force value to be string + $_value = (string) $_value; + + // Create a new attribute set for this option + $option = array('value' => $_value); + + if (in_array($_value, $selected)) + { + // This option is selected + $option['selected'] = 'selected'; + } + + // Change the option to the HTML string + $_options[] = ''.HTML::chars($_name, FALSE).''; + } + + // Compile the options into a string + $_options = "\n".implode("\n", $_options)."\n"; + + $options[$value] = ''.$_options.''; + } + else + { + // Force value to be string + $value = (string) $value; + + // Create a new attribute set for this option + $option = array('value' => $value); + + if (in_array($value, $selected)) + { + // This option is selected + $option['selected'] = 'selected'; + } + + // Change the option to the HTML string + $options[$value] = ''.HTML::chars($name, FALSE).''; + } + } + + // Compile the options into a single string + $options = "\n".implode("\n", $options)."\n"; + } + + return ''.$options.''; + } + + /** + * Creates a submit form input. + * + * echo Form::submit(NULL, 'Login'); + * + * @param string input name + * @param string input value + * @param array html attributes + * @return string + * @uses Form::input + */ + public static function submit($name, $value, array $attributes = NULL) + { + $attributes['type'] = 'submit'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a image form input. + * + * echo Form::image(NULL, NULL, array('src' => 'media/img/login.png')); + * + * @param string input name + * @param string input value + * @param array html attributes + * @param boolean add index file to URL? + * @return string + * @uses Form::input + */ + public static function image($name, $value, array $attributes = NULL, $index = FALSE) + { + if ( ! empty($attributes['src'])) + { + if (strpos($attributes['src'], '://') === FALSE) + { + // Add the base URL + $attributes['src'] = URL::base($index).$attributes['src']; + } + } + + $attributes['type'] = 'image'; + + return Form::input($name, $value, $attributes); + } + + /** + * Creates a button form input. Note that the body of a button is NOT escaped, + * to allow images and other HTML to be used. + * + * echo Form::button('save', 'Save Profile', array('type' => 'submit')); + * + * @param string input name + * @param string input value + * @param array html attributes + * @return string + * @uses HTML::attributes + */ + public static function button($name, $body, array $attributes = NULL) + { + // Set the input name + $attributes['name'] = $name; + + return ''.$body.''; + } + + /** + * Creates a form label. Label text is not automatically translated. + * + * echo Form::label('username', 'Username'); + * + * @param string target input + * @param string label text + * @param array html attributes + * @return string + * @uses HTML::attributes + */ + public static function label($input, $text = NULL, array $attributes = NULL) + { + if ($text === NULL) + { + // Use the input name as the text + $text = ucwords(preg_replace('/[\W_]+/', ' ', $input)); + } + + // Set the label target + $attributes['for'] = $input; + + return ''.$text.''; + } + +} // End form diff --git a/includes/kohana/system/classes/kohana/fragment.php b/includes/kohana/system/classes/kohana/fragment.php new file mode 100644 index 0000000..c2f2127 --- /dev/null +++ b/includes/kohana/system/classes/kohana/fragment.php @@ -0,0 +1,147 @@ + cache key + */ + protected static $_caches = array(); + + /** + * Generate the cache key name for a fragment. + * + * $key = Fragment::_cache_key('footer', TRUE); + * + * @param string fragment name + * @param boolean multilingual fragment support + * @return string + * @uses I18n::lang + * @since 3.0.4 + */ + protected static function _cache_key($name, $i18n = NULL) + { + if ($i18n === NULL) + { + // Use the default setting + $i18n = Fragment::$i18n; + } + + // Language prefix for cache key + $i18n = ($i18n === TRUE) ? I18n::lang() : ''; + + // Note: $i18n and $name need to be delimited to prevent naming collisions + return 'Fragment::cache('.$i18n.'+'.$name.')'; + } + + /** + * Load a fragment from cache and display it. Multiple fragments can + * be nested with different life times. + * + * if ( ! Fragment::load('footer')) { + * // Anything that is echo'ed here will be saved + * Fragment::save(); + * } + * + * @param string fragment name + * @param integer fragment cache lifetime + * @param boolean multilingual fragment support + * @return boolean + */ + public static function load($name, $lifetime = NULL, $i18n = NULL) + { + // Set the cache lifetime + $lifetime = ($lifetime === NULL) ? Fragment::$lifetime : (int) $lifetime; + + // Get the cache key name + $cache_key = Fragment::_cache_key($name, $i18n); + + if ($fragment = Kohana::cache($cache_key, NULL, $lifetime)) + { + // Display the cached fragment now + echo $fragment; + + return TRUE; + } + else + { + // Start the output buffer + ob_start(); + + // Store the cache key by the buffer level + Fragment::$_caches[ob_get_level()] = $cache_key; + + return FALSE; + } + } + + /** + * Saves the currently open fragment in the cache. + * + * Fragment::save(); + * + * @return void + */ + public static function save() + { + // Get the buffer level + $level = ob_get_level(); + + if (isset(Fragment::$_caches[$level])) + { + // Get the cache key based on the level + $cache_key = Fragment::$_caches[$level]; + + // Delete the cache key, we don't need it anymore + unset(Fragment::$_caches[$level]); + + // Get the output buffer and display it at the same time + $fragment = ob_get_flush(); + + // Cache the fragment + Kohana::cache($cache_key, $fragment); + } + } + + /** + * Delete a cached fragment. + * + * Fragment::delete($key); + * + * @param string fragment name + * @param boolean multilingual fragment support + * @return void + */ + public static function delete($name, $i18n = NULL) + { + // Invalid the cache + Kohana::cache(Fragment::_cache_key($name, $i18n), NULL, -3600); + } + +} // End Fragment diff --git a/includes/kohana/system/classes/kohana/html.php b/includes/kohana/system/classes/kohana/html.php new file mode 100644 index 0000000..5495ed6 --- /dev/null +++ b/includes/kohana/system/classes/kohana/html.php @@ -0,0 +1,380 @@ +'.$title.''; + } + + /** + * Creates an HTML anchor to a file. Note that the title is not escaped, + * to allow HTML elements within links (images, etc). + * + * echo HTML::file_anchor('media/doc/user_guide.pdf', 'User Guide'); + * + * @param string name of file to link to + * @param string link text + * @param array HTML anchor attributes + * @param string non-default protocol, eg: ftp + * @return string + * @uses URL::base + * @uses HTML::attributes + */ + public static function file_anchor($file, $title = NULL, array $attributes = NULL, $protocol = NULL) + { + if ($title === NULL) + { + // Use the file name as the title + $title = basename($file); + } + + // Add the file link to the attributes + $attributes['href'] = URL::base(FALSE, $protocol).$file; + + return ''.$title.''; + } + + /** + * Generates an obfuscated version of a string. Text passed through this + * method is less likely to be read by web crawlers and robots, which can + * be helpful for spam prevention, but can prevent legitimate robots from + * reading your content. + * + * echo HTML::obfuscate($text); + * + * @param string string to obfuscate + * @return string + * @since 3.0.3 + */ + public static function obfuscate($string) + { + $safe = ''; + foreach (str_split($string) as $letter) + { + switch (rand(1, 3)) + { + // HTML entity code + case 1: + $safe .= '&#'.ord($letter).';'; + break; + + // Hex character code + case 2: + $safe .= '&#x'.dechex(ord($letter)).';'; + break; + + // Raw (no) encoding + case 3: + $safe .= $letter; + } + } + + return $safe; + } + + /** + * Generates an obfuscated version of an email address. Helps prevent spam + * robots from finding email addresses. + * + * echo HTML::email($address); + * + * @param string email address + * @return string + * @uses HTML::obfuscate + */ + public static function email($email) + { + // Make sure the at sign is always obfuscated + return str_replace('@', '@', HTML::obfuscate($email)); + } + + /** + * Creates an email (mailto:) anchor. Note that the title is not escaped, + * to allow HTML elements within links (images, etc). + * + * echo HTML::mailto($address); + * + * @param string email address to send to + * @param string link text + * @param array HTML anchor attributes + * @return string + * @uses HTML::email + * @uses HTML::attributes + */ + public static function mailto($email, $title = NULL, array $attributes = NULL) + { + // Obfuscate email address + $email = HTML::email($email); + + if ($title === NULL) + { + // Use the email address as the title + $title = $email; + } + + return ''.$title.''; + } + + /** + * Creates a style sheet link element. + * + * echo HTML::style('media/css/screen.css'); + * + * @param string file name + * @param array default attributes + * @param boolean include the index page + * @return string + * @uses URL::base + * @uses HTML::attributes + */ + public static function style($file, array $attributes = NULL, $index = FALSE) + { + if (strpos($file, '://') === FALSE) + { + // Add the base URL + $file = URL::base($index).$file; + } + + // Set the stylesheet link + $attributes['href'] = $file; + + // Set the stylesheet rel + $attributes['rel'] = 'stylesheet'; + + // Set the stylesheet type + $attributes['type'] = 'text/css'; + + return ''; + } + + /** + * Creates a script link. + * + * echo HTML::script('media/js/jquery.min.js'); + * + * @param string file name + * @param array default attributes + * @param boolean include the index page + * @return string + * @uses URL::base + * @uses HTML::attributes + */ + public static function script($file, array $attributes = NULL, $index = FALSE) + { + if (strpos($file, '://') === FALSE) + { + // Add the base URL + $file = URL::base($index).$file; + } + + // Set the script link + $attributes['src'] = $file; + + // Set the script type + $attributes['type'] = 'text/javascript'; + + return ''; + } + + /** + * Creates a image link. + * + * echo HTML::image('media/img/logo.png', array('alt' => 'My Company')); + * + * @param string file name + * @param array default attributes + * @return string + * @uses URL::base + * @uses HTML::attributes + */ + public static function image($file, array $attributes = NULL, $index = FALSE) + { + if (strpos($file, '://') === FALSE) + { + // Add the base URL + $file = URL::base($index).$file; + } + + // Add the image link + $attributes['src'] = $file; + + return ''; + } + + /** + * Compiles an array of HTML attributes into an attribute string. + * Attributes will be sorted using HTML::$attribute_order for consistency. + * + * echo ''.$content.'
    '; + * + * @param array attribute list + * @return string + */ + public static function attributes(array $attributes = NULL) + { + if (empty($attributes)) + return ''; + + $sorted = array(); + foreach (HTML::$attribute_order as $key) + { + if (isset($attributes[$key])) + { + // Add the attribute to the sorted list + $sorted[$key] = $attributes[$key]; + } + } + + // Combine the sorted attributes + $attributes = $sorted + $attributes; + + $compiled = ''; + foreach ($attributes as $key => $value) + { + if ($value === NULL) + { + // Skip attributes that have NULL values + continue; + } + + if (is_int($key)) + { + // Assume non-associative keys are mirrored attributes + $key = $value; + } + + // Add the attribute value + $compiled .= ' '.$key.'="'.HTML::chars($value).'"'; + } + + return $compiled; + } + +} // End html diff --git a/includes/kohana/system/classes/kohana/i18n.php b/includes/kohana/system/classes/kohana/i18n.php new file mode 100644 index 0000000..f9a06bb --- /dev/null +++ b/includes/kohana/system/classes/kohana/i18n.php @@ -0,0 +1,139 @@ + $username)); + * + * [!!] The __() function is declared in `SYSPATH/base.php`. + * + * @package Kohana + * @category Base + * @author Kohana Team + * @copyright (c) 2008-2010 Kohana Team + * @license http://kohanaframework.org/license + */ +class Kohana_I18n { + + /** + * @var string target language: en-us, es-es, zh-cn, etc + */ + public static $lang = 'en-us'; + + /** + * @var string source language: en-us, es-es, zh-cn, etc + */ + public static $source = 'en-us'; + + /** + * @var array cache of loaded languages + */ + protected static $_cache = array(); + + /** + * Get and set the target language. + * + * // Get the current language + * $lang = I18n::lang(); + * + * // Change the current language to Spanish + * I18n::lang('es-es'); + * + * @param string new language setting + * @return string + * @since 3.0.2 + */ + public static function lang($lang = NULL) + { + if ($lang) + { + // Normalize the language + I18n::$lang = strtolower(str_replace(array(' ', '_'), '-', $lang)); + } + + return I18n::$lang; + } + + /** + * Returns translation of a string. If no translation exists, the original + * string will be returned. No parameters are replaced. + * + * $hello = I18n::get('Hello friends, my name is :name'); + * + * @param string text to translate + * @param string target language + * @return string + */ + public static function get($string, $lang = NULL) + { + if ( ! $lang) + { + // Use the global target language + $lang = I18n::$lang; + } + + // Load the translation table for this language + $table = I18n::load($lang); + + // Return the translated string if it exists + return isset($table[$string]) ? $table[$string] : $string; + } + + /** + * Returns the translation table for a given language. + * + * // Get all defined Spanish messages + * $messages = I18n::load('es-es'); + * + * @param string language to load + * @return array + */ + public static function load($lang) + { + if (isset(I18n::$_cache[$lang])) + { + return I18n::$_cache[$lang]; + } + + // New translation table + $table = array(); + + // Split the language: language, region, locale, etc + $parts = explode('-', $lang); + + do + { + // Create a path for this set of parts + $path = implode(DIRECTORY_SEPARATOR, $parts); + + if ($files = Kohana::find_file('i18n', $path, NULL, TRUE)) + { + $t = array(); + foreach ($files as $file) + { + // Merge the language strings into the sub table + $t = array_merge($t, Kohana::load($file)); + } + + // Append the sub table, preventing less specific language + // files from overloading more specific files + $table += $t; + } + + // Remove the last part + array_pop($parts); + } + while ($parts); + + // Cache the translation table locally + return I18n::$_cache[$lang] = $table; + } + +} // End I18n diff --git a/includes/kohana/system/classes/kohana/inflector.php b/includes/kohana/system/classes/kohana/inflector.php new file mode 100644 index 0000000..5edd618 --- /dev/null +++ b/includes/kohana/system/classes/kohana/inflector.php @@ -0,0 +1,269 @@ +uncountable; + + // Make uncountables mirrored + Inflector::$uncountable = array_combine(Inflector::$uncountable, Inflector::$uncountable); + } + + return isset(Inflector::$uncountable[strtolower($str)]); + } + + /** + * Makes a plural word singular. + * + * echo Inflector::singular('cats'); // "cat" + * echo Inflector::singular('fish'); // "fish", uncountable + * + * You can also provide the count to make inflection more intelligent. + * In this case, it will only return the singular value if the count is + * greater than one and not zero. + * + * echo Inflector::singular('cats', 2); // "cats" + * + * [!!] Special inflections are defined in `config/inflector.php`. + * + * @param string word to singularize + * @param integer count of thing + * @return string + * @uses Inflector::uncountable + */ + public static function singular($str, $count = NULL) + { + // $count should always be a float + $count = ($count === NULL) ? 1.0 : (float) $count; + + // Do nothing when $count is not 1 + if ($count != 1) + return $str; + + // Remove garbage + $str = strtolower(trim($str)); + + // Cache key name + $key = 'singular_'.$str.$count; + + if (isset(Inflector::$cache[$key])) + return Inflector::$cache[$key]; + + if (Inflector::uncountable($str)) + return Inflector::$cache[$key] = $str; + + if (empty(Inflector::$irregular)) + { + // Cache irregular words + Inflector::$irregular = Kohana::config('inflector')->irregular; + } + + if ($irregular = array_search($str, Inflector::$irregular)) + { + $str = $irregular; + } + elseif (preg_match('/us$/', $str)) + { + // http://en.wikipedia.org/wiki/Plural_form_of_words_ending_in_-us + // Already singular, do nothing + } + elseif (preg_match('/[sxz]es$/', $str) OR preg_match('/[^aeioudgkprt]hes$/', $str)) + { + // Remove "es" + $str = substr($str, 0, -2); + } + elseif (preg_match('/[^aeiou]ies$/', $str)) + { + // Replace "ies" with "y" + $str = substr($str, 0, -3).'y'; + } + elseif (substr($str, -1) === 's' AND substr($str, -2) !== 'ss') + { + // Remove singular "s" + $str = substr($str, 0, -1); + } + + return Inflector::$cache[$key] = $str; + } + + /** + * Makes a singular word plural. + * + * echo Inflector::plural('fish'); // "fish", uncountable + * echo Inflector::plural('cat'); // "cats" + * + * You can also provide the count to make inflection more intelligent. + * In this case, it will only return the plural value if the count is + * not one. + * + * echo Inflector::singular('cats', 3); // "cats" + * + * [!!] Special inflections are defined in `config/inflector.php`. + * + * @param string word to pluralize + * @param integer count of thing + * @return string + * @uses Inflector::uncountable + */ + public static function plural($str, $count = NULL) + { + // $count should always be a float + $count = ($count === NULL) ? 0.0 : (float) $count; + + // Do nothing with singular + if ($count == 1) + return $str; + + // Remove garbage + $str = trim($str); + + // Cache key name + $key = 'plural_'.$str.$count; + + // Check uppercase + $is_uppercase = ctype_upper($str); + + if (isset(Inflector::$cache[$key])) + return Inflector::$cache[$key]; + + if (Inflector::uncountable($str)) + return Inflector::$cache[$key] = $str; + + if (empty(Inflector::$irregular)) + { + // Cache irregular words + Inflector::$irregular = Kohana::config('inflector')->irregular; + } + + if (isset(Inflector::$irregular[$str])) + { + $str = Inflector::$irregular[$str]; + } + elseif (preg_match('/[sxz]$/', $str) OR preg_match('/[^aeioudgkprt]h$/', $str)) + { + $str .= 'es'; + } + elseif (preg_match('/[^aeiou]y$/', $str)) + { + // Change "y" to "ies" + $str = substr_replace($str, 'ies', -1); + } + else + { + $str .= 's'; + } + + // Convert to uppsecase if nessasary + if ($is_uppercase) + { + $str = strtoupper($str); + } + + // Set the cache and return + return Inflector::$cache[$key] = $str; + } + + /** + * Makes a phrase camel case. Spaces and underscores will be removed. + * + * $str = Inflector::camelize('mother cat'); // "motherCat" + * $str = Inflector::camelize('kittens in bed'); // "kittensInBed" + * + * @param string phrase to camelize + * @return string + */ + public static function camelize($str) + { + $str = 'x'.strtolower(trim($str)); + $str = ucwords(preg_replace('/[\s_]+/', ' ', $str)); + + return substr(str_replace(' ', '', $str), 1); + } + + /** + * Converts a camel case phrase into a spaced phrase. + * + * $str = Inflector::decamelize('houseCat'); // "house cat" + * $str = Inflector::decamelize('kingAllyCat'); // "king ally cat" + * + * @param string phrase to camelize + * @param string word separator + * @return string + */ + public static function decamelize($str, $sep = ' ') + { + return strtolower(preg_replace('/([a-z])([A-Z])/', '$1'.$sep.'$2', trim($str))); + } + + /** + * Makes a phrase underscored instead of spaced. + * + * $str = Inflector::underscore('five cats'); // "five_cats"; + * + * @param string phrase to underscore + * @return string + */ + public static function underscore($str) + { + return preg_replace('/\s+/', '_', trim($str)); + } + + /** + * Makes an underscored or dashed phrase human-readable. + * + * $str = Inflector::humanize('kittens-are-cats'); // "kittens are cats" + * $str = Inflector::humanize('dogs_as_well'); // "dogs as well" + * + * @param string phrase to make human-readable + * @return string + */ + public static function humanize($str) + { + return preg_replace('/[_-]+/', ' ', trim($str)); + } + +} // End Inflector diff --git a/includes/kohana/system/classes/kohana/log.php b/includes/kohana/system/classes/kohana/log.php new file mode 100644 index 0000000..50f9b6f --- /dev/null +++ b/includes/kohana/system/classes/kohana/log.php @@ -0,0 +1,189 @@ +attach($writer); + * + * @param object Kohana_Log_Writer instance + * @param array messages types to write + * @return Kohana_Log + */ + public function attach(Kohana_Log_Writer $writer, array $types = NULL) + { + $this->_writers["{$writer}"] = array + ( + 'object' => $writer, + 'types' => $types + ); + + return $this; + } + + /** + * Detaches a log writer. The same writer object must be used. + * + * $log->detach($writer); + * + * @param object Kohana_Log_Writer instance + * @return Kohana_Log + */ + public function detach(Kohana_Log_Writer $writer) + { + // Remove the writer + unset($this->_writers["{$writer}"]); + + return $this; + } + + /** + * Adds a message to the log. Replacement values must be passed in to be + * replaced using [strtr](http://php.net/strtr). + * + * $log->add('error', 'Could not locate user: :user', array( + * ':user' => $username, + * )); + * + * @param string type of message + * @param string message body + * @param array values to replace in the message + * @return Kohana_Log + */ + public function add($type, $message, array $values = NULL) + { + if ($values) + { + // Insert the values into the message + $message = strtr($message, $values); + } + + // Create a new message and timestamp it + $this->_messages[] = array + ( + 'time' => Date::formatted_time('now', self::$timestamp, self::$timezone), + 'type' => $type, + 'body' => $message, + ); + + if (self::$write_on_add) + { + // Write logs as they are added + $this->write(); + } + + return $this; + } + + /** + * Write and clear all of the messages. + * + * $log->write(); + * + * @return void + */ + public function write() + { + if (empty($this->_messages)) + { + // There is nothing to write, move along + return; + } + + // Import all messages locally + $messages = $this->_messages; + + // Reset the messages array + $this->_messages = array(); + + foreach ($this->_writers as $writer) + { + if (empty($writer['types'])) + { + // Write all of the messages + $writer['object']->write($messages); + } + else + { + // Filtered messages + $filtered = array(); + + foreach ($messages as $message) + { + if (in_array($message['type'], $writer['types'])) + { + // Writer accepts this kind of message + $filtered[] = $message; + } + } + + // Write the filtered messages + $writer['object']->write($filtered); + } + } + } + +} // End Kohana_Log diff --git a/includes/kohana/system/classes/kohana/log/file.php b/includes/kohana/system/classes/kohana/log/file.php new file mode 100644 index 0000000..488d9ad --- /dev/null +++ b/includes/kohana/system/classes/kohana/log/file.php @@ -0,0 +1,97 @@ + Kohana::debug_path($directory))); + } + + // Determine the directory path + $this->_directory = realpath($directory).DIRECTORY_SEPARATOR; + } + + /** + * Writes each of the messages into the log file. The log file will be + * appended to the `YYYY/MM/DD.log.php` file, where YYYY is the current + * year, MM is the current month, and DD is the current day. + * + * $writer->write($messages); + * + * @param array messages + * @return void + */ + public function write(array $messages) + { + // Set the yearly directory name + $directory = $this->_directory.date('Y'); + + if ( ! is_dir($directory)) + { + // Create the yearly directory + mkdir($directory, 02777); + + // Set permissions (must be manually set to fix umask issues) + chmod($directory, 02777); + } + + // Add the month to the directory + $directory .= DIRECTORY_SEPARATOR.date('m'); + + if ( ! is_dir($directory)) + { + // Create the yearly directory + mkdir($directory, 02777); + + // Set permissions (must be manually set to fix umask issues) + chmod($directory, 02777); + } + + // Set the name of the log file + $filename = $directory.DIRECTORY_SEPARATOR.date('d').EXT; + + if ( ! file_exists($filename)) + { + // Create the log file + file_put_contents($filename, Kohana::FILE_SECURITY.' ?>'.PHP_EOL); + + // Allow anyone to write to log files + chmod($filename, 0666); + } + + // Set the log line format + $format = 'time --- type: body'; + + foreach ($messages as $message) + { + // Write each message into the log file + file_put_contents($filename, PHP_EOL.strtr($format, $message), FILE_APPEND); + } + } + +} // End Kohana_Log_File \ No newline at end of file diff --git a/includes/kohana/system/classes/kohana/log/stderr.php b/includes/kohana/system/classes/kohana/log/stderr.php new file mode 100644 index 0000000..e11ce6e --- /dev/null +++ b/includes/kohana/system/classes/kohana/log/stderr.php @@ -0,0 +1,31 @@ +write($messages); + * + * @param array messages + * @return void + */ + public function write(array $messages) + { + // Set the log line format + $format = 'time --- type: body'; + + foreach ($messages as $message) + { + // Writes out each message + fwrite(STDERR, PHP_EOL.strtr($format, $message)); + } + } +} // End Kohana_Log_StdErr diff --git a/includes/kohana/system/classes/kohana/log/stdout.php b/includes/kohana/system/classes/kohana/log/stdout.php new file mode 100644 index 0000000..d8cddd1 --- /dev/null +++ b/includes/kohana/system/classes/kohana/log/stdout.php @@ -0,0 +1,31 @@ +write($messages); + * + * @param array messages + * @return void + */ + public function write(array $messages) + { + // Set the log line format + $format = 'time --- type: body'; + + foreach ($messages as $message) + { + // Writes out each message + fwrite(STDOUT, PHP_EOL.strtr($format, $message)); + } + } +} // End Kohana_Log_StdOut diff --git a/includes/kohana/system/classes/kohana/log/syslog.php b/includes/kohana/system/classes/kohana/log/syslog.php new file mode 100644 index 0000000..afb1149 --- /dev/null +++ b/includes/kohana/system/classes/kohana/log/syslog.php @@ -0,0 +1,70 @@ + LOG_ERR, + 'CRITICAL' => LOG_CRIT, + 'STRACE' => LOG_ALERT, + 'ALERT' => LOG_WARNING, + 'INFO' => LOG_INFO, + 'DEBUG' => LOG_DEBUG); + + /** + * Creates a new syslog logger. + * + * @see http://us2.php.net/openlog + * + * @param string syslog identifier + * @param int facility to log to + * @return void + */ + public function __construct($ident = 'KohanaPHP', $facility = LOG_USER) + { + $this->_ident = $ident; + + // Open the connection to syslog + openlog($this->_ident, LOG_CONS, $facility); + } + + /** + * Writes each of the messages into the syslog. + * + * @param array messages + * @return void + */ + public function write(array $messages) + { + foreach ($messages as $message) + { + syslog($this->_syslog_levels[$message['type']], $message['body']); + } + } + + /** + * Closes the syslog connection + * + * @return void + */ + public function __destruct() + { + // Close connection to syslog + closelog(); + } + +} // End Kohana_Log_Syslog \ No newline at end of file diff --git a/includes/kohana/system/classes/kohana/log/writer.php b/includes/kohana/system/classes/kohana/log/writer.php new file mode 100644 index 0000000..00ca3a9 --- /dev/null +++ b/includes/kohana/system/classes/kohana/log/writer.php @@ -0,0 +1,35 @@ +write($messages); + * + * @param array messages + * @return void + */ + abstract public function write(array $messages); + + /** + * Allows the writer to have a unique key when stored. + * + * echo $writer; + * + * @return string + */ + final public function __toString() + { + return spl_object_hash($this); + } + +} // End Kohana_Log_Writer diff --git a/includes/kohana/system/classes/kohana/model.php b/includes/kohana/system/classes/kohana/model.php new file mode 100644 index 0000000..7270df0 --- /dev/null +++ b/includes/kohana/system/classes/kohana/model.php @@ -0,0 +1,65 @@ +_db = $db; + } + elseif ( ! $this->_db) + { + // Use the global database + $this->_db = Database::$default; + } + + if (is_string($this->_db)) + { + // Load the database + $this->_db = Database::instance($this->_db); + } + } + +} // End Model diff --git a/includes/kohana/system/classes/kohana/num.php b/includes/kohana/system/classes/kohana/num.php new file mode 100644 index 0000000..80094e3 --- /dev/null +++ b/includes/kohana/system/classes/kohana/num.php @@ -0,0 +1,81 @@ + 10 AND $number % 100 < 14) + { + return 'th'; + } + + switch ($number % 10) + { + case 1: + return 'st'; + case 2: + return 'nd'; + case 3: + return 'rd'; + default: + return 'th'; + } + } + + /** + * Locale-aware number and monetary formatting. + * + * // In English, "1,200.05" + * // In Spanish, "1200,05" + * // In Portuguese, "1 200,05" + * echo Num::format(1200.05, 2); + * + * // In English, "1,200.05" + * // In Spanish, "1.200,05" + * // In Portuguese, "1.200.05" + * echo Num::format(1200.05, 2, TRUE); + * + * @param float number to format + * @param integer decimal places + * @param boolean monetary formatting? + * @return string + * @since 3.0.2 + */ + public static function format($number, $places, $monetary = FALSE) + { + $info = localeconv(); + + if ($monetary) + { + $decimal = $info['mon_decimal_point']; + $thousands = $info['mon_thousands_sep']; + } + else + { + $decimal = $info['decimal_point']; + $thousands = $info['thousands_sep']; + } + + return number_format($number, $places, $decimal, $thousands); + } + +} // End num diff --git a/includes/kohana/system/classes/kohana/profiler.php b/includes/kohana/system/classes/kohana/profiler.php new file mode 100644 index 0000000..481ac9d --- /dev/null +++ b/includes/kohana/system/classes/kohana/profiler.php @@ -0,0 +1,385 @@ + strtolower($group), + 'name' => (string) $name, + + // Start the benchmark + 'start_time' => microtime(TRUE), + 'start_memory' => memory_get_usage(), + + // Set the stop keys without values + 'stop_time' => FALSE, + 'stop_memory' => FALSE, + ); + + return $token; + } + + /** + * Stops a benchmark. + * + * Profiler::stop($token); + * + * @param string token + * @return void + */ + public static function stop($token) + { + // Stop the benchmark + Profiler::$_marks[$token]['stop_time'] = microtime(TRUE); + Profiler::$_marks[$token]['stop_memory'] = memory_get_usage(); + } + + /** + * Deletes a benchmark. If an error occurs during the benchmark, it is + * recommended to delete the benchmark to prevent statistics from being + * adversely affected. + * + * Profiler::delete($token); + * + * @param string token + * @return void + */ + public static function delete($token) + { + // Remove the benchmark + unset(Profiler::$_marks[$token]); + } + + /** + * Returns all the benchmark tokens by group and name as an array. + * + * $groups = Profiler::groups(); + * + * @return array + */ + public static function groups() + { + $groups = array(); + + foreach (Profiler::$_marks as $token => $mark) + { + // Sort the tokens by the group and name + $groups[$mark['group']][$mark['name']][] = $token; + } + + return $groups; + } + + /** + * Gets the min, max, average and total of a set of tokens as an array. + * + * $stats = Profiler::stats($tokens); + * + * @param array profiler tokens + * @return array min, max, average, total + * @uses Profiler::total + */ + public static function stats(array $tokens) + { + // Min and max are unknown by default + $min = $max = array( + 'time' => NULL, + 'memory' => NULL); + + // Total values are always integers + $total = array( + 'time' => 0, + 'memory' => 0); + + foreach ($tokens as $token) + { + // Get the total time and memory for this benchmark + list($time, $memory) = Profiler::total($token); + + if ($max['time'] === NULL OR $time > $max['time']) + { + // Set the maximum time + $max['time'] = $time; + } + + if ($min['time'] === NULL OR $time < $min['time']) + { + // Set the minimum time + $min['time'] = $time; + } + + // Increase the total time + $total['time'] += $time; + + if ($max['memory'] === NULL OR $memory > $max['memory']) + { + // Set the maximum memory + $max['memory'] = $memory; + } + + if ($min['memory'] === NULL OR $memory < $min['memory']) + { + // Set the minimum memory + $min['memory'] = $memory; + } + + // Increase the total memory + $total['memory'] += $memory; + } + + // Determine the number of tokens + $count = count($tokens); + + // Determine the averages + $average = array( + 'time' => $total['time'] / $count, + 'memory' => $total['memory'] / $count); + + return array( + 'min' => $min, + 'max' => $max, + 'total' => $total, + 'average' => $average); + } + + /** + * Gets the min, max, average and total of profiler groups as an array. + * + * $stats = Profiler::group_stats('test'); + * + * @param mixed single group name string, or array with group names; all groups by default + * @return array min, max, average, total + * @uses Profiler::groups + * @uses Profiler::stats + */ + public static function group_stats($groups = NULL) + { + // Which groups do we need to calculate stats for? + $groups = ($groups === NULL) + ? Profiler::groups() + : array_intersect_key(Profiler::groups(), array_flip( (array) $groups)); + + // All statistics + $stats = array(); + + foreach ($groups as $group => $names) + { + foreach ($names as $name => $tokens) + { + // Store the stats for each subgroup. + // We only need the values for "total". + $_stats = Profiler::stats($tokens); + $stats[$group][$name] = $_stats['total']; + } + } + + // Group stats + $groups = array(); + + foreach ($stats as $group => $names) + { + // Min and max are unknown by default + $groups[$group]['min'] = $groups[$group]['max'] = array( + 'time' => NULL, + 'memory' => NULL); + + // Total values are always integers + $groups[$group]['total'] = array( + 'time' => 0, + 'memory' => 0); + + foreach ($names as $total) + { + if ( ! isset($groups[$group]['min']['time']) OR $groups[$group]['min']['time'] > $total['time']) + { + // Set the minimum time + $groups[$group]['min']['time'] = $total['time']; + } + if ( ! isset($groups[$group]['min']['memory']) OR $groups[$group]['min']['memory'] > $total['memory']) + { + // Set the minimum memory + $groups[$group]['min']['memory'] = $total['memory']; + } + + if ( ! isset($groups[$group]['max']['time']) OR $groups[$group]['max']['time'] < $total['time']) + { + // Set the maximum time + $groups[$group]['max']['time'] = $total['time']; + } + if ( ! isset($groups[$group]['max']['memory']) OR $groups[$group]['max']['memory'] < $total['memory']) + { + // Set the maximum memory + $groups[$group]['max']['memory'] = $total['memory']; + } + + // Increase the total time and memory + $groups[$group]['total']['time'] += $total['time']; + $groups[$group]['total']['memory'] += $total['memory']; + } + + // Determine the number of names (subgroups) + $count = count($names); + + // Determine the averages + $groups[$group]['average']['time'] = $groups[$group]['total']['time'] / $count; + $groups[$group]['average']['memory'] = $groups[$group]['total']['memory'] / $count; + } + + return $groups; + } + + /** + * Gets the total execution time and memory usage of a benchmark as a list. + * + * list($time, $memory) = Profiler::total($token); + * + * @param string token + * @return array execution time, memory + */ + public static function total($token) + { + // Import the benchmark data + $mark = Profiler::$_marks[$token]; + + if ($mark['stop_time'] === FALSE) + { + // The benchmark has not been stopped yet + $mark['stop_time'] = microtime(TRUE); + $mark['stop_memory'] = memory_get_usage(); + } + + return array + ( + // Total time in seconds + $mark['stop_time'] - $mark['start_time'], + + // Amount of memory in bytes + $mark['stop_memory'] - $mark['start_memory'], + ); + } + + /** + * Gets the total application run time and memory usage. Caches the result + * so that it can be compared between requests. + * + * list($time, $memory) = Profiler::application(); + * + * @return array execution time, memory + * @uses Kohana::cache + */ + public static function application() + { + // Load the stats from cache, which is valid for 1 day + $stats = Kohana::cache('profiler_application_stats', NULL, 3600 * 24); + + if ( ! is_array($stats) OR $stats['count'] > Profiler::$rollover) + { + // Initialize the stats array + $stats = array( + 'min' => array( + 'time' => NULL, + 'memory' => NULL), + 'max' => array( + 'time' => NULL, + 'memory' => NULL), + 'total' => array( + 'time' => NULL, + 'memory' => NULL), + 'count' => 0); + } + + // Get the application run time + $time = microtime(TRUE) - KOHANA_START_TIME; + + // Get the total memory usage + $memory = memory_get_usage() - KOHANA_START_MEMORY; + + // Calculate max time + if ($stats['max']['time'] === NULL OR $time > $stats['max']['time']) + { + $stats['max']['time'] = $time; + } + + // Calculate min time + if ($stats['min']['time'] === NULL OR $time < $stats['min']['time']) + { + $stats['min']['time'] = $time; + } + + // Add to total time + $stats['total']['time'] += $time; + + // Calculate max memory + if ($stats['max']['memory'] === NULL OR $memory > $stats['max']['memory']) + { + $stats['max']['memory'] = $memory; + } + + // Calculate min memory + if ($stats['min']['memory'] === NULL OR $memory < $stats['min']['memory']) + { + $stats['min']['memory'] = $memory; + } + + // Add to total memory + $stats['total']['memory'] += $memory; + + // Another mark has been added to the stats + $stats['count']++; + + // Determine the averages + $stats['average'] = array( + 'time' => $stats['total']['time'] / $stats['count'], + 'memory' => $stats['total']['memory'] / $stats['count']); + + // Cache the new stats + Kohana::cache('profiler_application_stats', $stats); + + // Set the current application execution time and memory + // Do NOT cache these, they are specific to the current request only + $stats['current']['time'] = $time; + $stats['current']['memory'] = $memory; + + // Return the total application run time and memory usage + return $stats; + } + +} // End Profiler diff --git a/includes/kohana/system/classes/kohana/remote.php b/includes/kohana/system/classes/kohana/remote.php new file mode 100644 index 0000000..bfecec3 --- /dev/null +++ b/includes/kohana/system/classes/kohana/remote.php @@ -0,0 +1,154 @@ + 'Mozilla/5.0 (compatible; Kohana v3.0 +http://kohanaframework.org/)', + CURLOPT_CONNECTTIMEOUT => 5, + CURLOPT_TIMEOUT => 5, + ); + + /** + * Returns the output of a remote URL. Any [curl option](http://php.net/curl_setopt) + * may be used. + * + * // Do a simple GET request + * $data = Remote::get($url); + * + * // Do a POST request + * $data = Remote::get($url, array( + * CURLOPT_POST => TRUE, + * CURLOPT_POSTFIELDS => http_build_query($array), + * )); + * + * @param string remote URL + * @param array curl options + * @return string + * @throws Kohana_Exception + */ + public static function get($url, array $options = NULL) + { + if ($options === NULL) + { + // Use default options + $options = Remote::$default_options; + } + else + { + // Add default options + $options = $options + Remote::$default_options; + } + + // The transfer must always be returned + $options[CURLOPT_RETURNTRANSFER] = TRUE; + + // Open a new remote connection + $remote = curl_init($url); + + // Set connection options + if ( ! curl_setopt_array($remote, $options)) + { + throw new Kohana_Exception('Failed to set CURL options, check CURL documentation: :url', + array(':url' => 'http://php.net/curl_setopt_array')); + } + + // Get the response + $response = curl_exec($remote); + + // Get the response information + $code = curl_getinfo($remote, CURLINFO_HTTP_CODE); + + if ($code AND $code < 200 OR $code > 299) + { + $error = $response; + } + elseif ($response === FALSE) + { + $error = curl_error($remote); + } + + // Close the connection + curl_close($remote); + + if (isset($error)) + { + throw new Kohana_Exception('Error fetching remote :url [ status :code ] :error', + array(':url' => $url, ':code' => $code, ':error' => $error)); + } + + return $response; + } + + /** + * Returns the status code (200, 500, etc) for a URL. + * + * $status = Remote::status($url); + * + * @param string URL to check + * @return integer + */ + public static function status($url) + { + // Get the hostname and path + $url = parse_url($url); + + if (empty($url['path'])) + { + // Request the root document + $url['path'] = '/'; + } + + // Open a remote connection + $port = isset($url['port']) ? $url['port'] : 80; + $remote = fsockopen($url['host'], $port, $errno, $errstr, 5); + + if ( ! is_resource($remote)) + return FALSE; + + // Set CRLF + $line_feed = "\r\n"; + + // Send request + fwrite($remote, 'HEAD '.$url['path'].' HTTP/1.0'.$line_feed); + fwrite($remote, 'Host: '.$url['host'].$line_feed); + fwrite($remote, 'Connection: close'.$line_feed); + fwrite($remote, 'User-Agent: Kohana Framework (+http://kohanaframework.org/)'.$line_feed); + + // Send one more CRLF to terminate the headers + fwrite($remote, $line_feed); + + // Remote is offline + $response = FALSE; + + while ( ! feof($remote)) + { + // Get the line + $line = trim(fgets($remote, 512)); + + if ($line !== '' AND preg_match('#^HTTP/1\.[01] (\d{3})#', $line, $matches)) + { + // Response code found + $response = (int) $matches[1]; + break; + } + } + + // Close the connection + fclose($remote); + + return $response; + } + +} // End remote diff --git a/includes/kohana/system/classes/kohana/request.php b/includes/kohana/system/classes/kohana/request.php new file mode 100644 index 0000000..a295b34 --- /dev/null +++ b/includes/kohana/system/classes/kohana/request.php @@ -0,0 +1,1305 @@ + 'Continue', + 101 => 'Switching Protocols', + + // Success 2xx + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', + + // Redirection 3xx + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', // 1.1 + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + // 306 is deprecated but reserved + 307 => 'Temporary Redirect', + + // Client Error 4xx + 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', + 423 => 'Locked', + 424 => 'Failed Dependency', + + // Server Error 5xx + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 507 => 'Insufficient Storage', + 509 => 'Bandwidth Limit Exceeded' + ); + + /** + * @var string method: GET, POST, PUT, DELETE, etc + */ + public static $method = 'GET'; + + /** + * @var string protocol: http, https, ftp, cli, etc + */ + public static $protocol = 'http'; + + /** + * @var string referring URL + */ + public static $referrer; + + /** + * @var string client user agent + */ + public static $user_agent = ''; + + /** + * @var string client IP address + */ + public static $client_ip = '0.0.0.0'; + + /** + * @var boolean AJAX-generated request + */ + public static $is_ajax = FALSE; + + /** + * @var Request main request instance + */ + public static $instance; + + /** + * @var Request currently executing request instance + */ + public static $current; + + /** + * Main request singleton instance. If no URI is provided, the URI will + * be automatically detected. + * + * $request = Request::instance(); + * + * @param string URI of the request + * @return Request + * @uses Request::detect_uri + */ + public static function instance( & $uri = TRUE) + { + if ( ! Request::$instance) + { + if (Kohana::$is_cli) + { + // Default protocol for command line is cli:// + Request::$protocol = 'cli'; + + // Get the command line options + $options = CLI::options('uri', 'method', 'get', 'post'); + + if (isset($options['uri'])) + { + // Use the specified URI + $uri = $options['uri']; + } + + if (isset($options['method'])) + { + // Use the specified method + Request::$method = strtoupper($options['method']); + } + + if (isset($options['get'])) + { + // Overload the global GET data + parse_str($options['get'], $_GET); + } + + if (isset($options['post'])) + { + // Overload the global POST data + parse_str($options['post'], $_POST); + } + } + else + { + if (isset($_SERVER['REQUEST_METHOD'])) + { + // Use the server request method + Request::$method = $_SERVER['REQUEST_METHOD']; + } + + if ( ! empty($_SERVER['HTTPS']) AND filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) + { + // This request is secure + Request::$protocol = 'https'; + } + + if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') + { + // This request is an AJAX request + Request::$is_ajax = TRUE; + } + + if (isset($_SERVER['HTTP_REFERER'])) + { + // There is a referrer for this request + Request::$referrer = $_SERVER['HTTP_REFERER']; + } + + if (isset($_SERVER['HTTP_USER_AGENT'])) + { + // Set the client user agent + Request::$user_agent = $_SERVER['HTTP_USER_AGENT']; + } + + if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) + { + // Use the forwarded IP address, typically set when the + // client is using a proxy server. + Request::$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } + elseif (isset($_SERVER['HTTP_CLIENT_IP'])) + { + // Use the forwarded IP address, typically set when the + // client is using a proxy server. + Request::$client_ip = $_SERVER['HTTP_CLIENT_IP']; + } + elseif (isset($_SERVER['REMOTE_ADDR'])) + { + // The remote IP address + Request::$client_ip = $_SERVER['REMOTE_ADDR']; + } + + if (Request::$method !== 'GET' AND Request::$method !== 'POST') + { + // Methods besides GET and POST do not properly parse the form-encoded + // query string into the $_POST array, so we overload it manually. + parse_str(file_get_contents('php://input'), $_POST); + } + + if ($uri === TRUE) + { + $uri = Request::detect_uri(); + } + } + + // Reduce multiple slashes to a single slash + $uri = preg_replace('#//+#', '/', $uri); + + // Remove all dot-paths from the URI, they are not valid + $uri = preg_replace('#\.[\s./]*/#', '', $uri); + + // Create the instance singleton + Request::$instance = Request::$current = new Request($uri); + + // Add the default Content-Type header + Request::$instance->headers['Content-Type'] = 'text/html; charset='.Kohana::$charset; + } + + return Request::$instance; + } + + /** + * Automatically detects the URI of the main request using PATH_INFO, + * REQUEST_URI, PHP_SELF or REDIRECT_URL. + * + * $uri = Request::detect_uri(); + * + * @return string URI of the main request + * @throws Kohana_Exception + * @since 3.0.8 + */ + public static function detect_uri() + { + if ( ! empty($_SERVER['PATH_INFO'])) + { + // PATH_INFO does not contain the docroot or index + $uri = $_SERVER['PATH_INFO']; + } + else + { + // REQUEST_URI and PHP_SELF include the docroot and index + + if (isset($_SERVER['REQUEST_URI'])) + { + // REQUEST_URI includes the query string, remove it + $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); + + // Decode the request URI + $uri = rawurldecode($uri); + } + elseif (isset($_SERVER['PHP_SELF'])) + { + $uri = $_SERVER['PHP_SELF']; + } + elseif (isset($_SERVER['REDIRECT_URL'])) + { + $uri = $_SERVER['REDIRECT_URL']; + } + else + { + // If you ever see this error, please report an issue at http://dev.kohanaphp.com/projects/kohana3/issues + // along with any relevant information about your web server setup. Thanks! + throw new Kohana_Exception('Unable to detect the URI using PATH_INFO, REQUEST_URI, PHP_SELF or REDIRECT_URL'); + } + + // Get the path from the base URL, including the index file + $base_url = parse_url(Kohana::$base_url, PHP_URL_PATH); + + if (strpos($uri, $base_url) === 0) + { + // Remove the base URL from the URI + $uri = (string) substr($uri, strlen($base_url)); + } + + if (Kohana::$index_file AND strpos($uri, Kohana::$index_file) === 0) + { + // Remove the index file from the URI + $uri = (string) substr($uri, strlen(Kohana::$index_file)); + } + } + + return $uri; + } + + /** + * Return the currently executing request. This is changed to the current + * request when [Request::execute] is called and restored when the request + * is completed. + * + * $request = Request::current(); + * + * @return Request + * @since 3.0.5 + */ + public static function current() + { + return Request::$current; + } + + /** + * Creates a new request object for the given URI. This differs from + * [Request::instance] in that it does not automatically detect the URI + * and should only be used for creating HMVC requests. + * + * $request = Request::factory($uri); + * + * @param string URI of the request + * @return Request + */ + public static function factory($uri) + { + return new Request($uri); + } + + /** + * Returns information about the client user agent. + * + * // Returns "Chrome" when using Google Chrome + * $browser = Request::user_agent('browser'); + * + * Multiple values can be returned at once by using an array: + * + * // Get the browser and platform with a single call + * $info = Request::user_agent(array('browser', 'platform')); + * + * When using an array for the value, an associative array will be returned. + * + * @param mixed string to return: browser, version, robot, mobile, platform; or array of values + * @return mixed requested information, FALSE if nothing is found + * @uses Kohana::config + * @uses Request::$user_agent + */ + public static function user_agent($value) + { + if (is_array($value)) + { + $agent = array(); + foreach ($value as $v) + { + // Add each key to the set + $agent[$v] = Request::user_agent($v); + } + + return $agent; + } + + static $info; + + if (isset($info[$value])) + { + // This value has already been found + return $info[$value]; + } + + if ($value === 'browser' OR $value == 'version') + { + // Load browsers + $browsers = Kohana::config('user_agents')->browser; + + foreach ($browsers as $search => $name) + { + if (stripos(Request::$user_agent, $search) !== FALSE) + { + // Set the browser name + $info['browser'] = $name; + + if (preg_match('#'.preg_quote($search).'[^0-9.]*+([0-9.][0-9.a-z]*)#i', Request::$user_agent, $matches)) + { + // Set the version number + $info['version'] = $matches[1]; + } + else + { + // No version number found + $info['version'] = FALSE; + } + + return $info[$value]; + } + } + } + else + { + // Load the search group for this type + $group = Kohana::config('user_agents')->$value; + + foreach ($group as $search => $name) + { + if (stripos(Request::$user_agent, $search) !== FALSE) + { + // Set the value name + return $info[$value] = $name; + } + } + } + + // The value requested could not be found + return $info[$value] = FALSE; + } + + /** + * Returns the accepted content types. If a specific type is defined, + * the quality of that type will be returned. + * + * $types = Request::accept_type(); + * + * @param string content MIME type + * @return float when checking a specific type + * @return array + * @uses Request::_parse_accept + */ + public static function accept_type($type = NULL) + { + static $accepts; + + if ($accepts === NULL) + { + // Parse the HTTP_ACCEPT header + $accepts = Request::_parse_accept($_SERVER['HTTP_ACCEPT'], array('*/*' => 1.0)); + } + + if (isset($type)) + { + // Return the quality setting for this type + return isset($accepts[$type]) ? $accepts[$type] : $accepts['*/*']; + } + + return $accepts; + } + + /** + * Returns the accepted languages. If a specific language is defined, + * the quality of that language will be returned. If the language is not + * accepted, FALSE will be returned. + * + * $langs = Request::accept_lang(); + * + * @param string language code + * @return float when checking a specific language + * @return array + * @uses Request::_parse_accept + */ + public static function accept_lang($lang = NULL) + { + static $accepts; + + if ($accepts === NULL) + { + // Parse the HTTP_ACCEPT_LANGUAGE header + $accepts = Request::_parse_accept($_SERVER['HTTP_ACCEPT_LANGUAGE']); + } + + if (isset($lang)) + { + // Return the quality setting for this lang + return isset($accepts[$lang]) ? $accepts[$lang] : FALSE; + } + + return $accepts; + } + + /** + * Returns the accepted encodings. If a specific encoding is defined, + * the quality of that encoding will be returned. If the encoding is not + * accepted, FALSE will be returned. + * + * $encodings = Request::accept_encoding(); + * + * @param string encoding type + * @return float when checking a specific encoding + * @return array + * @uses Request::_parse_accept + */ + public static function accept_encoding($type = NULL) + { + static $accepts; + + if ($accepts === NULL) + { + // Parse the HTTP_ACCEPT_LANGUAGE header + $accepts = Request::_parse_accept($_SERVER['HTTP_ACCEPT_ENCODING']); + } + + if (isset($type)) + { + // Return the quality setting for this type + return isset($accepts[$type]) ? $accepts[$type] : FALSE; + } + + return $accepts; + } + + /** + * Parses an accept header and returns an array (type => quality) of the + * accepted types, ordered by quality. + * + * $accept = Request::_parse_accept($header, $defaults); + * + * @param string header to parse + * @param array default values + * @return array + */ + protected static function _parse_accept( & $header, array $accepts = NULL) + { + if ( ! empty($header)) + { + // Get all of the types + $types = explode(',', $header); + + foreach ($types as $type) + { + // Split the type into parts + $parts = explode(';', $type); + + // Make the type only the MIME + $type = trim(array_shift($parts)); + + // Default quality is 1.0 + $quality = 1.0; + + foreach ($parts as $part) + { + // Prevent undefined $value notice below + if (strpos($part, '=') === FALSE) + continue; + + // Separate the key and value + list ($key, $value) = explode('=', trim($part)); + + if ($key === 'q') + { + // There is a quality for this type + $quality = (float) trim($value); + } + } + + // Add the accept type and quality + $accepts[$type] = $quality; + } + } + + // Make sure that accepts is an array + $accepts = (array) $accepts; + + // Order by quality + arsort($accepts); + + return $accepts; + } + + /** + * @var object route matched for this request + */ + public $route; + + /** + * @var integer HTTP response code: 200, 404, 500, etc + */ + public $status = 200; + + /** + * @var string response body + */ + public $response = ''; + + /** + * @var array headers to send with the response body + */ + public $headers = array(); + + /** + * @var string controller directory + */ + public $directory = ''; + + /** + * @var string controller to be executed + */ + public $controller; + + /** + * @var string action to be executed in the controller + */ + public $action; + + /** + * @var string the URI of the request + */ + public $uri; + + // Parameters extracted from the route + protected $_params; + + /** + * Creates a new request object for the given URI. New requests should be + * created using the [Request::instance] or [Request::factory] methods. + * + * $request = new Request($uri); + * + * @param string URI of the request + * @return void + * @throws Kohana_Request_Exception + * @uses Route::all + * @uses Route::matches + */ + public function __construct($uri) + { + // Remove trailing slashes from the URI + $uri = trim($uri, '/'); + + // Load routes + $routes = Route::all(); + + foreach ($routes as $name => $route) + { + if ($params = $route->matches($uri)) + { + // Store the URI + $this->uri = $uri; + + // Store the matching route + $this->route = $route; + + if (isset($params['directory'])) + { + // Controllers are in a sub-directory + $this->directory = $params['directory']; + } + + // Store the controller + $this->controller = $params['controller']; + + if (isset($params['action'])) + { + // Store the action + $this->action = $params['action']; + } + else + { + // Use the default action + $this->action = Route::$default_action; + } + + // These are accessible as public vars and can be overloaded + unset($params['controller'], $params['action'], $params['directory']); + + // Params cannot be changed once matched + $this->_params = $params; + + return; + } + } + + // No matching route for this URI + $this->status = 404; + + throw new Kohana_Request_Exception('Unable to find a route to match the URI: :uri', + array(':uri' => $uri)); + } + + /** + * Returns the response as the string representation of a request. + * + * echo $request; + * + * @return string + */ + public function __toString() + { + return (string) $this->response; + } + + /** + * Generates a relative URI for the current route. + * + * $request->uri($params); + * + * @param array additional route parameters + * @return string + * @uses Route::uri + */ + public function uri(array $params = NULL) + { + if ( ! isset($params['directory'])) + { + // Add the current directory + $params['directory'] = $this->directory; + } + + if ( ! isset($params['controller'])) + { + // Add the current controller + $params['controller'] = $this->controller; + } + + if ( ! isset($params['action'])) + { + // Add the current action + $params['action'] = $this->action; + } + + // Add the current parameters + $params += $this->_params; + + return $this->route->uri($params); + } + + /** + * Create a URL from the current request. This is a shortcut for: + * + * echo URL::site($this->request->uri($params), $protocol); + * + * @param string route name + * @param array URI parameters + * @param mixed protocol string or boolean, adds protocol and domain + * @return string + * @since 3.0.7 + * @uses URL::site + */ + public function url(array $params = NULL, $protocol = NULL) + { + // Create a URI with the current route and convert it to a URL + return URL::site($this->uri($params), $protocol); + } + + /** + * Retrieves a value from the route parameters. + * + * $id = $request->param('id'); + * + * @param string key of the value + * @param mixed default value if the key is not set + * @return mixed + */ + public function param($key = NULL, $default = NULL) + { + if ($key === NULL) + { + // Return the full array + return $this->_params; + } + + return isset($this->_params[$key]) ? $this->_params[$key] : $default; + } + + /** + * Sends the response status and all set headers. The current server + * protocol (HTTP/1.0 or HTTP/1.1) will be used when available. If not + * available, HTTP/1.1 will be used. + * + * $request->send_headers(); + * + * @return $this + * @uses Request::$messages + */ + public function send_headers() + { + if ( ! headers_sent()) + { + if (isset($_SERVER['SERVER_PROTOCOL'])) + { + // Use the default server protocol + $protocol = $_SERVER['SERVER_PROTOCOL']; + } + else + { + // Default to using newer protocol + $protocol = 'HTTP/1.1'; + } + + // HTTP status line + header($protocol.' '.$this->status.' '.Request::$messages[$this->status]); + + foreach ($this->headers as $name => $value) + { + if (is_string($name)) + { + // Combine the name and value to make a raw header + $value = "{$name}: {$value}"; + } + + // Send the raw header + header($value, TRUE); + } + } + + return $this; + } + + /** + * Redirects as the request response. If the URL does not include a + * protocol, it will be converted into a complete URL. + * + * $request->redirect($url); + * + * [!!] No further processing can be done after this method is called! + * + * @param string redirect location + * @param integer status code: 301, 302, etc + * @return void + * @uses URL::site + * @uses Request::send_headers + */ + public function redirect($url = '', $code = 302) + { + if (strpos($url, '://') === FALSE) + { + // Make the URI into a URL + $url = URL::site($url, TRUE); + } + + // Set the response status + $this->status = $code; + + // Set the location header + $this->headers['Location'] = $url; + + // Send headers + $this->send_headers(); + + // Stop execution + exit; + } + + /** + * Send file download as the response. All execution will be halted when + * this method is called! Use TRUE for the filename to send the current + * response as the file content. The third parameter allows the following + * options to be set: + * + * Type | Option | Description | Default Value + * ----------|-----------|------------------------------------|-------------- + * `boolean` | inline | Display inline instead of download | `FALSE` + * `string` | mime_type | Manual mime type | Automatic + * `boolean` | delete | Delete the file after sending | `FALSE` + * + * Download a file that already exists: + * + * $request->send_file('media/packages/kohana.zip'); + * + * Download generated content as a file: + * + * $request->response = $content; + * $request->send_file(TRUE, $filename); + * + * [!!] No further processing can be done after this method is called! + * + * @param string filename with path, or TRUE for the current response + * @param string downloaded file name + * @param array additional options + * @return void + * @throws Kohana_Exception + * @uses File::mime_by_ext + * @uses File::mime + * @uses Request::send_headers + */ + public function send_file($filename, $download = NULL, array $options = NULL) + { + if ( ! empty($options['mime_type'])) + { + // The mime-type has been manually set + $mime = $options['mime_type']; + } + + if ($filename === TRUE) + { + if (empty($download)) + { + throw new Kohana_Exception('Download name must be provided for streaming files'); + } + + // Temporary files will automatically be deleted + $options['delete'] = FALSE; + + if ( ! isset($mime)) + { + // Guess the mime using the file extension + $mime = File::mime_by_ext(strtolower(pathinfo($download, PATHINFO_EXTENSION))); + } + + // Force the data to be rendered if + $file_data = (string) $this->response; + + // Get the content size + $size = strlen($file_data); + + // Create a temporary file to hold the current response + $file = tmpfile(); + + // Write the current response into the file + fwrite($file, $file_data); + + // File data is no longer needed + unset($file_data); + } + else + { + // Get the complete file path + $filename = realpath($filename); + + if (empty($download)) + { + // Use the file name as the download file name + $download = pathinfo($filename, PATHINFO_BASENAME); + } + + // Get the file size + $size = filesize($filename); + + if ( ! isset($mime)) + { + // Get the mime type + $mime = File::mime($filename); + } + + // Open the file for reading + $file = fopen($filename, 'rb'); + } + + if ( ! is_resource($file)) + { + throw new Kohana_Exception('Could not read file to send: :file', array( + ':file' => $download, + )); + } + + // Inline or download? + $disposition = empty($options['inline']) ? 'attachment' : 'inline'; + + // Calculate byte range to download. + list($start, $end) = $this->_calculate_byte_range($size); + + if ( ! empty($options['resumable'])) + { + if ($start > 0 OR $end < ($size - 1)) + { + // Partial Content + $this->status = 206; + } + + // Range of bytes being sent + $this->headers['Content-Range'] = 'bytes '.$start.'-'.$end.'/'.$size; + $this->headers['Accept-Ranges'] = 'bytes'; + } + + // Set the headers for a download + $this->headers['Content-Disposition'] = $disposition.'; filename="'.$download.'"'; + $this->headers['Content-Type'] = $mime; + $this->headers['Content-Length'] = ($end - $start) + 1; + + if (Request::user_agent('browser') === 'Internet Explorer') + { + // Naturally, IE does not act like a real browser... + if (Request::$protocol === 'https') + { + // http://support.microsoft.com/kb/316431 + $this->headers['Pragma'] = $this->headers['Cache-Control'] = 'public'; + } + + if (version_compare(Request::user_agent('version'), '8.0', '>=')) + { + // http://ajaxian.com/archives/ie-8-security + $this->headers['X-Content-Type-Options'] = 'nosniff'; + } + } + + // Send all headers now + $this->send_headers(); + + while (ob_get_level()) + { + // Flush all output buffers + ob_end_flush(); + } + + // Manually stop execution + ignore_user_abort(TRUE); + + if ( ! Kohana::$safe_mode) + { + // Keep the script running forever + set_time_limit(0); + } + + // Send data in 16kb blocks + $block = 1024 * 16; + + fseek($file, $start); + + while ( ! feof($file) AND ($pos = ftell($file)) <= $end) + { + if (connection_aborted()) + break; + + if ($pos + $block > $end) + { + // Don't read past the buffer. + $block = $end - $pos + 1; + } + + // Output a block of the file + echo fread($file, $block); + + // Send the data now + flush(); + } + + // Close the file + fclose($file); + + if ( ! empty($options['delete'])) + { + try + { + // Attempt to remove the file + unlink($filename); + } + catch (Exception $e) + { + // Create a text version of the exception + $error = Kohana::exception_text($e); + + if (is_object(Kohana::$log)) + { + // Add this exception to the log + Kohana::$log->add(Kohana::ERROR, $error); + + // Make sure the logs are written + Kohana::$log->write(); + } + + // Do NOT display the exception, it will corrupt the output! + } + } + + // Stop execution + exit; + } + + /** + * Parse the byte ranges from the HTTP_RANGE header used for + * resumable downloads. + * + * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 + * @return array|FALSE + */ + protected function _parse_byte_range() + { + if ( ! isset($_SERVER['HTTP_RANGE'])) + { + return FALSE; + } + + // TODO, speed this up with the use of string functions. + preg_match_all('/(-?[0-9]++(?:-(?![0-9]++))?)(?:-?([0-9]++))?/', $_SERVER['HTTP_RANGE'], $matches, PREG_SET_ORDER); + + return $matches[0]; + } + + /** + * Calculates the byte range to use with send_file. If HTTP_RANGE doesn't + * exist then the complete byte range is returned + * + * @param integer $size + * @return array + */ + protected function _calculate_byte_range($size) + { + // Defaults to start with when the HTTP_RANGE header doesn't exist. + $start = 0; + $end = $size - 1; + + if ($range = $this->_parse_byte_range()) + { + // We have a byte range from HTTP_RANGE + $start = $range[1]; + + if ($start[0] === '-') + { + // A negative value means we start from the end, so -500 would be the + // last 500 bytes. + $start = $size - abs($start); + } + + if (isset($range[2])) + { + // Set the end range + $end = $range[2]; + } + } + + // Normalize values. + $start = abs(intval($start)); + + // Keep the the end value in bounds and normalize it. + $end = min(abs(intval($end)), $size - 1); + + // Keep the start in bounds. + $start = ($end < $start) ? 0 : max($start, 0); + + return array($start, $end); + } + + /** + * Processes the request, executing the controller action that handles this + * request, determined by the [Route]. + * + * 1. Before the controller action is called, the [Controller::before] method + * will be called. + * 2. Next the controller action will be called. + * 3. After the controller action is called, the [Controller::after] method + * will be called. + * + * By default, the output from the controller is captured and returned, and + * no headers are sent. + * + * $request->execute(); + * + * @return $this + * @throws Kohana_Exception + * @uses [Kohana::$profiling] + * @uses [Profiler] + */ + public function execute() + { + // Create the class prefix + $prefix = 'controller_'; + + if ($this->directory) + { + // Add the directory name to the class prefix + $prefix .= str_replace(array('\\', '/'), '_', trim($this->directory, '/')).'_'; + } + + if (Kohana::$profiling) + { + // Set the benchmark name + $benchmark = '"'.$this->uri.'"'; + + if ($this !== Request::$instance AND Request::$current) + { + // Add the parent request uri + $benchmark .= ' « "'.Request::$current->uri.'"'; + } + + // Start benchmarking + $benchmark = Profiler::start('Requests', $benchmark); + } + + // Store the currently active request + $previous = Request::$current; + + // Change the current request to this request + Request::$current = $this; + + try + { + // Load the controller using reflection + $class = new ReflectionClass($prefix.$this->controller); + + if ($class->isAbstract()) + { + throw new Kohana_Exception('Cannot create instances of abstract :controller', + array(':controller' => $prefix.$this->controller)); + } + + // Create a new instance of the controller + $controller = $class->newInstance($this); + + // Execute the "before action" method + $class->getMethod('before')->invoke($controller); + + // Determine the action to use + $action = empty($this->action) ? Route::$default_action : $this->action; + + // Execute the main action with the parameters + $class->getMethod('action_'.$action)->invokeArgs($controller, $this->_params); + + // Execute the "after action" method + $class->getMethod('after')->invoke($controller); + } + catch (Exception $e) + { + // Restore the previous request + Request::$current = $previous; + + if (isset($benchmark)) + { + // Delete the benchmark, it is invalid + Profiler::delete($benchmark); + } + + if ($e instanceof ReflectionException) + { + // Reflection will throw exceptions for missing classes or actions + $this->status = 404; + } + else + { + // All other exceptions are PHP/server errors + $this->status = 500; + } + + // Re-throw the exception + throw $e; + } + + // Restore the previous request + Request::$current = $previous; + + if (isset($benchmark)) + { + // Stop the benchmark + Profiler::stop($benchmark); + } + + return $this; + } + + + /** + * Generates an [ETag](http://en.wikipedia.org/wiki/HTTP_ETag) from the + * request response. + * + * $etag = $request->generate_etag(); + * + * [!!] If the request response is empty when this method is called, an + * exception will be thrown! + * + * @return string + * @throws Kohana_Request_Exception + */ + public function generate_etag() + { + if ($this->response === NULL) + { + throw new Kohana_Request_Exception('No response yet associated with request - cannot auto generate resource ETag'); + } + + // Generate a unique hash for the response + return '"'.sha1($this->response).'"'; + } + + + /** + * Checks the browser cache to see the response needs to be returned. + * + * $request->check_cache($etag); + * + * [!!] If the cache check succeeds, no further processing can be done! + * + * @param string etag to check + * @return $this + * @throws Kohana_Request_Exception + * @uses Request::generate_etag + */ + public function check_cache($etag = null) + { + if (empty($etag)) + { + $etag = $this->generate_etag(); + } + + // Set the ETag header + $this->headers['ETag'] = $etag; + + // Add the Cache-Control header if it is not already set + // This allows etags to be used with Max-Age, etc + $this->headers += array( + 'Cache-Control' => 'must-revalidate', + ); + + if (isset($_SERVER['HTTP_IF_NONE_MATCH']) AND $_SERVER['HTTP_IF_NONE_MATCH'] === $etag) + { + // No need to send data again + $this->status = 304; + $this->send_headers(); + + // Stop execution + exit; + } + + return $this; + } + +} // End Request diff --git a/includes/kohana/system/classes/kohana/request/exception.php b/includes/kohana/system/classes/kohana/request/exception.php new file mode 100644 index 0000000..1e8e149 --- /dev/null +++ b/includes/kohana/system/classes/kohana/request/exception.php @@ -0,0 +1,9 @@ + will be translated to a regular expression using a default + * regular expression pattern. You can override the default pattern by providing + * a pattern for the key: + * + * // This route will only match when is a digit + * Route::set('user', 'user//', array('id' => '\d+')); + * + * // This route will match when is anything + * Route::set('file', '', array('path' => '.*')); + * + * It is also possible to create optional segments by using parentheses in + * the URI definition: + * + * // This is the standard default route, and no keys are required + * Route::set('default', '((/(/)))'); + * + * // This route only requires the key + * Route::set('file', '(/)(.)', array('path' => '.*', 'format' => '\w+')); + * + * Routes also provide a way to generate URIs (called "reverse routing"), which + * makes them an extremely powerful and flexible way to generate internal links. + * + * @package Kohana + * @category Base + * @author Kohana Team + * @copyright (c) 2008-2010 Kohana Team + * @license http://kohanaframework.org/license + */ +class Kohana_Route { + + // Defines the pattern of a + const REGEX_KEY = '<([a-zA-Z0-9_]++)>'; + + // What can be part of a value + const REGEX_SEGMENT = '[^/.,;?\n]++'; + + // What must be escaped in the route regex + const REGEX_ESCAPE = '[.\\+*?[^\\]${}=!|]'; + + /** + * @var string default action for all routes + */ + public static $default_action = 'index'; + + /** + * @var array list of route objects + */ + protected static $_routes = array(); + + /** + * Stores a named route and returns it. The "action" will always be set to + * "index" if it is not defined. + * + * Route::set('default', '((/(/)))') + * ->defaults(array( + * 'controller' => 'welcome', + * )); + * + * @param string route name + * @param string URI pattern + * @param array regex patterns for route keys + * @return Route + */ + public static function set($name, $uri, array $regex = NULL) + { + return Route::$_routes[$name] = new Route($uri, $regex); + } + + /** + * Retrieves a named route. + * + * $route = Route::get('default'); + * + * @param string route name + * @return Route + * @throws Kohana_Exception + */ + public static function get($name) + { + if ( ! isset(Route::$_routes[$name])) + { + throw new Kohana_Exception('The requested route does not exist: :route', + array(':route' => $name)); + } + + return Route::$_routes[$name]; + } + + /** + * Retrieves all named routes. + * + * $routes = Route::all(); + * + * @return array routes by name + */ + public static function all() + { + return Route::$_routes; + } + + /** + * Get the name of a route. + * + * $name = Route::name($route) + * + * @param object Route instance + * @return string + */ + public static function name(Route $route) + { + return array_search($route, Route::$_routes); + } + + /** + * Saves or loads the route cache. If your routes will remain the same for + * a long period of time, use this to reload the routes from the cache + * rather than redefining them on every page load. + * + * if ( ! Route::cache()) + * { + * // Set routes here + * Route::cache(TRUE); + * } + * + * @param boolean cache the current routes + * @return void when saving routes + * @return boolean when loading routes + * @uses Kohana::cache + */ + public static function cache($save = FALSE) + { + if ($save === TRUE) + { + // Cache all defined routes + Kohana::cache('Route::cache()', Route::$_routes); + } + else + { + if ($routes = Kohana::cache('Route::cache()')) + { + Route::$_routes = $routes; + + // Routes were cached + return TRUE; + } + else + { + // Routes were not cached + return FALSE; + } + } + } + + /** + * Create a URL from a route name. This is a shortcut for: + * + * echo URL::site(Route::get($name)->uri($params), $protocol); + * + * @param string route name + * @param array URI parameters + * @param mixed protocol string or boolean, adds protocol and domain + * @return string + * @since 3.0.7 + * @uses URL::site + */ + public static function url($name, array $params = NULL, $protocol = NULL) + { + // Create a URI with the route and convert it to a URL + return URL::site(Route::get($name)->uri($params), $protocol); + } + + // Route URI string + protected $_uri = ''; + + // Regular expressions for route keys + protected $_regex = array(); + + // Default values for route keys + protected $_defaults = array('action' => 'index'); + + // Compiled regex cache + protected $_route_regex; + + /** + * Creates a new route. Sets the URI and regular expressions for keys. + * Routes should always be created with [Route::set] or they will not + * be properly stored. + * + * $route = new Route($uri, $regex); + * + * @param string route URI pattern + * @param array key patterns + * @return void + * @uses Route::_compile + */ + public function __construct($uri = NULL, array $regex = NULL) + { + if ($uri === NULL) + { + // Assume the route is from cache + return; + } + + if ( ! empty($regex)) + { + $this->_regex = $regex; + } + + // Store the URI that this route will match + $this->_uri = $uri; + + // Store the compiled regex locally + $this->_route_regex = $this->_compile(); + } + + /** + * Provides default values for keys when they are not present. The default + * action will always be "index" unless it is overloaded here. + * + * $route->defaults(array( + * 'controller' => 'welcome', + * 'action' => 'index' + * )); + * + * @param array key values + * @return $this + */ + public function defaults(array $defaults = NULL) + { + $this->_defaults = $defaults; + + return $this; + } + + /** + * Tests if the route matches a given URI. A successful match will return + * all of the routed parameters as an array. A failed match will return + * boolean FALSE. + * + * // Params: controller = users, action = edit, id = 10 + * $params = $route->matches('users/edit/10'); + * + * This method should almost always be used within an if/else block: + * + * if ($params = $route->matches($uri)) + * { + * // Parse the parameters + * } + * + * @param string URI to match + * @return array on success + * @return FALSE on failure + */ + public function matches($uri) + { + if ( ! preg_match($this->_route_regex, $uri, $matches)) + return FALSE; + + $params = array(); + foreach ($matches as $key => $value) + { + if (is_int($key)) + { + // Skip all unnamed keys + continue; + } + + // Set the value for all matched keys + $params[$key] = $value; + } + + foreach ($this->_defaults as $key => $value) + { + if ( ! isset($params[$key]) OR $params[$key] === '') + { + // Set default values for any key that was not matched + $params[$key] = $value; + } + } + + return $params; + } + + /** + * Generates a URI for the current route based on the parameters given. + * + * // Using the "default" route: "users/profile/10" + * $route->uri(array( + * 'controller' => 'users', + * 'action' => 'profile', + * 'id' => '10' + * )); + * + * @param array URI parameters + * @return string + * @throws Kohana_Exception + * @uses Route::REGEX_Key + */ + public function uri(array $params = NULL) + { + if ($params === NULL) + { + // Use the default parameters + $params = $this->_defaults; + } + else + { + // Add the default parameters + $params += $this->_defaults; + } + + // Start with the routed URI + $uri = $this->_uri; + + if (strpos($uri, '<') === FALSE AND strpos($uri, '(') === FALSE) + { + // This is a static route, no need to replace anything + return $uri; + } + + while (preg_match('#\([^()]++\)#', $uri, $match)) + { + // Search for the matched value + $search = $match[0]; + + // Remove the parenthesis from the match as the replace + $replace = substr($match[0], 1, -1); + + while (preg_match('#'.Route::REGEX_KEY.'#', $replace, $match)) + { + list($key, $param) = $match; + + if (isset($params[$param])) + { + // Replace the key with the parameter value + $replace = str_replace($key, $params[$param], $replace); + } + else + { + // This group has missing parameters + $replace = ''; + break; + } + } + + // Replace the group in the URI + $uri = str_replace($search, $replace, $uri); + } + + while (preg_match('#'.Route::REGEX_KEY.'#', $uri, $match)) + { + list($key, $param) = $match; + + if ( ! isset($params[$param])) + { + // Ungrouped parameters are required + throw new Kohana_Exception('Required route parameter not passed: :param', + array(':param' => $param)); + } + + $uri = str_replace($key, $params[$param], $uri); + } + + // Trim all extra slashes from the URI + $uri = preg_replace('#//+#', '/', rtrim($uri, '/')); + + return $uri; + } + + /** + * Returns the compiled regular expression for the route. This translates + * keys and optional groups to a proper PCRE regular expression. + * + * $regex = $route->_compile(); + * + * @return string + * @uses Route::REGEX_ESCAPE + * @uses Route::REGEX_SEGMENT + */ + protected function _compile() + { + // The URI should be considered literal except for keys and optional parts + // Escape everything preg_quote would escape except for : ( ) < > + $regex = preg_replace('#'.Route::REGEX_ESCAPE.'#', '\\\\$0', $this->_uri); + + if (strpos($regex, '(') !== FALSE) + { + // Make optional parts of the URI non-capturing and optional + $regex = str_replace(array('(', ')'), array('(?:', ')?'), $regex); + } + + // Insert default regex for keys + $regex = str_replace(array('<', '>'), array('(?P<', '>'.Route::REGEX_SEGMENT.')'), $regex); + + if ( ! empty($this->_regex)) + { + $search = $replace = array(); + foreach ($this->_regex as $key => $value) + { + $search[] = "<$key>".Route::REGEX_SEGMENT; + $replace[] = "<$key>$value"; + } + + // Replace the default regex with the user-specified regex + $regex = str_replace($search, $replace, $regex); + } + + return '#^'.$regex.'$#uD'; + } + +} // End Route diff --git a/includes/kohana/system/classes/kohana/security.php b/includes/kohana/system/classes/kohana/security.php new file mode 100644 index 0000000..020bb68 --- /dev/null +++ b/includes/kohana/system/classes/kohana/security.php @@ -0,0 +1,193 @@ + + * @copyright (c) 2001-2006 Bitflux GmbH + * @param mixed string or array to sanitize + * @return string + * @deprecated since v3.0.5 + */ + public static function xss_clean($str) + { + // http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.php + // +----------------------------------------------------------------------+ + // | Copyright (c) 2001-2006 Bitflux GmbH | + // +----------------------------------------------------------------------+ + // | Licensed under the Apache License, Version 2.0 (the "License"); | + // | you may not use this file except in compliance with the License. | + // | You may obtain a copy of the License at | + // | http://www.apache.org/licenses/LICENSE-2.0 | + // | Unless required by applicable law or agreed to in writing, software | + // | distributed under the License is distributed on an "AS IS" BASIS, | + // | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | + // | implied. See the License for the specific language governing | + // | permissions and limitations under the License. | + // +----------------------------------------------------------------------+ + // | Author: Christian Stocker | + // +----------------------------------------------------------------------+ + // + // Kohana Modifications: + // * Changed double quotes to single quotes, changed indenting and spacing + // * Removed magic_quotes stuff + // * Increased regex readability: + // * Used delimeters that aren't found in the pattern + // * Removed all unneeded escapes + // * Deleted U modifiers and swapped greediness where needed + // * Increased regex speed: + // * Made capturing parentheses non-capturing where possible + // * Removed parentheses where possible + // * Split up alternation alternatives + // * Made some quantifiers possessive + // * Handle arrays recursively + + if (is_array($str) OR is_object($str)) + { + foreach ($str as $k => $s) + { + $str[$k] = Security::xss_clean($s); + } + + return $str; + } + + // Remove all NULL bytes + $str = str_replace("\0", '', $str); + + // Fix &entity\n; + $str = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $str); + $str = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $str); + $str = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $str); + $str = html_entity_decode($str, ENT_COMPAT, Kohana::$charset); + + // Remove any attribute starting with "on" or xmlns + $str = preg_replace('#(?:on[a-z]+|xmlns)\s*=\s*[\'"\x00-\x20]?[^\'>"]*[\'"\x00-\x20]?\s?#iu', '', $str); + + // Remove javascript: and vbscript: protocols + $str = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $str); + $str = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $str); + $str = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $str); + + // Only works in IE: + $str = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#is', '$1>', $str); + $str = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#is', '$1>', $str); + $str = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#ius', '$1>', $str); + + // Remove namespaced elements (we do not need them) + $str = preg_replace('#]*+>#i', '', $str); + + do + { + // Remove really unwanted tags + $old = $str; + $str = preg_replace('#]*+>#i', '', $str); + } + while ($old !== $str); + + return $str; + } + + /** + * Generate and store a unique token which can be used to help prevent + * [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks. + * + * $token = Security::token(); + * + * You can insert this token into your forms as a hidden field: + * + * echo Form::hidden('csrf', Security::token()); + * + * And then check it when using [Validate]: + * + * $array->rules('csrf', array( + * 'not_empty' => NULL, + * 'Security::check' => NULL, + * )); + * + * This provides a basic, but effective, method of preventing CSRF attacks. + * + * @param boolean force a new token to be generated? + * @return string + * @uses Session::instance + */ + public static function token($new = FALSE) + { + $session = Session::instance(); + + // Get the current token + $token = $session->get(Security::$token_name); + + if ($new === TRUE OR ! $token) + { + // Generate a new unique token + $token = uniqid('security'); + + // Store the new token + $session->set(Security::$token_name, $token); + } + + return $token; + } + + /** + * Check that the given token matches the currently stored security token. + * + * if (Security::check($token)) + * { + * // Pass + * } + * + * @param string token to check + * @return boolean + * @uses Security::token + */ + public static function check($token) + { + return Security::token() === $token; + } + + /** + * Remove image tags from a string. + * + * $str = Security::strip_image_tags($str); + * + * @param string string to sanitize + * @return string + */ + public static function strip_image_tags($str) + { + return preg_replace('#\s]*)["\']?[^>]*)?>#is', '$1', $str); + } + + /** + * Encodes PHP tags in a string. + * + * $str = Security::encode_php_tags($str); + * + * @param string string to sanitize + * @return string + */ + public static function encode_php_tags($str) + { + return str_replace(array(''), array('<?', '?>'), $str); + } + +} // End security diff --git a/includes/kohana/system/classes/kohana/session.php b/includes/kohana/system/classes/kohana/session.php new file mode 100644 index 0000000..3977916 --- /dev/null +++ b/includes/kohana/system/classes/kohana/session.php @@ -0,0 +1,427 @@ +get($type); + + // Set the session class name + $class = 'Session_'.ucfirst($type); + + // Create a new session instance + Session::$instances[$type] = $session = new $class($config, $id); + + // Write the session at shutdown + register_shutdown_function(array($session, 'write')); + } + + return Session::$instances[$type]; + } + + /** + * @var string cookie name + */ + protected $_name = 'session'; + + /** + * @var int cookie lifetime + */ + protected $_lifetime = 0; + + /** + * @var bool encrypt session data? + */ + protected $_encrypted = FALSE; + + /** + * @var array session data + */ + protected $_data = array(); + + /** + * @var bool session destroyed? + */ + protected $_destroyed = FALSE; + + /** + * Overloads the name, lifetime, and encrypted session settings. + * + * [!!] Sessions can only be created using the [Session::instance] method. + * + * @param array configuration + * @param string session id + * @return void + * @uses Session::read + */ + public function __construct(array $config = NULL, $id = NULL) + { + if (isset($config['name'])) + { + // Cookie name to store the session id in + $this->_name = (string) $config['name']; + } + + if (isset($config['lifetime'])) + { + // Cookie lifetime + $this->_lifetime = (int) $config['lifetime']; + } + + if (isset($config['encrypted'])) + { + if ($config['encrypted'] === TRUE) + { + // Use the default Encrypt instance + $config['encrypted'] = 'default'; + } + + // Enable or disable encryption of data + $this->_encrypted = $config['encrypted']; + } + + // Load the session + $this->read($id); + } + + /** + * Session object is rendered to a serialized string. If encryption is + * enabled, the session will be encrypted. If not, the output string will + * be encoded using [base64_encode]. + * + * echo $session; + * + * @return string + * @uses Encrypt::encode + */ + public function __toString() + { + // Serialize the data array + $data = serialize($this->_data); + + if ($this->_encrypted) + { + // Encrypt the data using the default key + $data = Encrypt::instance($this->_encrypted)->encode($data); + } + else + { + // Obfuscate the data with base64 encoding + $data = base64_encode($data); + } + + return $data; + } + + /** + * Returns the current session array. The returned array can also be + * assigned by reference. + * + * // Get a copy of the current session data + * $data = $session->as_array(); + * + * // Assign by reference for modification + * $data =& $session->as_array(); + * + * @return array + */ + public function & as_array() + { + return $this->_data; + } + + /** + * Get the current session id, if the session supports it. + * + * $id = $session->id(); + * + * [!!] Not all session types have ids. + * + * @return string + * @since 3.0.8 + */ + public function id() + { + return NULL; + } + + /** + * Get the current session cookie name. + * + * $name = $session->name(); + * + * @return string + * @since 3.0.8 + */ + public function name() + { + return $this->_name; + } + + /** + * Get a variable from the session array. + * + * $foo = $session->get('foo'); + * + * @param string variable name + * @param mixed default value to return + * @return mixed + */ + public function get($key, $default = NULL) + { + return array_key_exists($key, $this->_data) ? $this->_data[$key] : $default; + } + + /** + * Get and delete a variable from the session array. + * + * $bar = $session->get_once('bar'); + * + * @param string variable name + * @param mixed default value to return + * @return mixed + */ + public function get_once($key, $default = NULL) + { + $value = $this->get($key, $default); + + unset($this->_data[$key]); + + return $value; + } + + /** + * Set a variable in the session array. + * + * $session->set('foo', 'bar'); + * + * @param string variable name + * @param mixed value + * @return $this + */ + public function set($key, $value) + { + $this->_data[$key] = $value; + + return $this; + } + + /** + * Set a variable by reference. + * + * $session->bind('foo', $foo); + * + * @param string variable name + * @param mixed referenced value + * @return $this + */ + public function bind($key, & $value) + { + $this->_data[$key] =& $value; + + return $this; + } + + /** + * Removes a variable in the session array. + * + * $session->delete('foo'); + * + * @param string variable name + * @param ... + * @return $this + */ + public function delete($key) + { + $args = func_get_args(); + + foreach ($args as $key) + { + unset($this->_data[$key]); + } + + return $this; + } + + /** + * Loads existing session data. + * + * $session->read(); + * + * @param string session id + * @return void + */ + public function read($id = NULL) + { + if (is_string($data = $this->_read($id))) + { + try + { + if ($this->_encrypted) + { + // Decrypt the data using the default key + $data = Encrypt::instance($this->_encrypted)->decode($data); + } + else + { + // Decode the base64 encoded data + $data = base64_decode($data); + } + + // Unserialize the data + $data = unserialize($data); + } + catch (Exception $e) + { + // Ignore all reading errors + } + } + + if (is_array($data)) + { + // Load the data locally + $this->_data = $data; + } + } + + /** + * Generates a new session id and returns it. + * + * $id = $session->regenerate(); + * + * @return string + */ + public function regenerate() + { + return $this->_regenerate(); + } + + /** + * Sets the last_active timestamp and saves the session. + * + * $session->write(); + * + * [!!] Any errors that occur during session writing will be logged, + * but not displayed, because sessions are written after output has + * been sent. + * + * @return boolean + * @uses Kohana::$log + */ + public function write() + { + if (headers_sent() OR $this->_destroyed) + { + // Session cannot be written when the headers are sent or when + // the session has been destroyed + return FALSE; + } + + // Set the last active timestamp + $this->_data['last_active'] = time(); + + try + { + return $this->_write(); + } + catch (Exception $e) + { + // Log & ignore all errors when a write fails + Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e))->write(); + + return FALSE; + } + } + + /** + * Completely destroy the current session. + * + * $success = $session->destroy(); + * + * @return boolean + */ + public function destroy() + { + if ($this->_destroyed === FALSE) + { + if ($this->_destroyed = $this->_destroy()) + { + // The session has been destroyed, clear all data + $this->_data = array(); + } + } + + return $this->_destroyed; + } + + /** + * Loads the raw session data string and returns it. + * + * @param string session id + * @return string + */ + abstract protected function _read($id = NULL); + + /** + * Generate a new session id and return it. + * + * @return string + */ + abstract protected function _regenerate(); + + /** + * Writes the current session. + * + * @return boolean + */ + abstract protected function _write(); + + /** + * Destroys the current session. + * + * @return boolean + */ + abstract protected function _destroy(); + +} // End Session diff --git a/includes/kohana/system/classes/kohana/session/cookie.php b/includes/kohana/system/classes/kohana/session/cookie.php new file mode 100644 index 0000000..92e2a11 --- /dev/null +++ b/includes/kohana/system/classes/kohana/session/cookie.php @@ -0,0 +1,47 @@ +_name, NULL); + } + + /** + * @return null + */ + protected function _regenerate() + { + // Cookie sessions have no id + return NULL; + } + + /** + * @return bool + */ + protected function _write() + { + return Cookie::set($this->_name, $this->__toString(), $this->_lifetime); + } + + /** + * @return bool + */ + protected function _destroy() + { + return Cookie::delete($this->_name); + } + +} // End Session_Cookie diff --git a/includes/kohana/system/classes/kohana/session/native.php b/includes/kohana/system/classes/kohana/session/native.php new file mode 100644 index 0000000..961bf32 --- /dev/null +++ b/includes/kohana/system/classes/kohana/session/native.php @@ -0,0 +1,93 @@ +_lifetime, Cookie::$path, Cookie::$domain, Cookie::$secure, Cookie::$httponly); + + // Do not allow PHP to send Cache-Control headers + session_cache_limiter(FALSE); + + // Set the session cookie name + session_name($this->_name); + + if ($id) + { + // Set the session id + session_id($id); + } + + // Start the session + session_start(); + + // Use the $_SESSION global for storing data + $this->_data =& $_SESSION; + + return NULL; + } + + /** + * @return string + */ + protected function _regenerate() + { + // Regenerate the session id + session_regenerate_id(); + + return session_id(); + } + + /** + * @return bool + */ + protected function _write() + { + // Write and close the session + session_write_close(); + + return TRUE; + } + + /** + * @return bool + */ + protected function _destroy() + { + // Destroy the current session + session_destroy(); + + // Did destruction work? + $status = ! session_id(); + + if ($status) + { + // Make sure the session cannot be restarted + Cookie::delete($this->_name); + } + + return $status; + } + +} // End Session_Native diff --git a/includes/kohana/system/classes/kohana/text.php b/includes/kohana/system/classes/kohana/text.php new file mode 100644 index 0000000..7919249 --- /dev/null +++ b/includes/kohana/system/classes/kohana/text.php @@ -0,0 +1,590 @@ + 'billion', + 1000000 => 'million', + 1000 => 'thousand', + 100 => 'hundred', + 90 => 'ninety', + 80 => 'eighty', + 70 => 'seventy', + 60 => 'sixty', + 50 => 'fifty', + 40 => 'fourty', + 30 => 'thirty', + 20 => 'twenty', + 19 => 'nineteen', + 18 => 'eighteen', + 17 => 'seventeen', + 16 => 'sixteen', + 15 => 'fifteen', + 14 => 'fourteen', + 13 => 'thirteen', + 12 => 'twelve', + 11 => 'eleven', + 10 => 'ten', + 9 => 'nine', + 8 => 'eight', + 7 => 'seven', + 6 => 'six', + 5 => 'five', + 4 => 'four', + 3 => 'three', + 2 => 'two', + 1 => 'one', + ); + + /** + * Limits a phrase to a given number of words. + * + * $text = Text::limit_words($text); + * + * @param string phrase to limit words of + * @param integer number of words to limit to + * @param string end character or entity + * @return string + */ + public static function limit_words($str, $limit = 100, $end_char = NULL) + { + $limit = (int) $limit; + $end_char = ($end_char === NULL) ? '…' : $end_char; + + if (trim($str) === '') + return $str; + + if ($limit <= 0) + return $end_char; + + preg_match('/^\s*+(?:\S++\s*+){1,'.$limit.'}/u', $str, $matches); + + // Only attach the end character if the matched string is shorter + // than the starting string. + return rtrim($matches[0]).((strlen($matches[0]) === strlen($str)) ? '' : $end_char); + } + + /** + * Limits a phrase to a given number of characters. + * + * $text = Text::limit_chars($text); + * + * @param string phrase to limit characters of + * @param integer number of characters to limit to + * @param string end character or entity + * @param boolean enable or disable the preservation of words while limiting + * @return string + * @uses UTF8::strlen + */ + public static function limit_chars($str, $limit = 100, $end_char = NULL, $preserve_words = FALSE) + { + $end_char = ($end_char === NULL) ? '…' : $end_char; + + $limit = (int) $limit; + + if (trim($str) === '' OR UTF8::strlen($str) <= $limit) + return $str; + + if ($limit <= 0) + return $end_char; + + if ($preserve_words === FALSE) + return rtrim(UTF8::substr($str, 0, $limit)).$end_char; + + // Don't preserve words. The limit is considered the top limit. + // No strings with a length longer than $limit should be returned. + if ( ! preg_match('/^.{0,'.$limit.'}\s/us', $str, $matches)) + return $end_char; + + return rtrim($matches[0]).((strlen($matches[0]) === strlen($str)) ? '' : $end_char); + } + + /** + * Alternates between two or more strings. + * + * echo Text::alternate('one', 'two'); // "one" + * echo Text::alternate('one', 'two'); // "two" + * echo Text::alternate('one', 'two'); // "one" + * + * Note that using multiple iterations of different strings may produce + * unexpected results. + * + * @param string strings to alternate between + * @return string + */ + public static function alternate() + { + static $i; + + if (func_num_args() === 0) + { + $i = 0; + return ''; + } + + $args = func_get_args(); + return $args[($i++ % count($args))]; + } + + /** + * Generates a random string of a given type and length. + * + * + * $str = Text::random(); // 8 character random string + * + * The following types are supported: + * + * alnum + * : Upper and lower case a-z, 0-9 (default) + * + * alpha + * : Upper and lower case a-z + * + * hexdec + * : Hexadecimal characters a-f, 0-9 + * + * distinct + * : Uppercase characters and numbers that cannot be confused + * + * You can also create a custom type by providing the "pool" of characters + * as the type. + * + * @param string a type of pool, or a string of characters to use as the pool + * @param integer length of string to return + * @return string + * @uses UTF8::split + */ + public static function random($type = NULL, $length = 8) + { + if ($type === NULL) + { + // Default is to generate an alphanumeric string + $type = 'alnum'; + } + + $utf8 = FALSE; + + switch ($type) + { + case 'alnum': + $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + case 'alpha': + $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + case 'hexdec': + $pool = '0123456789abcdef'; + break; + case 'numeric': + $pool = '0123456789'; + break; + case 'nozero': + $pool = '123456789'; + break; + case 'distinct': + $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; + break; + default: + $pool = (string) $type; + $utf8 = ! UTF8::is_ascii($pool); + break; + } + + // Split the pool into an array of characters + $pool = ($utf8 === TRUE) ? UTF8::str_split($pool, 1) : str_split($pool, 1); + + // Largest pool key + $max = count($pool) - 1; + + $str = ''; + for ($i = 0; $i < $length; $i++) + { + // Select a random character from the pool and add it to the string + $str .= $pool[mt_rand(0, $max)]; + } + + // Make sure alnum strings contain at least one letter and one digit + if ($type === 'alnum' AND $length > 1) + { + if (ctype_alpha($str)) + { + // Add a random digit + $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57)); + } + elseif (ctype_digit($str)) + { + // Add a random letter + $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90)); + } + } + + return $str; + } + + /** + * Reduces multiple slashes in a string to single slashes. + * + * $str = Text::reduce_slashes('foo//bar/baz'); // "foo/bar/baz" + * + * @param string string to reduce slashes of + * @return string + */ + public static function reduce_slashes($str) + { + return preg_replace('#(? '#####', + * )); + * + * @param string phrase to replace words in + * @param array words to replace + * @param string replacement string + * @param boolean replace words across word boundries (space, period, etc) + * @return string + * @uses UTF8::strlen + */ + public static function censor($str, $badwords, $replacement = '#', $replace_partial_words = TRUE) + { + foreach ( (array) $badwords as $key => $badword) + { + $badwords[$key] = str_replace('\*', '\S*?', preg_quote( (string) $badword)); + } + + $regex = '('.implode('|', $badwords).')'; + + if ($replace_partial_words === FALSE) + { + // Just using \b isn't sufficient when we need to replace a badword that already contains word boundaries itself + $regex = '(?<=\b|\s|^)'.$regex.'(?=\b|\s|$)'; + } + + $regex = '!'.$regex.'!ui'; + + if (UTF8::strlen($replacement) == 1) + { + $regex .= 'e'; + return preg_replace($regex, 'str_repeat($replacement, UTF8::strlen(\'$1\'))', $str); + } + + return preg_replace($regex, $replacement, $str); + } + + /** + * Finds the text that is similar between a set of words. + * + * $match = Text::similar(array('fred', 'fran', 'free'); // "fr" + * + * @param array words to find similar text of + * @return string + */ + public static function similar(array $words) + { + // First word is the word to match against + $word = current($words); + + for ($i = 0, $max = strlen($word); $i < $max; ++$i) + { + foreach ($words as $w) + { + // Once a difference is found, break out of the loops + if ( ! isset($w[$i]) OR $w[$i] !== $word[$i]) + break 2; + } + } + + // Return the similar text + return substr($word, 0, $i); + } + + /** + * Converts text email addresses and anchors into links. Existing links + * will not be altered. + * + * echo Text::auto_link($text); + * + * [!!] This method is not foolproof since it uses regex to parse HTML. + * + * @param string text to auto link + * @return string + * @uses Text::auto_link_urls + * @uses Text::auto_link_emails + */ + public static function auto_link($text) + { + // Auto link emails first to prevent problems with "www.domain.com@example.com" + return Text::auto_link_urls(Text::auto_link_emails($text)); + } + + /** + * Converts text anchors into links. Existing links will not be altered. + * + * echo Text::auto_link_urls($text); + * + * [!!] This method is not foolproof since it uses regex to parse HTML. + * + * @param string text to auto link + * @return string + * @uses HTML::anchor + */ + public static function auto_link_urls($text) + { + // Find and replace all http/https/ftp/ftps links that are not part of an existing html anchor + $text = preg_replace_callback('~\b(?)(?:ht|f)tps?://\S+(?:/|\b)~i', 'Text::_auto_link_urls_callback1', $text); + + // Find and replace all naked www.links.com (without http://) + return preg_replace_callback('~\b(?)www(?:\.[a-z0-9][-a-z0-9]*+)+\.[a-z]{2,6}\b~i', 'Text::_auto_link_urls_callback2', $text); + } + + protected static function _auto_link_urls_callback1($matches) + { + return HTML::anchor($matches[0]); + } + + protected static function _auto_link_urls_callback2($matches) + { + return HTML::anchor('http://'.$matches[0], $matches[0]); + } + + /** + * Converts text email addresses into links. Existing links will not + * be altered. + * + * echo Text::auto_link_emails($text); + * + * [!!] This method is not foolproof since it uses regex to parse HTML. + * + * @param string text to auto link + * @return string + * @uses HTML::mailto + */ + public static function auto_link_emails($text) + { + // Find and replace all email addresses that are not part of an existing html mailto anchor + // Note: The "58;" negative lookbehind prevents matching of existing encoded html mailto anchors + // The html entity for a colon (:) is : or : or : etc. + return preg_replace_callback('~\b(?)~i', 'Text::_auto_link_emails_callback', $text); + } + + protected static function _auto_link_emails_callback($matches) + { + return HTML::mailto($matches[0]); + } + + /** + * Automatically applies "p" and "br" markup to text. + * Basically [nl2br](http://php.net/nl2br) on steroids. + * + * echo Text::auto_p($text); + * + * [!!] This method is not foolproof since it uses regex to parse HTML. + * + * @param string subject + * @param boolean convert single linebreaks to
    + * @return string + */ + public static function auto_p($str, $br = TRUE) + { + // Trim whitespace + if (($str = trim($str)) === '') + return ''; + + // Standardize newlines + $str = str_replace(array("\r\n", "\r"), "\n", $str); + + // Trim whitespace on each line + $str = preg_replace('~^[ \t]+~m', '', $str); + $str = preg_replace('~[ \t]+$~m', '', $str); + + // The following regexes only need to be executed if the string contains html + if ($html_found = (strpos($str, '<') !== FALSE)) + { + // Elements that should not be surrounded by p tags + $no_p = '(?:p|div|h[1-6r]|ul|ol|li|blockquote|d[dlt]|pre|t[dhr]|t(?:able|body|foot|head)|c(?:aption|olgroup)|form|s(?:elect|tyle)|a(?:ddress|rea)|ma(?:p|th))'; + + // Put at least two linebreaks before and after $no_p elements + $str = preg_replace('~^<'.$no_p.'[^>]*+>~im', "\n$0", $str); + $str = preg_replace('~$~im', "$0\n", $str); + } + + // Do the

    magic! + $str = '

    '.trim($str).'

    '; + $str = preg_replace('~\n{2,}~', "

    \n\n

    ", $str); + + // The following regexes only need to be executed if the string contains html + if ($html_found !== FALSE) + { + // Remove p tags around $no_p elements + $str = preg_replace('~

    (?=]*+>)~i', '', $str); + $str = preg_replace('~(]*+>)

    ~i', '$1', $str); + } + + // Convert single linebreaks to
    + if ($br === TRUE) + { + $str = preg_replace('~(?\n", $str); + } + + return $str; + } + + /** + * Returns human readable sizes. Based on original functions written by + * [Aidan Lister](http://aidanlister.com/repos/v/function.size_readable.php) + * and [Quentin Zervaas](http://www.phpriot.com/d/code/strings/filesize-format/). + * + * echo Text::bytes(filesize($file)); + * + * @param integer size in bytes + * @param string a definitive unit + * @param string the return string format + * @param boolean whether to use SI prefixes or IEC + * @return string + */ + public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE) + { + // Format string + $format = ($format === NULL) ? '%01.2f %s' : (string) $format; + + // IEC prefixes (binary) + if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE) + { + $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); + $mod = 1024; + } + // SI prefixes (decimal) + else + { + $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB'); + $mod = 1000; + } + + // Determine unit to use + if (($power = array_search( (string) $force_unit, $units)) === FALSE) + { + $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0; + } + + return sprintf($format, $bytes / pow($mod, $power), $units[$power]); + } + + /** + * Format a number to human-readable text. + * + * // Display: one thousand and twenty-four + * echo Text::number(1024); + * + * // Display: five million, six hundred and thirty-two + * echo Text::number(5000632); + * + * @param integer number to format + * @return string + * @since 3.0.8 + */ + public static function number($number) + { + // The number must always be an integer + $number = (int) $number; + + // Uncompiled text version + $text = array(); + + // Last matched unit within the loop + $last_unit = NULL; + + // The last matched item within the loop + $last_item = ''; + + foreach (Text::$units as $unit => $name) + { + if ($number / $unit >= 1) + { + // $value = the number of times the number is divisble by unit + $number -= $unit * ($value = (int) floor($number / $unit)); + // Temporary var for textifying the current unit + $item = ''; + + if ($unit < 100) + { + if ($last_unit < 100 AND $last_unit >= 20) + { + $last_item .= '-'.$name; + } + else + { + $item = $name; + } + } + else + { + $item = Text::number($value).' '.$name; + } + + // In the situation that we need to make a composite number (i.e. twenty-three) + // then we need to modify the previous entry + if (empty($item)) + { + array_pop($text); + + $item = $last_item; + } + + $last_item = $text[] = $item; + $last_unit = $unit; + } + } + + if (count($text) > 1) + { + $and = array_pop($text); + } + + $text = implode(', ', $text); + + if (isset($and)) + { + $text .= ' and '.$and; + } + + return $text; + } + + /** + * Prevents [widow words](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin) + * by inserting a non-breaking space between the last two words. + * + * echo Text::widont($text); + * + * @param string text to remove widows from + * @return string + */ + public static function widont($str) + { + $str = rtrim($str); + $space = strrpos($str, ' '); + + if ($space !== FALSE) + { + $str = substr($str, 0, $space).' '.substr($str, $space + 1); + } + + return $str; + } + +} // End text diff --git a/includes/kohana/system/classes/kohana/upload.php b/includes/kohana/system/classes/kohana/upload.php new file mode 100644 index 0000000..6ab5a50 --- /dev/null +++ b/includes/kohana/system/classes/kohana/upload.php @@ -0,0 +1,213 @@ +check()) + * { + * // Upload is valid, save it + * Upload::save($_FILES['file']); + * } + * + * @param array uploaded file data + * @param string new filename + * @param string new directory + * @param integer chmod mask + * @return string on success, full path to new file + * @return FALSE on failure + */ + public static function save(array $file, $filename = NULL, $directory = NULL, $chmod = 0644) + { + if ( ! isset($file['tmp_name']) OR ! is_uploaded_file($file['tmp_name'])) + { + // Ignore corrupted uploads + return FALSE; + } + + if ($filename === NULL) + { + // Use the default filename, with a timestamp pre-pended + $filename = uniqid().$file['name']; + } + + if (Upload::$remove_spaces === TRUE) + { + // Remove spaces from the filename + $filename = preg_replace('/\s+/', '_', $filename); + } + + if ($directory === NULL) + { + // Use the pre-configured upload directory + $directory = Upload::$default_directory; + } + + if ( ! is_dir($directory) OR ! is_writable(realpath($directory))) + { + throw new Kohana_Exception('Directory :dir must be writable', + array(':dir' => Kohana::debug_path($directory))); + } + + // Make the filename into a complete path + $filename = realpath($directory).DIRECTORY_SEPARATOR.$filename; + + if (move_uploaded_file($file['tmp_name'], $filename)) + { + if ($chmod !== FALSE) + { + // Set permissions on filename + chmod($filename, $chmod); + } + + // Return new file path + return $filename; + } + + return FALSE; + } + + /** + * Tests if upload data is valid, even if no file was uploaded. If you + * _do_ require a file to be uploaded, add the [Upload::not_empty] rule + * before this rule. + * + * $array->rule('file', 'Upload::valid') + * + * @param array $_FILES item + * @return bool + */ + public static function valid($file) + { + return (isset($file['error']) + AND isset($file['name']) + AND isset($file['type']) + AND isset($file['tmp_name']) + AND isset($file['size'])); + } + + /** + * Tests if a successful upload has been made. + * + * $array->rule('file', 'Upload::not_empty'); + * + * @param array $_FILES item + * @return bool + */ + public static function not_empty(array $file) + { + return (isset($file['error']) + AND isset($file['tmp_name']) + AND $file['error'] === UPLOAD_ERR_OK + AND is_uploaded_file($file['tmp_name']) + ); + } + + /** + * Test if an uploaded file is an allowed file type, by extension. + * + * $array->rule('file', 'Upload::type', array(array('jpg', 'png', 'gif'))); + * + * @param array $_FILES item + * @param array allowed file extensions + * @return bool + */ + public static function type(array $file, array $allowed) + { + if ($file['error'] !== UPLOAD_ERR_OK) + return TRUE; + + $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); + + return in_array($ext, $allowed); + } + + /** + * Validation rule to test if an uploaded file is allowed by file size. + * File sizes are defined as: SB, where S is the size (1, 15, 300, etc) and + * B is the byte modifier: (B)ytes, (K)ilobytes, (M)egabytes, (G)igabytes. + * + * $array->rule('file', 'Upload::size', array('1M')) + * + * @param array $_FILES item + * @param string maximum file size + * @return bool + */ + public static function size(array $file, $size) + { + if ($file['error'] === UPLOAD_ERR_INI_SIZE) + { + // Upload is larger than PHP allowed size + return FALSE; + } + + if ($file['error'] !== UPLOAD_ERR_OK) + { + // The upload failed, no size to check + return TRUE; + } + + // Only one size is allowed + $size = strtoupper(trim($size)); + + if ( ! preg_match('/^[0-9]++[BKMG]$/', $size)) + { + throw new Kohana_Exception('Size does not contain a digit and a byte value: :size', array( + ':size' => $size, + )); + } + + // Make the size into a power of 1024 + switch (substr($size, -1)) + { + case 'G': + $size = intval($size) * pow(1024, 3); + break; + case 'M': + $size = intval($size) * pow(1024, 2); + break; + case 'K': + $size = intval($size) * pow(1024, 1); + break; + default: + $size = intval($size); + break; + } + + // Test that the file is under or equal to the max size + return ($file['size'] <= $size); + } + +} // End upload diff --git a/includes/kohana/system/classes/kohana/url.php b/includes/kohana/system/classes/kohana/url.php new file mode 100644 index 0000000..359870c --- /dev/null +++ b/includes/kohana/system/classes/kohana/url.php @@ -0,0 +1,186 @@ + 'title', 'limit' => 10)); + * + * Typically you would use this when you are sorting query results, + * or something similar. + * + * [!!] Parameters with a NULL value are left out. + * + * @param array array of GET parameters + * @param boolean include current request GET parameters + * @return string + */ + public static function query(array $params = NULL, $use_get = TRUE) + { + if ($use_get) + { + if ($params === NULL) + { + // Use only the current parameters + $params = $_GET; + } + else + { + // Merge the current and new parameters + $params = array_merge($_GET, $params); + } + } + + if (empty($params)) + { + // No query parameters + return ''; + } + + // Note: http_build_query returns an empty string for a params array with only NULL values + $query = http_build_query($params, '', '&'); + + // Don't prepend '?' to an empty string + return ($query === '') ? '' : ('?'.$query); + } + + /** + * Convert a phrase to a URL-safe title. + * + * echo URL::title('My Blog Post'); // "my-blog-post" + * + * @param string phrase to convert + * @param string word separator (any single character) + * @param boolean transliterate to ASCII? + * @return string + * @uses UTF8::transliterate_to_ascii + */ + public static function title($title, $separator = '-', $ascii_only = FALSE) + { + if ($ascii_only === TRUE) + { + // Transliterate non-ASCII characters + $title = UTF8::transliterate_to_ascii($title); + + // Remove all characters that are not the separator, a-z, 0-9, or whitespace + $title = preg_replace('![^'.preg_quote($separator).'a-z0-9\s]+!', '', strtolower($title)); + } + else + { + // Remove all characters that are not the separator, letters, numbers, or whitespace + $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', UTF8::strtolower($title)); + } + + // Replace all separator characters and whitespace by a single separator + $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); + + // Trim separators from the beginning and end + return trim($title, $separator); + } + +} // End url \ No newline at end of file diff --git a/includes/kohana/system/classes/kohana/utf8.php b/includes/kohana/system/classes/kohana/utf8.php new file mode 100644 index 0000000..cfcaef1 --- /dev/null +++ b/includes/kohana/system/classes/kohana/utf8.php @@ -0,0 +1,767 @@ + $val) + { + // Recursion! + $var[self::clean($key)] = self::clean($val); + } + } + elseif (is_string($var) AND $var !== '') + { + // Remove control characters + $var = self::strip_ascii_ctrl($var); + + if ( ! self::is_ascii($var)) + { + // Disable notices + $error_reporting = error_reporting(~E_NOTICE); + + // iconv is expensive, so it is only used when needed + $var = iconv($charset, $charset.'//IGNORE', $var); + + // Turn notices back on + error_reporting($error_reporting); + } + } + + return $var; + } + + /** + * Tests whether a string contains only 7-bit ASCII bytes. This is used to + * determine when to use native functions or UTF-8 functions. + * + * $ascii = UTF8::is_ascii($str); + * + * @param mixed string or array of strings to check + * @return boolean + */ + public static function is_ascii($str) + { + if (is_array($str)) + { + $str = implode($str); + } + + return ! preg_match('/[^\x00-\x7F]/S', $str); + } + + /** + * Strips out device control codes in the ASCII range. + * + * $str = UTF8::strip_ascii_ctrl($str); + * + * @param string string to clean + * @return string + */ + public static function strip_ascii_ctrl($str) + { + return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $str); + } + + /** + * Strips out all non-7bit ASCII bytes. + * + * $str = UTF8::strip_non_ascii($str); + * + * @param string string to clean + * @return string + */ + public static function strip_non_ascii($str) + { + return preg_replace('/[^\x00-\x7F]+/S', '', $str); + } + + /** + * Replaces special/accented UTF-8 characters by ASCII-7 "equivalents". + * + * $ascii = UTF8::transliterate_to_ascii($utf8); + * + * @author Andreas Gohr + * @param string string to transliterate + * @param integer -1 lowercase only, +1 uppercase only, 0 both cases + * @return string + */ + public static function transliterate_to_ascii($str, $case = 0) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _transliterate_to_ascii($str, $case); + } + + /** + * Returns the length of the given string. This is a UTF8-aware version + * of [strlen](http://php.net/strlen). + * + * $length = UTF8::strlen($str); + * + * @param string string being measured for length + * @return integer + * @uses UTF8::$server_utf8 + */ + public static function strlen($str) + { + if (UTF8::$server_utf8) + return mb_strlen($str, Kohana::$charset); + + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strlen($str); + } + + /** + * Finds position of first occurrence of a UTF-8 string. This is a + * UTF8-aware version of [strpos](http://php.net/strpos). + * + * $position = UTF8::strpos($str, $search); + * + * @author Harry Fuecks + * @param string haystack + * @param string needle + * @param integer offset from which character in haystack to start searching + * @return integer position of needle + * @return boolean FALSE if the needle is not found + * @uses UTF8::$server_utf8 + */ + public static function strpos($str, $search, $offset = 0) + { + if (UTF8::$server_utf8) + return mb_strpos($str, $search, $offset, Kohana::$charset); + + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strpos($str, $search, $offset); + } + + /** + * Finds position of last occurrence of a char in a UTF-8 string. This is + * a UTF8-aware version of [strrpos](http://php.net/strrpos). + * + * $position = UTF8::strrpos($str, $search); + * + * @author Harry Fuecks + * @param string haystack + * @param string needle + * @param integer offset from which character in haystack to start searching + * @return integer position of needle + * @return boolean FALSE if the needle is not found + * @uses UTF8::$server_utf8 + */ + public static function strrpos($str, $search, $offset = 0) + { + if (UTF8::$server_utf8) + return mb_strrpos($str, $search, $offset, Kohana::$charset); + + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strrpos($str, $search, $offset); + } + + /** + * Returns part of a UTF-8 string. This is a UTF8-aware version + * of [substr](http://php.net/substr). + * + * $sub = UTF8::substr($str, $offset); + * + * @author Chris Smith + * @param string input string + * @param integer offset + * @param integer length limit + * @return string + * @uses UTF8::$server_utf8 + * @uses Kohana::$charset + */ + public static function substr($str, $offset, $length = NULL) + { + if (UTF8::$server_utf8) + return ($length === NULL) + ? mb_substr($str, $offset, mb_strlen($str), Kohana::$charset) + : mb_substr($str, $offset, $length, Kohana::$charset); + + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _substr($str, $offset, $length); + } + + /** + * Replaces text within a portion of a UTF-8 string. This is a UTF8-aware + * version of [substr_replace](http://php.net/substr_replace). + * + * $str = UTF8::substr_replace($str, $replacement, $offset); + * + * @author Harry Fuecks + * @param string input string + * @param string replacement string + * @param integer offset + * @return string + */ + public static function substr_replace($str, $replacement, $offset, $length = NULL) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _substr_replace($str, $replacement, $offset, $length); + } + + /** + * Makes a UTF-8 string lowercase. This is a UTF8-aware version + * of [strtolower](http://php.net/strtolower). + * + * $str = UTF8::strtolower($str); + * + * @author Andreas Gohr + * @param string mixed case string + * @return string + * @uses UTF8::$server_utf8 + */ + public static function strtolower($str) + { + if (UTF8::$server_utf8) + return mb_strtolower($str, Kohana::$charset); + + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strtolower($str); + } + + /** + * Makes a UTF-8 string uppercase. This is a UTF8-aware version + * of [strtoupper](http://php.net/strtoupper). + * + * @author Andreas Gohr + * @param string mixed case string + * @return string + * @uses UTF8::$server_utf8 + * @uses Kohana::$charset + */ + public static function strtoupper($str) + { + if (UTF8::$server_utf8) + return mb_strtoupper($str, Kohana::$charset); + + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strtoupper($str); + } + + /** + * Makes a UTF-8 string's first character uppercase. This is a UTF8-aware + * version of [ucfirst](http://php.net/ucfirst). + * + * $str = UTF8::ucfirst($str); + * + * @author Harry Fuecks + * @param string mixed case string + * @return string + */ + public static function ucfirst($str) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _ucfirst($str); + } + + /** + * Makes the first character of every word in a UTF-8 string uppercase. + * This is a UTF8-aware version of [ucwords](http://php.net/ucwords). + * + * $str = UTF8::ucwords($str); + * + * @author Harry Fuecks + * @param string mixed case string + * @return string + * @uses UTF8::$server_utf8 + */ + public static function ucwords($str) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _ucwords($str); + } + + /** + * Case-insensitive UTF-8 string comparison. This is a UTF8-aware version + * of [strcasecmp](http://php.net/strcasecmp). + * + * $compare = UTF8::strcasecmp($str1, $str2); + * + * @author Harry Fuecks + * @param string string to compare + * @param string string to compare + * @return integer less than 0 if str1 is less than str2 + * @return integer greater than 0 if str1 is greater than str2 + * @return integer 0 if they are equal + */ + public static function strcasecmp($str1, $str2) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strcasecmp($str1, $str2); + } + + /** + * Returns a string or an array with all occurrences of search in subject + * (ignoring case) and replaced with the given replace value. This is a + * UTF8-aware version of [str_ireplace](http://php.net/str_ireplace). + * + * [!!] This function is very slow compared to the native version. Avoid + * using it when possible. + * + * @author Harry Fuecks + * @param string input string + * @param string needle + * @return string matched substring if found + * @return FALSE if the substring was not found + */ + public static function stristr($str, $search) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _stristr($str, $search); + } + + /** + * Finds the length of the initial segment matching mask. This is a + * UTF8-aware version of [strspn](http://php.net/strspn). + * + * $found = UTF8::strspn($str, $mask); + * + * @author Harry Fuecks + * @param string input string + * @param string mask for search + * @param integer start position of the string to examine + * @param integer length of the string to examine + * @return integer length of the initial segment that contains characters in the mask + */ + public static function strspn($str, $mask, $offset = NULL, $length = NULL) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strspn($str, $mask, $offset, $length); + } + + /** + * Finds the length of the initial segment not matching mask. This is a + * UTF8-aware version of [strcspn](http://php.net/strcspn). + * + * $found = UTF8::strcspn($str, $mask); + * + * @author Harry Fuecks + * @param string input string + * @param string mask for search + * @param integer start position of the string to examine + * @param integer length of the string to examine + * @return integer length of the initial segment that contains characters not in the mask + */ + public static function strcspn($str, $mask, $offset = NULL, $length = NULL) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strcspn($str, $mask, $offset, $length); + } + + /** + * Pads a UTF-8 string to a certain length with another string. This is a + * UTF8-aware version of [str_pad](http://php.net/str_pad). + * + * $str = UTF8::str_pad($str, $length); + * + * @author Harry Fuecks + * @param string input string + * @param integer desired string length after padding + * @param string string to use as padding + * @param string padding type: STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH + * @return string + */ + public static function str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _str_pad($str, $final_str_length, $pad_str, $pad_type); + } + + /** + * Converts a UTF-8 string to an array. This is a UTF8-aware version of + * [str_split](http://php.net/str_split). + * + * $array = UTF8::str_split($str); + * + * @author Harry Fuecks + * @param string input string + * @param integer maximum length of each chunk + * @return array + */ + public static function str_split($str, $split_length = 1) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _str_split($str, $split_length); + } + + /** + * Reverses a UTF-8 string. This is a UTF8-aware version of [strrev](http://php.net/strrev). + * + * $str = UTF8::strrev($str); + * + * @author Harry Fuecks + * @param string string to be reversed + * @return string + */ + public static function strrev($str) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _strrev($str); + } + + /** + * Strips whitespace (or other UTF-8 characters) from the beginning and + * end of a string. This is a UTF8-aware version of [trim](http://php.net/trim). + * + * $str = UTF8::trim($str); + * + * @author Andreas Gohr + * @param string input string + * @param string string of characters to remove + * @return string + */ + public static function trim($str, $charlist = NULL) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _trim($str, $charlist); + } + + /** + * Strips whitespace (or other UTF-8 characters) from the beginning of + * a string. This is a UTF8-aware version of [ltrim](http://php.net/ltrim). + * + * $str = UTF8::ltrim($str); + * + * @author Andreas Gohr + * @param string input string + * @param string string of characters to remove + * @return string + */ + public static function ltrim($str, $charlist = NULL) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _ltrim($str, $charlist); + } + + /** + * Strips whitespace (or other UTF-8 characters) from the end of a string. + * This is a UTF8-aware version of [rtrim](http://php.net/rtrim). + * + * $str = UTF8::rtrim($str); + * + * @author Andreas Gohr + * @param string input string + * @param string string of characters to remove + * @return string + */ + public static function rtrim($str, $charlist = NULL) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _rtrim($str, $charlist); + } + + /** + * Returns the unicode ordinal for a character. This is a UTF8-aware + * version of [ord](http://php.net/ord). + * + * $digit = UTF8::ord($character); + * + * @author Harry Fuecks + * @param string UTF-8 encoded character + * @return integer + */ + public static function ord($chr) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _ord($chr); + } + + /** + * Takes an UTF-8 string and returns an array of ints representing the Unicode characters. + * Astral planes are supported i.e. the ints in the output can be > 0xFFFF. + * Occurrences of the BOM are ignored. Surrogates are not allowed. + * + * $array = UTF8::to_unicode($str); + * + * The Original Code is Mozilla Communicator client code. + * The Initial Developer of the Original Code is Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer. + * Ported to PHP by Henri Sivonen , see + * Slight modifications to fit with phputf8 library by Harry Fuecks + * + * @param string UTF-8 encoded string + * @return array unicode code points + * @return FALSE if the string is invalid + */ + public static function to_unicode($str) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _to_unicode($str); + } + + /** + * Takes an array of ints representing the Unicode characters and returns a UTF-8 string. + * Astral planes are supported i.e. the ints in the input can be > 0xFFFF. + * Occurrances of the BOM are ignored. Surrogates are not allowed. + * + * $str = UTF8::to_unicode($array); + * + * The Original Code is Mozilla Communicator client code. + * The Initial Developer of the Original Code is Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer. + * Ported to PHP by Henri Sivonen , see http://hsivonen.iki.fi/php-utf8/ + * Slight modifications to fit with phputf8 library by Harry Fuecks . + * + * @param array unicode code points representing a string + * @return string utf8 string of characters + * @return boolean FALSE if a code point cannot be found + */ + public static function from_unicode($arr) + { + if ( ! isset(self::$called[__FUNCTION__])) + { + require SYSPATH.'utf8'.DIRECTORY_SEPARATOR.__FUNCTION__.EXT; + + // Function has been called + self::$called[__FUNCTION__] = TRUE; + } + + return _from_unicode($arr); + } + +} // End UTF8 + +if (Kohana_UTF8::$server_utf8 === NULL) +{ + // Determine if this server supports UTF-8 natively + Kohana_UTF8::$server_utf8 = extension_loaded('mbstring'); +} diff --git a/includes/kohana/system/classes/kohana/validate.php b/includes/kohana/system/classes/kohana/validate.php new file mode 100644 index 0000000..70b036e --- /dev/null +++ b/includes/kohana/system/classes/kohana/validate.php @@ -0,0 +1,1190 @@ +getArrayCopy(); + } + + // Value cannot be NULL, FALSE, '', or an empty array + return ! in_array($value, array(NULL, FALSE, '', array()), TRUE); + } + + /** + * Checks a field against a regular expression. + * + * @param string value + * @param string regular expression to match (including delimiters) + * @return boolean + */ + public static function regex($value, $expression) + { + return (bool) preg_match($expression, (string) $value); + } + + /** + * Checks that a field is long enough. + * + * @param string value + * @param integer minimum length required + * @return boolean + */ + public static function min_length($value, $length) + { + return UTF8::strlen($value) >= $length; + } + + /** + * Checks that a field is short enough. + * + * @param string value + * @param integer maximum length required + * @return boolean + */ + public static function max_length($value, $length) + { + return UTF8::strlen($value) <= $length; + } + + /** + * Checks that a field is exactly the right length. + * + * @param string value + * @param integer exact length required + * @return boolean + */ + public static function exact_length($value, $length) + { + return UTF8::strlen($value) === $length; + } + + /** + * CHecks that a field is exactly the value required. + * + * @param string value + * @param string required value + * @return boolean + */ + public static function equals($value, $required) + { + return ($value === $required); + } + + /** + * Check an email address for correct format. + * + * @link http://www.iamcal.com/publish/articles/php/parsing_email/ + * @link http://www.w3.org/Protocols/rfc822/ + * + * @param string email address + * @param boolean strict RFC compatibility + * @return boolean + */ + public static function email($email, $strict = FALSE) + { + if ($strict === TRUE) + { + $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; + $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; + $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; + $pair = '\\x5c[\\x00-\\x7f]'; + + $domain_literal = "\\x5b($dtext|$pair)*\\x5d"; + $quoted_string = "\\x22($qtext|$pair)*\\x22"; + $sub_domain = "($atom|$domain_literal)"; + $word = "($atom|$quoted_string)"; + $domain = "$sub_domain(\\x2e$sub_domain)*"; + $local_part = "$word(\\x2e$word)*"; + + $expression = "/^$local_part\\x40$domain$/D"; + } + else + { + $expression = '/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(? 253) + return FALSE; + + // An extra check for the top level domain + // It must start with a letter + $tld = ltrim(substr($matches[1], (int) strrpos($matches[1], '.')), '.'); + return ctype_alpha($tld[0]); + } + + /** + * Validate an IP. + * + * @param string IP address + * @param boolean allow private IP networks + * @return boolean + */ + public static function ip($ip, $allow_private = TRUE) + { + // Do not allow reserved addresses + $flags = FILTER_FLAG_NO_RES_RANGE; + + if ($allow_private === FALSE) + { + // Do not allow private or reserved addresses + $flags = $flags | FILTER_FLAG_NO_PRIV_RANGE; + } + + return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flags); + } + + /** + * Validates a credit card number, with a Luhn check if possible. + * + * @param integer credit card number + * @param string|array card type, or an array of card types + * @return boolean + * @uses Validate::luhn + */ + public static function credit_card($number, $type = NULL) + { + // Remove all non-digit characters from the number + if (($number = preg_replace('/\D+/', '', $number)) === '') + return FALSE; + + if ($type == NULL) + { + // Use the default type + $type = 'default'; + } + elseif (is_array($type)) + { + foreach ($type as $t) + { + // Test each type for validity + if (Validate::credit_card($number, $t)) + return TRUE; + } + + return FALSE; + } + + $cards = Kohana::config('credit_cards'); + + // Check card type + $type = strtolower($type); + + if ( ! isset($cards[$type])) + return FALSE; + + // Check card number length + $length = strlen($number); + + // Validate the card length by the card type + if ( ! in_array($length, preg_split('/\D+/', $cards[$type]['length']))) + return FALSE; + + // Check card number prefix + if ( ! preg_match('/^'.$cards[$type]['prefix'].'/', $number)) + return FALSE; + + // No Luhn check required + if ($cards[$type]['luhn'] == FALSE) + return TRUE; + + return Validate::luhn($number); + } + + /** + * Validate a number against the [Luhn](http://en.wikipedia.org/wiki/Luhn_algorithm) + * (mod10) formula. + * + * @param string number to check + * @return boolean + */ + public static function luhn($number) + { + // Force the value to be a string as this method uses string functions. + // Converting to an integer may pass PHP_INT_MAX and result in an error! + $number = (string) $number; + + if ( ! ctype_digit($number)) + { + // Luhn can only be used on numbers! + return FALSE; + } + + // Check number length + $length = strlen($number); + + // Checksum of the card number + $checksum = 0; + + for ($i = $length - 1; $i >= 0; $i -= 2) + { + // Add up every 2nd digit, starting from the right + $checksum += substr($number, $i, 1); + } + + for ($i = $length - 2; $i >= 0; $i -= 2) + { + // Add up every 2nd digit doubled, starting from the right + $double = substr($number, $i, 1) * 2; + + // Subtract 9 from the double where value is greater than 10 + $checksum += ($double >= 10) ? ($double - 9) : $double; + } + + // If the checksum is a multiple of 10, the number is valid + return ($checksum % 10 === 0); + } + + /** + * Checks if a phone number is valid. + * + * @param string phone number to check + * @return boolean + */ + public static function phone($number, $lengths = NULL) + { + if ( ! is_array($lengths)) + { + $lengths = array(7,10,11); + } + + // Remove all non-digit characters from the number + $number = preg_replace('/\D+/', '', $number); + + // Check if the number is within range + return in_array(strlen($number), $lengths); + } + + /** + * Tests if a string is a valid date string. + * + * @param string date to check + * @return boolean + */ + public static function date($str) + { + return (strtotime($str) !== FALSE); + } + + /** + * Checks whether a string consists of alphabetical characters only. + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function alpha($str, $utf8 = FALSE) + { + $str = (string) $str; + + if ($utf8 === TRUE) + { + return (bool) preg_match('/^\pL++$/uD', $str); + } + else + { + return ctype_alpha($str); + } + } + + /** + * Checks whether a string consists of alphabetical characters and numbers only. + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function alpha_numeric($str, $utf8 = FALSE) + { + if ($utf8 === TRUE) + { + return (bool) preg_match('/^[\pL\pN]++$/uD', $str); + } + else + { + return ctype_alnum($str); + } + } + + /** + * Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only. + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function alpha_dash($str, $utf8 = FALSE) + { + if ($utf8 === TRUE) + { + $regex = '/^[-\pL\pN_]++$/uD'; + } + else + { + $regex = '/^[-a-z0-9_]++$/iD'; + } + + return (bool) preg_match($regex, $str); + } + + /** + * Checks whether a string consists of digits only (no dots or dashes). + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function digit($str, $utf8 = FALSE) + { + if ($utf8 === TRUE) + { + return (bool) preg_match('/^\pN++$/uD', $str); + } + else + { + return (is_int($str) AND $str >= 0) OR ctype_digit($str); + } + } + + /** + * Checks whether a string is a valid number (negative and decimal numbers allowed). + * + * Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion} + * to allow decimal point to be locale specific. + * + * @param string input string + * @return boolean + */ + public static function numeric($str) + { + // Get the decimal point for the current locale + list($decimal) = array_values(localeconv()); + + // A lookahead is used to make sure the string contains at least one digit (before or after the decimal point) + return (bool) preg_match('/^-?+(?=.*[0-9])[0-9]*+'.preg_quote($decimal).'?+[0-9]*+$/D', (string) $str); + } + + /** + * Tests if a number is within a range. + * + * @param string number to check + * @param integer minimum value + * @param integer maximum value + * @return boolean + */ + public static function range($number, $min, $max) + { + return ($number >= $min AND $number <= $max); + } + + /** + * Checks if a string is a proper decimal format. Optionally, a specific + * number of digits can be checked too. + * + * @param string number to check + * @param integer number of decimal places + * @param integer number of digits + * @return boolean + */ + public static function decimal($str, $places = 2, $digits = NULL) + { + if ($digits > 0) + { + // Specific number of digits + $digits = '{'. (int) $digits.'}'; + } + else + { + // Any number of digits + $digits = '+'; + } + + // Get the decimal point for the current locale + list($decimal) = array_values(localeconv()); + + return (bool) preg_match('/^[0-9]'.$digits.preg_quote($decimal).'[0-9]{'. (int) $places.'}$/D', $str); + } + + /** + * Checks if a string is a proper hexadecimal HTML color value. The validation + * is quite flexible as it does not require an initial "#" and also allows for + * the short notation using only three instead of six hexadecimal characters. + * + * @param string input string + * @return boolean + */ + public static function color($str) + { + return (bool) preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $str); + } + + // Field filters + protected $_filters = array(); + + // Field rules + protected $_rules = array(); + + // Field callbacks + protected $_callbacks = array(); + + // Field labels + protected $_labels = array(); + + // Rules that are executed even when the value is empty + protected $_empty_rules = array('not_empty', 'matches'); + + // Error list, field => rule + protected $_errors = array(); + + /** + * Sets the unique "any field" key and creates an ArrayObject from the + * passed array. + * + * @param array array to validate + * @return void + */ + public function __construct(array $array) + { + parent::__construct($array, ArrayObject::STD_PROP_LIST); + } + + /** + * Copies the current filter/rule/callback to a new array. + * + * $copy = $array->copy($new_data); + * + * @param array new data set + * @return Validation + * @since 3.0.5 + */ + public function copy(array $array) + { + // Create a copy of the current validation set + $copy = clone $this; + + // Replace the data set + $copy->exchangeArray($array); + + return $copy; + } + + /** + * Returns the array representation of the current object. + * + * @return array + */ + public function as_array() + { + return $this->getArrayCopy(); + } + + /** + * Sets or overwrites the label name for a field. + * + * @param string field name + * @param string label + * @return $this + */ + public function label($field, $label) + { + // Set the label for this field + $this->_labels[$field] = $label; + + return $this; + } + + /** + * Sets labels using an array. + * + * @param array list of field => label names + * @return $this + */ + public function labels(array $labels) + { + $this->_labels = $labels + $this->_labels; + + return $this; + } + + /** + * Overwrites or appends filters to a field. Each filter will be executed once. + * All rules must be valid PHP callbacks. + * + * // Run trim() on all fields + * $validation->filter(TRUE, 'trim'); + * + * @param string field name + * @param mixed valid PHP callback + * @param array extra parameters for the filter + * @return $this + */ + public function filter($field, $filter, array $params = NULL) + { + if ($field !== TRUE AND ! isset($this->_labels[$field])) + { + // Set the field label to the field name + $this->_labels[$field] = preg_replace('/[^\pL]+/u', ' ', $field); + } + + // Store the filter and params for this rule + $this->_filters[$field][$filter] = (array) $params; + + return $this; + } + + /** + * Add filters using an array. + * + * @param string field name + * @param array list of functions or static method name + * @return $this + */ + public function filters($field, array $filters) + { + foreach ($filters as $filter => $params) + { + $this->filter($field, $filter, $params); + } + + return $this; + } + + /** + * Overwrites or appends rules to a field. Each rule will be executed once. + * All rules must be string names of functions method names. + * + * // The "username" must not be empty and have a minimum length of 4 + * $validation->rule('username', 'not_empty') + * ->rule('username', 'min_length', array(4)); + * + * @param string field name + * @param string function or static method name + * @param array extra parameters for the rule + * @return $this + */ + public function rule($field, $rule, array $params = NULL) + { + if ($field !== TRUE AND ! isset($this->_labels[$field])) + { + // Set the field label to the field name + $this->_labels[$field] = trim(preg_replace('/[^\pL]+/u', ' ', $field)); + } + + if ('matches' === $rule AND ! isset($this->_labels[$params[0]])) + { + $match_field = $params[0]; + $this->_labels[$match_field] = trim(preg_replace('/[^\pL]+/u', ' ', $match_field)); + } + + // Store the rule and params for this rule + $this->_rules[$field][$rule] = (array) $params; + + return $this; + } + + /** + * Add rules using an array. + * + * @param string field name + * @param array list of functions or static method name + * @return $this + */ + public function rules($field, array $rules) + { + foreach ($rules as $rule => $params) + { + $this->rule($field, $rule, $params); + } + + return $this; + } + + /** + * Adds a callback to a field. Each callback will be executed only once. + * + * // The "username" must be checked with a custom method + * $validation->callback('username', array($this, 'check_username')); + * + * To add a callback to every field already set, use TRUE for the field name. + * + * @param string field name + * @param mixed callback to add + * @param array extra parameters for the callback + * @return $this + */ + public function callback($field, $callback, array $params = array()) + { + if ( ! isset($this->_callbacks[$field])) + { + // Create the list for this field + $this->_callbacks[$field] = array(); + } + + if ($field !== TRUE AND ! isset($this->_labels[$field])) + { + // Set the field label to the field name + $this->_labels[$field] = preg_replace('/[^\pL]+/u', ' ', $field); + } + + if ( ! in_array($callback, $this->_callbacks[$field], TRUE)) + { + // Store the callback + $this->_callbacks[$field][] = array($callback, $params); + } + + return $this; + } + + /** + * Add callbacks using an array. + * + * @param string field name + * @param array list of callbacks + * @return $this + */ + public function callbacks($field, array $callbacks) + { + foreach ($callbacks as $callback) + { + $this->callback($field, $callback); + } + + return $this; + } + + /** + * Executes all validation filters, rules, and callbacks. This should + * typically be called within an if/else block. + * + * if ($validation->check()) + * { + * // The data is valid, do something here + * } + * + * @param boolean allow empty array? + * @return boolean + */ + public function check($allow_empty = FALSE) + { + if (Kohana::$profiling === TRUE) + { + // Start a new benchmark + $benchmark = Profiler::start('Validation', __FUNCTION__); + } + + // New data set + $data = $this->_errors = array(); + + // Assume nothing has been submitted + $submitted = FALSE; + + // Get a list of the expected fields + $expected = array_keys($this->_labels); + + // Import the filters, rules, and callbacks locally + $filters = $this->_filters; + $rules = $this->_rules; + $callbacks = $this->_callbacks; + + foreach ($expected as $field) + { + if (isset($this[$field])) + { + // Some data has been submitted, continue validation + $submitted = TRUE; + + // Use the submitted value + $data[$field] = $this[$field]; + } + else + { + // No data exists for this field + $data[$field] = NULL; + } + + if (isset($filters[TRUE])) + { + if ( ! isset($filters[$field])) + { + // Initialize the filters for this field + $filters[$field] = array(); + } + + // Append the filters + $filters[$field] += $filters[TRUE]; + } + + if (isset($rules[TRUE])) + { + if ( ! isset($rules[$field])) + { + // Initialize the rules for this field + $rules[$field] = array(); + } + + // Append the rules + $rules[$field] += $rules[TRUE]; + } + + if (isset($callbacks[TRUE])) + { + if ( ! isset($callbacks[$field])) + { + // Initialize the callbacks for this field + $callbacks[$field] = array(); + } + + // Append the callbacks + $callbacks[$field] += $callbacks[TRUE]; + } + } + + // Overload the current array with the new one + $this->exchangeArray($data); + + if ($submitted === FALSE AND ! $allow_empty) + { + // Because no data was submitted, validation will not be forced + return FALSE; + } + + // Remove the filters, rules, and callbacks that apply to every field + unset($filters[TRUE], $rules[TRUE], $callbacks[TRUE]); + + // Execute the filters + + foreach ($filters as $field => $set) + { + // Get the field value + $value = $this[$field]; + + foreach ($set as $filter => $params) + { + // Add the field value to the parameters + array_unshift($params, $value); + + if (strpos($filter, '::') === FALSE) + { + // Use a function call + $function = new ReflectionFunction($filter); + + // Call $function($this[$field], $param, ...) with Reflection + $value = $function->invokeArgs($params); + } + else + { + // Split the class and method of the rule + list($class, $method) = explode('::', $filter, 2); + + // Use a static method call + $method = new ReflectionMethod($class, $method); + + // Call $Class::$method($this[$field], $param, ...) with Reflection + $value = $method->invokeArgs(NULL, $params); + } + } + + // Set the filtered value + $this[$field] = $value; + } + + // Execute the rules + + foreach ($rules as $field => $set) + { + // Get the field value + $value = $this[$field]; + + foreach ($set as $rule => $params) + { + if ( ! in_array($rule, $this->_empty_rules) AND ! Validate::not_empty($value)) + { + // Skip this rule for empty fields + continue; + } + + // Add the field value to the parameters + array_unshift($params, $value); + + if (method_exists($this, $rule)) + { + // Use a method in this object + $method = new ReflectionMethod($this, $rule); + + if ($method->isStatic()) + { + // Call static::$rule($this[$field], $param, ...) with Reflection + $passed = $method->invokeArgs(NULL, $params); + } + else + { + // Do not use Reflection here, the method may be protected + $passed = call_user_func_array(array($this, $rule), $params); + } + } + elseif (strpos($rule, '::') === FALSE) + { + // Use a function call + $function = new ReflectionFunction($rule); + + // Call $function($this[$field], $param, ...) with Reflection + $passed = $function->invokeArgs($params); + } + else + { + // Split the class and method of the rule + list($class, $method) = explode('::', $rule, 2); + + // Use a static method call + $method = new ReflectionMethod($class, $method); + + // Call $Class::$method($this[$field], $param, ...) with Reflection + $passed = $method->invokeArgs(NULL, $params); + } + + if ($passed === FALSE) + { + // Remove the field value from the parameters + array_shift($params); + + // Add the rule to the errors + $this->error($field, $rule, $params); + + // This field has an error, stop executing rules + break; + } + } + } + + // Execute the callbacks + + foreach ($callbacks as $field => $set) + { + if (isset($this->_errors[$field])) + { + // Skip any field that already has an error + continue; + } + + foreach ($set as $callback_array) + { + list($callback, $params) = $callback_array; + + if (is_string($callback) AND strpos($callback, '::') !== FALSE) + { + // Make the static callback into an array + $callback = explode('::', $callback, 2); + } + + if (is_array($callback)) + { + // Separate the object and method + list ($object, $method) = $callback; + + // Use a method in the given object + $method = new ReflectionMethod($object, $method); + + if ( ! is_object($object)) + { + // The object must be NULL for static calls + $object = NULL; + } + + // Call $object->$method($this, $field, $errors) with Reflection + $method->invoke($object, $this, $field, $params); + } + else + { + // Use a function call + $function = new ReflectionFunction($callback); + + // Call $function($this, $field, $errors) with Reflection + $function->invoke($this, $field, $params); + } + + if (isset($this->_errors[$field])) + { + // An error was added, stop processing callbacks + break; + } + } + } + + if (isset($benchmark)) + { + // Stop benchmarking + Profiler::stop($benchmark); + } + + return empty($this->_errors); + } + + /** + * Add an error to a field. + * + * @param string field name + * @param string error message + * @return $this + */ + public function error($field, $error, array $params = NULL) + { + $this->_errors[$field] = array($error, $params); + + return $this; + } + + /** + * Returns the error messages. If no file is specified, the error message + * will be the name of the rule that failed. When a file is specified, the + * message will be loaded from "field/rule", or if no rule-specific message + * exists, "field/default" will be used. If neither is set, the returned + * message will be "file/field/rule". + * + * By default all messages are translated using the default language. + * A string can be used as the second parameter to specified the language + * that the message was written in. + * + * // Get errors from messages/forms/login.php + * $errors = $validate->errors('forms/login'); + * + * @uses Kohana::message + * @param string file to load error messages from + * @param mixed translate the message + * @return array + */ + public function errors($file = NULL, $translate = TRUE) + { + if ($file === NULL) + { + // Return the error list + return $this->_errors; + } + + // Create a new message list + $messages = array(); + + foreach ($this->_errors as $field => $set) + { + list($error, $params) = $set; + + // Get the label for this field + $label = $this->_labels[$field]; + + if ($translate) + { + if (is_string($translate)) + { + // Translate the label using the specified language + $label = __($label, NULL, $translate); + } + else + { + // Translate the label + $label = __($label); + } + } + + // Start the translation values list + $values = array( + ':field' => $label, + ':value' => $this[$field], + ); + + if (is_array($values[':value'])) + { + // All values must be strings + $values[':value'] = implode(', ', Arr::flatten($values[':value'])); + } + + if ($params) + { + foreach ($params as $key => $value) + { + if (is_array($value)) + { + // All values must be strings + $value = implode(', ', Arr::flatten($value)); + } + + // Check if a label for this parameter exists + if (isset($this->_labels[$value])) + { + // Use the label as the value, eg: related field name for "matches" + $value = $this->_labels[$value]; + + if ($translate) + { + if (is_string($translate)) + { + // Translate the value using the specified language + $value = __($value, NULL, $translate); + } + else + { + // Translate the value + $value = __($value); + } + } + } + + // Add each parameter as a numbered value, starting from 1 + $values[':param'.($key + 1)] = $value; + } + } + + if ($message = Kohana::message($file, "{$field}.{$error}")) + { + // Found a message for this field and error + } + elseif ($message = Kohana::message($file, "{$field}.default")) + { + // Found a default message for this field + } + elseif ($message = Kohana::message($file, $error)) + { + // Found a default message for this error + } + elseif ($message = Kohana::message('validate', $error)) + { + // Found a default message for this error + } + else + { + // No message exists, display the path expected + $message = "{$file}.{$field}.{$error}"; + } + + if ($translate) + { + if (is_string($translate)) + { + // Translate the message using specified language + $message = __($message, $values, $translate); + } + else + { + // Translate the message using the default language + $message = __($message, $values); + } + } + else + { + // Do not translate, just replace the values + $message = strtr($message, $values); + } + + // Set the message for this field + $messages[$field] = $message; + } + + return $messages; + } + + /** + * Checks if a field matches the value of another field. + * + * @param string field value + * @param string field name to match + * @return boolean + */ + protected function matches($value, $match) + { + return ($value === $this[$match]); + } + +} // End Validation diff --git a/includes/kohana/system/classes/kohana/validate/exception.php b/includes/kohana/system/classes/kohana/validate/exception.php new file mode 100644 index 0000000..bde9095 --- /dev/null +++ b/includes/kohana/system/classes/kohana/validate/exception.php @@ -0,0 +1,29 @@ +array = $array; + + parent::__construct($message, $values, $code); + } + +} // End Kohana_Validate_Exception diff --git a/includes/kohana/system/classes/kohana/view.php b/includes/kohana/system/classes/kohana/view.php new file mode 100644 index 0000000..1839700 --- /dev/null +++ b/includes/kohana/system/classes/kohana/view.php @@ -0,0 +1,346 @@ + $value) + { + View::$_global_data[$key2] = $value; + } + } + else + { + View::$_global_data[$key] = $value; + } + } + + /** + * Assigns a global variable by reference, similar to [View::bind], except + * that the variable will be accessible to all views. + * + * View::bind_global($key, $value); + * + * @param string variable name + * @param mixed referenced variable + * @return void + */ + public static function bind_global($key, & $value) + { + View::$_global_data[$key] =& $value; + } + + // View filename + protected $_file; + + // Array of local variables + protected $_data = array(); + + /** + * Sets the initial view filename and local data. Views should almost + * always only be created using [View::factory]. + * + * $view = new View($file); + * + * @param string view filename + * @param array array of values + * @return void + * @uses View::set_filename + */ + public function __construct($file = NULL, array $data = NULL) + { + if ($file !== NULL) + { + $this->set_filename($file); + } + + if ($data !== NULL) + { + // Add the values to the current data + $this->_data = $data + $this->_data; + } + } + + /** + * Magic method, searches for the given variable and returns its value. + * Local variables will be returned before global variables. + * + * $value = $view->foo; + * + * [!!] If the variable has not yet been set, an exception will be thrown. + * + * @param string variable name + * @return mixed + * @throws Kohana_Exception + */ + public function & __get($key) + { + if (array_key_exists($key, $this->_data)) + { + return $this->_data[$key]; + } + elseif (array_key_exists($key, View::$_global_data)) + { + return View::$_global_data[$key]; + } + else + { + throw new Kohana_Exception('View variable is not set: :var', + array(':var' => $key)); + } + } + + /** + * Magic method, calls [View::set] with the same parameters. + * + * $view->foo = 'something'; + * + * @param string variable name + * @param mixed value + * @return void + */ + public function __set($key, $value) + { + $this->set($key, $value); + } + + /** + * Magic method, determines if a variable is set. + * + * isset($view->foo); + * + * [!!] `NULL` variables are not considered to be set by [isset](http://php.net/isset). + * + * @param string variable name + * @return boolean + */ + public function __isset($key) + { + return (isset($this->_data[$key]) OR isset(View::$_global_data[$key])); + } + + /** + * Magic method, unsets a given variable. + * + * unset($view->foo); + * + * @param string variable name + * @return void + */ + public function __unset($key) + { + unset($this->_data[$key], View::$_global_data[$key]); + } + + /** + * Magic method, returns the output of [View::render]. + * + * @return string + * @uses View::render + */ + public function __toString() + { + try + { + return $this->render(); + } + catch (Exception $e) + { + // Display the exception message + Kohana::exception_handler($e); + + return ''; + } + } + + /** + * Sets the view filename. + * + * $view->set_filename($file); + * + * @param string view filename + * @return View + * @throws Kohana_View_Exception + */ + public function set_filename($file) + { + if (($path = Kohana::find_file('views', $file)) === FALSE) + { + throw new Kohana_View_Exception('The requested view :file could not be found', array( + ':file' => $file, + )); + } + + // Store the file path locally + $this->_file = $path; + + return $this; + } + + /** + * Assigns a variable by name. Assigned values will be available as a + * variable within the view file: + * + * // This value can be accessed as $foo within the view + * $view->set('foo', 'my value'); + * + * You can also use an array to set several values at once: + * + * // Create the values $food and $beverage in the view + * $view->set(array('food' => 'bread', 'beverage' => 'water')); + * + * @param string variable name or an array of variables + * @param mixed value + * @return $this + */ + public function set($key, $value = NULL) + { + if (is_array($key)) + { + foreach ($key as $name => $value) + { + $this->_data[$name] = $value; + } + } + else + { + $this->_data[$key] = $value; + } + + return $this; + } + + /** + * Assigns a value by reference. The benefit of binding is that values can + * be altered without re-setting them. It is also possible to bind variables + * before they have values. Assigned values will be available as a + * variable within the view file: + * + * // This reference can be accessed as $ref within the view + * $view->bind('ref', $bar); + * + * @param string variable name + * @param mixed referenced variable + * @return $this + */ + public function bind($key, & $value) + { + $this->_data[$key] =& $value; + + return $this; + } + + /** + * Renders the view object to a string. Global and local data are merged + * and extracted to create local variables within the view file. + * + * $output = $view->render(); + * + * [!!] Global variables with the same key name as local variables will be + * overwritten by the local variable. + * + * @param string view filename + * @return string + * @throws Kohana_View_Exception + * @uses View::capture + */ + public function render($file = NULL) + { + if ($file !== NULL) + { + $this->set_filename($file); + } + + if (empty($this->_file)) + { + throw new Kohana_View_Exception('You must set the file to use within your view before rendering'); + } + + // Combine local and global data and capture the output + return View::capture($this->_file, $this->_data); + } + +} // End View diff --git a/includes/kohana/system/classes/kohana/view/exception.php b/includes/kohana/system/classes/kohana/view/exception.php new file mode 100644 index 0000000..a83ba4e --- /dev/null +++ b/includes/kohana/system/classes/kohana/view/exception.php @@ -0,0 +1,9 @@ + array( + 'length' => '13,14,15,16,17,18,19', + 'prefix' => '', + 'luhn' => TRUE, + ), + + 'american express' => array( + 'length' => '15', + 'prefix' => '3[47]', + 'luhn' => TRUE, + ), + + 'diners club' => array( + 'length' => '14,16', + 'prefix' => '36|55|30[0-5]', + 'luhn' => TRUE, + ), + + 'discover' => array( + 'length' => '16', + 'prefix' => '6(?:5|011)', + 'luhn' => TRUE, + ), + + 'jcb' => array( + 'length' => '15,16', + 'prefix' => '3|1800|2131', + 'luhn' => TRUE, + ), + + 'maestro' => array( + 'length' => '16,18', + 'prefix' => '50(?:20|38)|6(?:304|759)', + 'luhn' => TRUE, + ), + + 'mastercard' => array( + 'length' => '16', + 'prefix' => '5[1-5]', + 'luhn' => TRUE, + ), + + 'visa' => array( + 'length' => '13,16', + 'prefix' => '4', + 'luhn' => TRUE, + ), + +); \ No newline at end of file diff --git a/includes/kohana/system/config/encrypt.php b/includes/kohana/system/config/encrypt.php new file mode 100644 index 0000000..ae9126a --- /dev/null +++ b/includes/kohana/system/config/encrypt.php @@ -0,0 +1,17 @@ + array( + /** + * The following options must be set: + * + * string key secret passphrase + * integer mode encryption mode, one of MCRYPT_MODE_* + * integer cipher encryption cipher, one of the Mcrpyt cipher constants + */ + 'cipher' => MCRYPT_RIJNDAEL_128, + 'mode' => MCRYPT_MODE_NOFB, + ), + +); diff --git a/includes/kohana/system/config/inflector.php b/includes/kohana/system/config/inflector.php new file mode 100644 index 0000000..f54bb50 --- /dev/null +++ b/includes/kohana/system/config/inflector.php @@ -0,0 +1,65 @@ + array( + 'access', + 'advice', + 'art', + 'baggage', + 'dances', + 'equipment', + 'fish', + 'fuel', + 'furniture', + 'heat', + 'honey', + 'homework', + 'impatience', + 'information', + 'knowledge', + 'luggage', + 'media', + 'money', + 'music', + 'news', + 'patience', + 'progress', + 'pollution', + 'research', + 'rice', + 'sand', + 'series', + 'sheep', + 'sms', + 'spam', + 'species', + 'staff', + 'toothpaste', + 'traffic', + 'understanding', + 'water', + 'weather', + 'work', + ), + + 'irregular' => array( + 'child' => 'children', + 'clothes' => 'clothing', + 'man' => 'men', + 'movie' => 'movies', + 'person' => 'people', + 'woman' => 'women', + 'mouse' => 'mice', + 'goose' => 'geese', + 'ox' => 'oxen', + 'leaf' => 'leaves', + 'course' => 'courses', + 'size' => 'sizes', + 'was' => 'were', + 'is' => 'are', + 'verse' => 'verses', + 'hero' => 'heroes', + 'purchase' => 'purchases', + ), +); diff --git a/includes/kohana/system/config/mimes.php b/includes/kohana/system/config/mimes.php new file mode 100644 index 0000000..e63a9ca --- /dev/null +++ b/includes/kohana/system/config/mimes.php @@ -0,0 +1,225 @@ + array('text/h323'), + '7z' => array('application/x-7z-compressed'), + 'abw' => array('application/x-abiword'), + 'acx' => array('application/internet-property-stream'), + 'ai' => array('application/postscript'), + 'aif' => array('audio/x-aiff'), + 'aifc' => array('audio/x-aiff'), + 'aiff' => array('audio/x-aiff'), + 'asf' => array('video/x-ms-asf'), + 'asr' => array('video/x-ms-asf'), + 'asx' => array('video/x-ms-asf'), + 'atom' => array('application/atom+xml'), + 'avi' => array('video/avi', 'video/msvideo', 'video/x-msvideo'), + 'bin' => array('application/octet-stream','application/macbinary'), + 'bmp' => array('image/bmp'), + 'c' => array('text/x-csrc'), + 'c++' => array('text/x-c++src'), + 'cab' => array('application/x-cab'), + 'cc' => array('text/x-c++src'), + 'cda' => array('application/x-cdf'), + 'class' => array('application/octet-stream'), + 'cpp' => array('text/x-c++src'), + 'cpt' => array('application/mac-compactpro'), + 'csh' => array('text/x-csh'), + 'css' => array('text/css'), + 'csv' => array('text/x-comma-separated-values', 'application/vnd.ms-excel', 'text/comma-separated-values', 'text/csv'), + 'dbk' => array('application/docbook+xml'), + 'dcr' => array('application/x-director'), + 'deb' => array('application/x-debian-package'), + 'diff' => array('text/x-diff'), + 'dir' => array('application/x-director'), + 'divx' => array('video/divx'), + 'dll' => array('application/octet-stream', 'application/x-msdos-program'), + 'dmg' => array('application/x-apple-diskimage'), + 'dms' => array('application/octet-stream'), + 'doc' => array('application/msword'), + 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document'), + 'dvi' => array('application/x-dvi'), + 'dxr' => array('application/x-director'), + 'eml' => array('message/rfc822'), + 'eps' => array('application/postscript'), + 'evy' => array('application/envoy'), + 'exe' => array('application/x-msdos-program', 'application/octet-stream'), + 'fla' => array('application/octet-stream'), + 'flac' => array('application/x-flac'), + 'flc' => array('video/flc'), + 'fli' => array('video/fli'), + 'flv' => array('video/x-flv'), + 'gif' => array('image/gif'), + 'gtar' => array('application/x-gtar'), + 'gz' => array('application/x-gzip'), + 'h' => array('text/x-chdr'), + 'h++' => array('text/x-c++hdr'), + 'hh' => array('text/x-c++hdr'), + 'hpp' => array('text/x-c++hdr'), + 'hqx' => array('application/mac-binhex40'), + 'hs' => array('text/x-haskell'), + 'htm' => array('text/html'), + 'html' => array('text/html'), + 'ico' => array('image/x-icon'), + 'ics' => array('text/calendar'), + 'iii' => array('application/x-iphone'), + 'ins' => array('application/x-internet-signup'), + 'iso' => array('application/x-iso9660-image'), + 'isp' => array('application/x-internet-signup'), + 'jar' => array('application/java-archive'), + 'java' => array('application/x-java-applet'), + 'jpe' => array('image/jpeg', 'image/pjpeg'), + 'jpeg' => array('image/jpeg', 'image/pjpeg'), + 'jpg' => array('image/jpeg', 'image/pjpeg'), + 'js' => array('application/x-javascript'), + 'json' => array('application/json'), + 'latex' => array('application/x-latex'), + 'lha' => array('application/octet-stream'), + 'log' => array('text/plain', 'text/x-log'), + 'lzh' => array('application/octet-stream'), + 'm4a' => array('audio/mpeg'), + 'm4p' => array('video/mp4v-es'), + 'm4v' => array('video/mp4'), + 'man' => array('application/x-troff-man'), + 'mdb' => array('application/x-msaccess'), + 'midi' => array('audio/midi'), + 'mid' => array('audio/midi'), + 'mif' => array('application/vnd.mif'), + 'mka' => array('audio/x-matroska'), + 'mkv' => array('video/x-matroska'), + 'mov' => array('video/quicktime'), + 'movie' => array('video/x-sgi-movie'), + 'mp2' => array('audio/mpeg'), + 'mp3' => array('audio/mpeg'), + 'mp4' => array('application/mp4','audio/mp4','video/mp4'), + 'mpa' => array('video/mpeg'), + 'mpe' => array('video/mpeg'), + 'mpeg' => array('video/mpeg'), + 'mpg' => array('video/mpeg'), + 'mpg4' => array('video/mp4'), + 'mpga' => array('audio/mpeg'), + 'mpp' => array('application/vnd.ms-project'), + 'mpv' => array('video/x-matroska'), + 'mpv2' => array('video/mpeg'), + 'ms' => array('application/x-troff-ms'), + 'msg' => array('application/msoutlook','application/x-msg'), + 'msi' => array('application/x-msi'), + 'nws' => array('message/rfc822'), + 'oda' => array('application/oda'), + 'odb' => array('application/vnd.oasis.opendocument.database'), + 'odc' => array('application/vnd.oasis.opendocument.chart'), + 'odf' => array('application/vnd.oasis.opendocument.forumla'), + 'odg' => array('application/vnd.oasis.opendocument.graphics'), + 'odi' => array('application/vnd.oasis.opendocument.image'), + 'odm' => array('application/vnd.oasis.opendocument.text-master'), + 'odp' => array('application/vnd.oasis.opendocument.presentation'), + 'ods' => array('application/vnd.oasis.opendocument.spreadsheet'), + 'odt' => array('application/vnd.oasis.opendocument.text'), + 'oga' => array('audio/ogg'), + 'ogg' => array('application/ogg'), + 'ogv' => array('video/ogg'), + 'otg' => array('application/vnd.oasis.opendocument.graphics-template'), + 'oth' => array('application/vnd.oasis.opendocument.web'), + 'otp' => array('application/vnd.oasis.opendocument.presentation-template'), + 'ots' => array('application/vnd.oasis.opendocument.spreadsheet-template'), + 'ott' => array('application/vnd.oasis.opendocument.template'), + 'p' => array('text/x-pascal'), + 'pas' => array('text/x-pascal'), + 'patch' => array('text/x-diff'), + 'pbm' => array('image/x-portable-bitmap'), + 'pdf' => array('application/pdf', 'application/x-download'), + 'php' => array('application/x-httpd-php'), + 'php3' => array('application/x-httpd-php'), + 'php4' => array('application/x-httpd-php'), + 'php5' => array('application/x-httpd-php'), + 'phps' => array('application/x-httpd-php-source'), + 'phtml' => array('application/x-httpd-php'), + 'pl' => array('text/x-perl'), + 'pm' => array('text/x-perl'), + 'png' => array('image/png', 'image/x-png'), + 'po' => array('text/x-gettext-translation'), + 'pot' => array('application/vnd.ms-powerpoint'), + 'pps' => array('application/vnd.ms-powerpoint'), + 'ppt' => array('application/powerpoint'), + 'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation'), + 'ps' => array('application/postscript'), + 'psd' => array('application/x-photoshop', 'image/x-photoshop'), + 'pub' => array('application/x-mspublisher'), + 'py' => array('text/x-python'), + 'qt' => array('video/quicktime'), + 'ra' => array('audio/x-realaudio'), + 'ram' => array('audio/x-realaudio', 'audio/x-pn-realaudio'), + 'rar' => array('application/rar'), + 'rgb' => array('image/x-rgb'), + 'rm' => array('audio/x-pn-realaudio'), + 'rpm' => array('audio/x-pn-realaudio-plugin', 'application/x-redhat-package-manager'), + 'rss' => array('application/rss+xml'), + 'rtf' => array('text/rtf'), + 'rtx' => array('text/richtext'), + 'rv' => array('video/vnd.rn-realvideo'), + 'sea' => array('application/octet-stream'), + 'sh' => array('text/x-sh'), + 'shtml' => array('text/html'), + 'sit' => array('application/x-stuffit'), + 'smi' => array('application/smil'), + 'smil' => array('application/smil'), + 'so' => array('application/octet-stream'), + 'src' => array('application/x-wais-source'), + 'svg' => array('image/svg+xml'), + 'swf' => array('application/x-shockwave-flash'), + 't' => array('application/x-troff'), + 'tar' => array('application/x-tar'), + 'tcl' => array('text/x-tcl'), + 'tex' => array('application/x-tex'), + 'text' => array('text/plain'), + 'texti' => array('application/x-texinfo'), + 'textinfo' => array('application/x-texinfo'), + 'tgz' => array('application/x-tar'), + 'tif' => array('image/tiff'), + 'tiff' => array('image/tiff'), + 'torrent' => array('application/x-bittorrent'), + 'tr' => array('application/x-troff'), + 'tsv' => array('text/tab-separated-values'), + 'txt' => array('text/plain'), + 'wav' => array('audio/x-wav'), + 'wax' => array('audio/x-ms-wax'), + 'wbxml' => array('application/wbxml'), + 'wm' => array('video/x-ms-wm'), + 'wma' => array('audio/x-ms-wma'), + 'wmd' => array('application/x-ms-wmd'), + 'wmlc' => array('application/wmlc'), + 'wmv' => array('video/x-ms-wmv', 'application/octet-stream'), + 'wmx' => array('video/x-ms-wmx'), + 'wmz' => array('application/x-ms-wmz'), + 'word' => array('application/msword', 'application/octet-stream'), + 'wp5' => array('application/wordperfect5.1'), + 'wpd' => array('application/vnd.wordperfect'), + 'wvx' => array('video/x-ms-wvx'), + 'xbm' => array('image/x-xbitmap'), + 'xcf' => array('image/xcf'), + 'xhtml' => array('application/xhtml+xml'), + 'xht' => array('application/xhtml+xml'), + 'xl' => array('application/excel', 'application/vnd.ms-excel'), + 'xla' => array('application/excel', 'application/vnd.ms-excel'), + 'xlc' => array('application/excel', 'application/vnd.ms-excel'), + 'xlm' => array('application/excel', 'application/vnd.ms-excel'), + 'xls' => array('application/excel', 'application/vnd.ms-excel'), + 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'), + 'xlt' => array('application/excel', 'application/vnd.ms-excel'), + 'xml' => array('text/xml', 'application/xml'), + 'xof' => array('x-world/x-vrml'), + 'xpm' => array('image/x-xpixmap'), + 'xsl' => array('text/xml'), + 'xvid' => array('video/x-xvid'), + 'xwd' => array('image/x-xwindowdump'), + 'z' => array('application/x-compress'), + 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed') +); diff --git a/includes/kohana/system/config/session.php b/includes/kohana/system/config/session.php new file mode 100644 index 0000000..78ac9fa --- /dev/null +++ b/includes/kohana/system/config/session.php @@ -0,0 +1,7 @@ + array( + 'encrypted' => FALSE, + ), +); diff --git a/includes/kohana/system/config/user_agents.php b/includes/kohana/system/config/user_agents.php new file mode 100644 index 0000000..5753c23 --- /dev/null +++ b/includes/kohana/system/config/user_agents.php @@ -0,0 +1,104 @@ + array( + 'windows nt 6.1' => 'Windows 7', + 'windows nt 6.0' => 'Windows Vista', + 'windows nt 5.2' => 'Windows 2003', + 'windows nt 5.1' => 'Windows XP', + 'windows nt 5.0' => 'Windows 2000', + 'windows nt 4.0' => 'Windows NT', + 'winnt4.0' => 'Windows NT', + 'winnt 4.0' => 'Windows NT', + 'winnt' => 'Windows NT', + 'windows 98' => 'Windows 98', + 'win98' => 'Windows 98', + 'windows 95' => 'Windows 95', + 'win95' => 'Windows 95', + 'windows' => 'Unknown Windows OS', + 'os x' => 'Mac OS X', + 'intel mac' => 'Intel Mac', + 'ppc mac' => 'PowerPC Mac', + 'powerpc' => 'PowerPC', + 'ppc' => 'PowerPC', + 'cygwin' => 'Cygwin', + 'linux' => 'Linux', + 'debian' => 'Debian', + 'openvms' => 'OpenVMS', + 'sunos' => 'Sun Solaris', + 'amiga' => 'Amiga', + 'beos' => 'BeOS', + 'apachebench' => 'ApacheBench', + 'freebsd' => 'FreeBSD', + 'netbsd' => 'NetBSD', + 'bsdi' => 'BSDi', + 'openbsd' => 'OpenBSD', + 'os/2' => 'OS/2', + 'warp' => 'OS/2', + 'aix' => 'AIX', + 'irix' => 'Irix', + 'osf' => 'DEC OSF', + 'hp-ux' => 'HP-UX', + 'hurd' => 'GNU/Hurd', + 'unix' => 'Unknown Unix OS', + ), + + 'browser' => array( + 'Opera' => 'Opera', + 'MSIE' => 'Internet Explorer', + 'Internet Explorer' => 'Internet Explorer', + 'Shiira' => 'Shiira', + 'Firefox' => 'Firefox', + 'Chimera' => 'Chimera', + 'Phoenix' => 'Phoenix', + 'Firebird' => 'Firebird', + 'Camino' => 'Camino', + 'Navigator' => 'Netscape', + 'Netscape' => 'Netscape', + 'OmniWeb' => 'OmniWeb', + 'Chrome' => 'Chrome', + 'Safari' => 'Safari', + 'CFNetwork' => 'Safari', // Core Foundation for OSX, WebKit/Safari + 'Konqueror' => 'Konqueror', + 'Epiphany' => 'Epiphany', + 'Galeon' => 'Galeon', + 'Mozilla' => 'Mozilla', + 'icab' => 'iCab', + 'lynx' => 'Lynx', + 'links' => 'Links', + 'hotjava' => 'HotJava', + 'amaya' => 'Amaya', + 'IBrowse' => 'IBrowse', + ), + + 'mobile' => array( + 'mobileexplorer' => 'Mobile Explorer', + 'openwave' => 'Open Wave', + 'opera mini' => 'Opera Mini', + 'operamini' => 'Opera Mini', + 'elaine' => 'Palm', + 'palmsource' => 'Palm', + 'digital paths' => 'Palm', + 'avantgo' => 'Avantgo', + 'xiino' => 'Xiino', + 'palmscape' => 'Palmscape', + 'nokia' => 'Nokia', + 'ericsson' => 'Ericsson', + 'blackBerry' => 'BlackBerry', + 'motorola' => 'Motorola', + 'iphone' => 'iPhone', + 'android' => 'Android', + ), + + 'robot' => array( + 'googlebot' => 'Googlebot', + 'msnbot' => 'MSNBot', + 'slurp' => 'Inktomi Slurp', + 'yahoo' => 'Yahoo', + 'askjeeves' => 'AskJeeves', + 'fastcrawler' => 'FastCrawler', + 'infoseek' => 'InfoSeek Robot 1.0', + 'lycos' => 'Lycos', + ), +); diff --git a/includes/kohana/system/config/userguide.php b/includes/kohana/system/config/userguide.php new file mode 100644 index 0000000..3c49362 --- /dev/null +++ b/includes/kohana/system/config/userguide.php @@ -0,0 +1,23 @@ + array( + + // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' + 'kohana' => array( + + // Whether this modules userguide pages should be shown + 'enabled' => TRUE, + + // The name that should show up on the userguide index page + 'name' => 'Kohana', + + // A short description of this module, shown on the index page + 'description' => 'Documentation for Kohana core/system.', + + // Copyright message, shown in the footer for this module + 'copyright' => '© 2008–2010 Kohana Team', + ) + ) +); \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/autoloading.md b/includes/kohana/system/guide/kohana/autoloading.md new file mode 100644 index 0000000..def15bc --- /dev/null +++ b/includes/kohana/system/guide/kohana/autoloading.md @@ -0,0 +1,69 @@ +# Loading Classes + +Kohana takes advantage of PHP [autoloading](http://php.net/manual/language.oop5.autoload.php). This removes the need to call [include](http://php.net/include) or [require](http://php.net/require) before using a class. When you use a class Kohana will find and include the class file for you. For instance, when you want to use the [Cookie::set] method, you simply call: + + Cookie::set('mycookie', 'any string value'); + +Or to load an [Encrypt] instance, just call [Encrypt::instance]: + + $encrypt = Encrypt::instance(); + +Classes are loaded via the [Kohana::auto_load] method, which makes a simple conversion from class name to file name: + +1. Classes are placed in the `classes/` directory of the [filesystem](files) +2. Any underscore characters in the class name are converted to slashes +2. The filename is lowercase + +When calling a class that has not been loaded (eg: `Session_Cookie`), Kohana will search the filesystem using [Kohana::find_file] for a file named `classes/session/cookie.php`. + +If your classes do not follow this convention, they cannot be autoloaded by Kohana. You will have to manually included your files, or add your own [autoload function.](http://us3.php.net/manual/en/function.spl-autoload-register.php) + +## Custom Autoloaders + +Kohana's default autoloader is enabled in `application/bootstrap.php` using [spl_autoload_register](http://php.net/spl_autoload_register): + + spl_autoload_register(array('Kohana', 'auto_load')); + +This allows [Kohana::auto_load] to attempt to find and include any class that does not yet exist when the class is first used. + +### Example: Zend + +You can easily gain access to other libraries if they include an autoloader. For example, here is how to enable Zend's autoloader so you can use Zend libraries in your Kohana application. + +#### Download and install the Zend Framework files + +- [Download the latest Zend Framework files](http://framework.zend.com/download/latest). +- Create a `vendor` directory at `application/vendor`. This keeps third party software separate from your application classes. +- Move the decompressed Zend folder containing Zend Framework to `application/vendor/Zend`. + + +#### Include Zend's Autoloader in your bootstrap + +Somewhere in `application/bootstrap.php`, copy the following code: + + /** + * Enable Zend Framework autoloading + */ + if ($path = Kohana::find_file('vendor', 'Zend/Loader')) + { + ini_set('include_path', + ini_get('include_path').PATH_SEPARATOR.dirname(dirname($path))); + + require_once 'Zend/Loader/Autoloader.php'; + Zend_Loader_Autoloader::getInstance(); + } + +#### Usage example + +You can now autoload any Zend Framework classes from inside your Kohana application. + + if ($validate($_POST)) + { + $mailer = new Zend_Mail; + + $mailer->setBodyHtml($view) + ->setFrom(Kohana::config('site')->email_from) + ->addTo($email) + ->setSubject($message) + ->send(); + } \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/bootstrap.md b/includes/kohana/system/guide/kohana/bootstrap.md new file mode 100644 index 0000000..6ff9588 --- /dev/null +++ b/includes/kohana/system/guide/kohana/bootstrap.md @@ -0,0 +1,164 @@ +# Bootstrap + +The bootstrap is located at `application/bootstrap.php`. It is responsible for setting up the Kohana environment and executing the main response. It is included by `index.php` (see [Request flow](flow)) + +[!!] The bootstrap is responsible for the flow of your application. In previous versions of Kohana the bootstrap was in `system` and was somewhat of an unseen, uneditible force. In Kohana 3 the bootstrap takes on a much more integral and versatile role. Do not be afraid to edit and change your bootstrap however you see fit. + +## Environment setup + +First the bootstrap sets the timezone and the locale, and adds Kohana's autoloader so the [cascading filesystem](files) works. You could add any other settings that all your application needed here. + +~~~ +// Sample excerpt from bootstrap.php with comments trimmed down + +// Set the default time zone. +date_default_timezone_set('America/Chicago'); + +// Set the default locale. +setlocale(LC_ALL, 'en_US.utf-8'); + +// Enable the Kohana auto-loader. +spl_autoload_register(array('Kohana', 'auto_load')); + +// Enable the Kohana auto-loader for unserialization. +ini_set('unserialize_callback_func', 'spl_autoload_call'); +~~~ + +## Initilization and Configuration + +Kohana is then initialized by calling [Kohana::init], and the log and [config](files/config) reader/writers are enabled. + +~~~ +// Sample excerpt from bootstrap.php with comments trimmed down + +Kohana::init(array(' + base_url' => '/kohana/', + index_file => false, +)); + +// Attach the file writer to logging. Multiple writers are supported. +Kohana::$log->attach(new Kohana_Log_File(APPPATH.'logs')); + +// Attach a file reader to config. Multiple readers are supported. +Kohana::$config->attach(new Kohana_Config_File); +~~~ + +You can add conditional statements to make the bootstrap have different values based on certain settings. For example, detect whether we are live by checking `$_SERVER['HTTP_HOST']` and set caching, profiling, etc. accordingly. This is just an example, there are many different ways to accomplish the same thing. + +~~~ +// Excerpt from http://github.com/isaiahdw/kohanaphp.com/blob/f2afe8e28b/application/bootstrap.php +... [trimmed] + +/** + * Set the environment status by the domain. + */ +if (strpos($_SERVER['HTTP_HOST'], 'kohanaphp.com') !== FALSE) +{ + // We are live! + Kohana::$environment = Kohana::PRODUCTION; + + // Turn off notices and strict errors + error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT); +} + +/** + * Initialize Kohana, setting the default options. + ... [trimmed] + */ +Kohana::init(array( + 'base_url' => Kohana::$environment === Kohana::PRODUCTION ? '/' : '/kohanaphp.com/', + 'caching' => Kohana::$environment === Kohana::PRODUCTION, + 'profile' => Kohana::$environment !== Kohana::PRODUCTION, + 'index_file' => FALSE, +)); + +... [trimmed] + +try +{ + $request = Request::instance()->execute(); +} +catch (Exception $e) +{ + // If we are in development and the error wasn't a 404, show the stack trace. + if ( Kohana::$environment == "development" AND $e->getCode() != 404 ) + { + throw $e; + } +...[trimmed] +~~~ + +[!!] Note: The default bootstrap will set `Kohana::$environment = $_ENV['KOHANA_ENV']` if set. Docs on how to supply this variable are available in your web server's documentation (e.g. [Apache](http://httpd.apache.org/docs/1.3/mod/mod_env.html#setenv), [Lighttpd](http://redmine.lighttpd.net/wiki/1/Docs:ModSetEnv#Options)). This is considered better practice than many alternative methods to set `Kohana::$enviroment`, as you can change the setting per server, without having to rely on config options or hostnames. + +## Modules + +**Read the [Modules](modules) page for a more detailed description.** + +[Modules](modules) are then loaded using [Kohana::modules()]. Including modules is optional. + +Each key in the array should be the name of the module, and the value is the path to the module, either relative or absolute. +~~~ +// Example excerpt from bootstrap.php + +Kohana::modules(array( + 'database' => MODPATH.'database', + 'orm' => MODPATH.'orm', + 'userguide' => MODPATH.'userguide', +)); +~~~ + +## Routes + +**Read the [Routing](routing) page for a more detailed description and more examples.** + +[Routes](routing) are then defined via [Route::set()]. + +~~~ +// The default route that comes with Kohana 3 +Route::set('default', '((/(/)))') + ->defaults(array( + 'controller' => 'welcome', + 'action' => 'index', + )); +~~~ + +## Execution + +Once our environment is initialized and routes defined, it's time to execute our application. This area of the bootstrap is very flexible. Do not be afraid to change this around to whatever suits your needs. + +### Basic Example +The most simple way to do this, and what comes default with Kohana 3 is simply: +~~~ +// Execute the main request +echo Request::instance() + ->execute() + ->send_headers() + ->response; +~~~ + +### Catching Exceptions + +**See [Error Handling](errors) for a more detailed description and more examples.** + +The previous example provides no error catching, which means if an error occurs a stack trace would be shown which could show sensitive info, as well as be unfriendly for the user. One way to solve this is to add a `try catch` block. If we get an exception, we will show the view located at `views/errors/404.php`. **Note: Because we catch the exception, Kohana will not log the error! It is your responsibility to log the error.** + +~~~ +try +{ + // Execute the main request + $request = Request::instance()->execute(); +} +catch (Exception $e) +{ + // Be sure to log the error + Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e)); + + // If there was an error, send a 404 response and display an error + $request->status = 404; + $request->response = View::factory('errors/404'); +} + +// Send the headers and echo the response +$request->send_headers(); +echo $request->response; +~~~ \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/controllers.md b/includes/kohana/system/guide/kohana/controllers.md new file mode 100644 index 0000000..d95d98a --- /dev/null +++ b/includes/kohana/system/guide/kohana/controllers.md @@ -0,0 +1 @@ +This will discuss controller basics, like before() and after(), private function, and about extending controllers like the Controller_Template, or using a parent::before() for authentication. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/conventions.md b/includes/kohana/system/guide/kohana/conventions.md new file mode 100644 index 0000000..e047746 --- /dev/null +++ b/includes/kohana/system/guide/kohana/conventions.md @@ -0,0 +1,306 @@ +# Conventions and Coding Style + +It is encouraged that you follow Kohana's [coding style](http://dev.kohanaframework.org/wiki/kohana2/CodingStyle). This makes code more readable and allows for easier code sharing and contributing. + +## Class Names and File Location + +Class names in Kohana follow a strict convention to facilitate [autoloading](autoloading). Class names should have uppercase first letters with underscores to separate words. Underscores are significant as they directly reflect the file location in the filesystem. + +The following conventions apply: + +1. CamelCased class names should not be used, except when it is undesirable to create a new directory level. +2. All class file names and directory names are lowercase. +3. All classes should be in the `classes` directory. This may be at any level in the [cascading filesystem](files). + +[!!] Unlike Kohana v2.x, there is no separation between "controllers", "models", "libraries" and "helpers". All classes are placed in the "classes/" directory, regardless if they are static "helpers" or object "libraries". You can use whatever kind of class design you want: static, singleton, adapter, etc. + +### Examples {#class-name-examples} + +Remember that in a class, an underscore means a new directory. Consider the following examples: + +Class Name | File Path +----------------------|------------------------------- +Controller_Template | classes/controller/template.php +Model_User | classes/model/user.php +Database | classes/database.php +Database_Query | classes/database/query.php +Form | classes/form.php + +## Coding Standards + +In order to produce highly consistent source code, we ask that everyone follow the coding standards as closely as possible. + +### Brackets +Please use [BSD/Allman Style](http://en.wikipedia.org/wiki/Indent_style#BSD.2FAllman_style) bracketing. Brackets are always on their own line. The exception to this rule is the opening bracket for a class, which can be on the same line. + + if ($foo == 'bar') + { + $baz->bar(); + } + else + { + $baz->default(); + } + + // The opening bracket for a class can be on the same line + Class Foobar { + + +### Naming Conventions + +Kohana uses under_score naming, not camelCase naming. + +#### Classes + + // Controller class, uses Controller_ prefix + class Controller_Apple extends Controller { + + // Model class, uses Model_ prefix + class Model_Cheese extends Model { + + // Regular class + class Peanut { + +When creating an instance of a class, don't use parentheses if you're not passing something on to the constructor: + + // Correct: + $db = new Database; + + // Incorrect: + $db = new Database(); + +#### Functions and Methods + +Functions should be all lowercase, and use under_scores to separate words: + + function drink_beverage($beverage) + { + +#### Variables + +All variables should be lowercase and use under_score, not camelCase: + + // Correct: + $foo = 'bar'; + $long_example = 'uses underscores'; + + // Incorrect: + $weDontWantThis = 'understood?'; + +### Indentation + +You must use tabs to indent your code. Using spaces for tabbing is strictly forbidden. + +Vertical spacing (for multi-line) is done with spaces. Tabs are not good for vertical alignment because different people have different tab widths. + + $text = 'this is a long text block that is wrapped. Normally, we aim for ' + .'wrapping at 80 chars. Vertical alignment is very important for ' + .'code readability. Remember that all indentation is done with tabs,' + .'but vertical alignment should be completed with spaces, after ' + .'indenting with tabs.'; + +### String concatenation + +Do not put spaces around the concatenation operator: + + // Correct: + $str = 'one'.$var.'two'; + + // Incorrect: + $str = 'one'. $var .'two'; + $str = 'one' . $var . 'two'; + +### Single Line Statements + +Single-line IF statements should only be used when breaking normal execution (e.g. return or continue): + + // Acceptable: + if ($foo == $bar) + return $foo; + + if ($foo == $bar) + continue; + + if ($foo == $bar) + break; + + if ($foo == $bar) + throw new Exception('You screwed up!'); + + // Not acceptable: + if ($baz == $bun) + $baz = $bar + 2; + +### Comparison Operations + +Please use OR and AND for comparison: + + // Correct: + if (($foo AND $bar) OR ($b AND $c)) + + // Incorrect: + if (($foo && $bar) || ($b && $c)) + +Please use elseif, not else if: + + // Correct: + elseif ($bar) + + // Incorrect: + else if($bar) + +### Switch structures + +Each case, break and default should be on a separate line. The block inside a case or default must be indented by 1 tab. + + switch ($var) + { + case 'bar': + case 'foo': + echo 'hello'; + break; + case 1: + echo 'one'; + break; + default: + echo 'bye'; + break; + } + +### Parentheses + +There should be one space after statement name, followed by a parenthesis. The ! (bang) character must have a space on either side to ensure maximum readability. Except in the case of a bang or type casting, there should be no whitespace after an opening parenthesis or before a closing parenthesis. + + // Correct: + if ($foo == $bar) + if ( ! $foo) + + // Incorrect: + if($foo == $bar) + if(!$foo) + if ((int) $foo) + if ( $foo == $bar ) + if (! $foo) + +### Ternaries + +All ternary operations should follow a standard format. Use parentheses around expressions only, not around just variables. + + $foo = ($bar == $foo) ? $foo : $bar; + $foo = $bar ? $foo : $bar; + +All comparisons and operations must be done inside of a parentheses group: + + $foo = ($bar > 5) ? ($bar + $foo) : strlen($bar); + +When separating complex ternaries (ternaries where the first part goes beyond ~80 chars) into multiple lines, spaces should be used to line up operators, which should be at the front of the successive lines: + + $foo = ($bar == $foo) + ? $foo + : $bar; + +### Type Casting + +Type casting should be done with spaces on each side of the cast: + + // Correct: + $foo = (string) $bar; + if ( (string) $bar) + + // Incorrect: + $foo = (string)$bar; + +When possible, please use type casting instead of ternary operations: + + // Correct: + $foo = (bool) $bar; + + // Incorrect: + $foo = ($bar == TRUE) ? TRUE : FALSE; + +When casting type to integer or boolean, use the short format: + + // Correct: + $foo = (int) $bar; + $foo = (bool) $bar; + + // Incorrect: + $foo = (integer) $bar; + $foo = (boolean) $bar; + +### Constants + +Always use uppercase for constants: + + // Correct: + define('MY_CONSTANT', 'my_value'); + $a = TRUE; + $b = NULL; + + // Incorrect: + define('MyConstant', 'my_value'); + $a = True; + $b = null; + +Place constant comparisons at the end of tests: + + // Correct: + if ($foo !== FALSE) + + // Incorrect: + if (FALSE !== $foo) + +This is a slightly controversial choice, so I will explain the reasoning. If we were to write the previous example in plain English, the correct example would read: + + if variable $foo is not exactly FALSE + +And the incorrect example would read: + + if FALSE is not exactly variable $foo + +Since we are reading left to right, it simply doesn't make sense to put the constant first. + +### Comments + +#### One-line comments + +Use //, preferably above the line of code you're commenting on. Leave a space after it and start with a capital. Never use #. + + // Correct + + //Incorrect + // incorrect + # Incorrect + +### Regular expressions + +When coding regular expressions please use PCRE rather than the POSIX flavor. PCRE is considered more powerful and faster. + + // Correct: + if (preg_match('/abc/i'), $str) + + // Incorrect: + if (eregi('abc', $str)) + +Use single quotes around your regular expressions rather than double quotes. Single-quoted strings are more convenient because of their simplicity. Unlike double-quoted strings they don't support variable interpolation nor integrated backslash sequences like \n or \t, etc. + + // Correct: + preg_match('/abc/', $str); + + // Incorrect: + preg_match("/abc/", $str); + +When performing a regular expression search and replace, please use the $n notation for backreferences. This is preferred over \\n. + + // Correct: + preg_replace('/(\d+) dollar/', '$1 euro', $str); + + // Incorrect: + preg_replace('/(\d+) dollar/', '\\1 euro', $str); + +Finally, please note that the $ character for matching the position at the end of the line allows for a following newline character. Use the D modifier to fix this if needed. [More info](http://blog.php-security.org/archives/76-Holes-in-most-preg_match-filters.html). + + $str = "email@example.com\n"; + + preg_match('/^.+@.+$/', $str); // TRUE + preg_match('/^.+@.+$/D', $str); // FALSE \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/cookies.md b/includes/kohana/system/guide/kohana/cookies.md new file mode 100644 index 0000000..5b5a310 --- /dev/null +++ b/includes/kohana/system/guide/kohana/cookies.md @@ -0,0 +1,89 @@ +# Cookies + +Kohana provides classes that make it easy to work with both cookies and sessions. At a high level both sessions and cookies provide the same functionality. They allow the developer to store temporary or persistent information about a specific client for later retrieval, usually to make something persistent between requests. + +[Cookies](http://en.wikipedia.org/wiki/HTTP_cookie) should be used for storing non-private data that is persistent for a long period of time. For example storing a user preference or a language setting. Use the [Cookie] class for getting and setting cookies. + +[!!] Kohana uses "signed" cookies. Every cookie that is stored is combined with a secure hash to prevent modification of the cookie. If a cookie is modified outside of Kohana the hash will be incorrect and the cookie will be deleted. This hash is generated using [Cookie::salt()], which uses the [Cookie::$salt] property. You should change this setting when your application is live. + +Nothing stops you from using `$_COOKIE` like normal, but you can not mix using the Cookie class and the regular `$_COOKIE` global, because the hash that Kohana uses to sign cookies will not be present, and Kohana will delete the cookie. + +## Storing, Retrieving, and Deleting Data + +[Cookie] and [Session] provide a very similar API for storing data. The main difference between them is that sessions are accessed using an object, and cookies are accessed using a static class. + +### Storing Data + +Storing session or cookie data is done using the [Cookie::set] method: + + // Set cookie data + Cookie::set($key, $value); + + // Store a user id + Cookie::set('user_id', 10); + +### Retrieving Data + +Getting session or cookie data is done using the [Cookie::get] method: + + // Get cookie data + $data = Cookie::get($key, $default_value); + + // Get the user id + $user = Cookie::get('user_id'); + +### Deleting Data + +Deleting session or cookie data is done using the [Cookie::delete] method: + + // Delete cookie data + Cookie::delete($key); + + // Delete the user id + Cookie::delete('user_id'); + +## Cookie Settings + +All of the cookie settings are changed using static properties. You can either change these settings in `bootstrap.php` or by using [transparent extension](extension). Always check these settings before making your application live, as many of them will have a direct affect on the security of your application. + +The most important setting is [Cookie::$salt], which is used for secure signing. This value should be changed and kept secret: + + Cookie::$salt = 'your secret is safe with me'; + +[!!] Changing this value will render all cookies that have been set before invalid. + +By default, cookies are stored until the browser is closed. To use a specific lifetime, change the [Cookie::$expiration] setting: + + // Set cookies to expire after 1 week + Cookie::$expiration = 604800; + + // Alternative to using raw integers, for better clarity + Cookie::$expiration = Date::WEEK; + +The path that the cookie can be accessed from can be restricted using the [Cookie::$path] setting. + + // Allow cookies only when going to /public/* + Cookie::$path = '/public/'; + +The domain that the cookie can be accessed from can also be restricted, using the [Cookie::$domain] setting. + + // Allow cookies only on the domain www.example.com + Cookie::$domain = 'www.example.com'; + +If you want to make the cookie accessible on all subdomains, use a dot at the beginning of the domain. + + // Allow cookies to be accessed on example.com and *.example.com + Cookie::$domain = '.example.com'; + +To only allow the cookie to be accessed over a secure (HTTPS) connection, use the [Cookie::$secure] setting. + + // Allow cookies to be accessed only on a secure connection + Cookie::$secure = TRUE; + + // Allow cookies to be accessed on any connection + Cookie::$secure = FALSE; + +To prevent cookies from being accessed using Javascript, you can change the [Cookie::$httponly] setting. + + // Make cookies inaccessible to Javascript + Cookie::$httponly = TRUE; \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/debugging.md b/includes/kohana/system/guide/kohana/debugging.md new file mode 100644 index 0000000..1bb7174 --- /dev/null +++ b/includes/kohana/system/guide/kohana/debugging.md @@ -0,0 +1,20 @@ +# Debugging + +Kohana includes several tools to help you debug your application. + +The most basic of these is [Kohana::debug]. This simple method will display any number of variables, similar to [var_export](http://php.net/var_export) or [print_r](http://php.net/print_r), but using HTML for extra formatting. + + // Display a dump of the $foo and $bar variables + echo Kohana::debug($foo, $bar); + +Kohana also provides a method to show the source code of a particular file using [Kohana::debug_source]. + + // Display this line of source code + echo Kohana::debug_source(__FILE__, __LINE__); + +If you want to display information about your application files without exposing the installation directory, you can use [Kohana::debug_path]: + + // Displays "APPPATH/cache" rather than the real path + echo Kohana::debug_path(APPPATH.'cache'); + +If you are having trouble getting something to work correctly, you could check your Kohana logs and your webserver logs, as well as using a debugging tool like [Xdebug](http://www.xdebug.org/). \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/errors.md b/includes/kohana/system/guide/kohana/errors.md new file mode 100644 index 0000000..fb63648 --- /dev/null +++ b/includes/kohana/system/guide/kohana/errors.md @@ -0,0 +1,85 @@ +# Error/Exception Handling + +Kohana provides both an exception handler and an error handler that transforms errors into exceptions using PHP's [ErrorException](http://php.net/errorexception) class. Many details of the error and the internal state of the application is displayed by the handler: + +1. Exception class +2. Error level +3. Error message +4. Source of the error, with the error line highlighted +5. A [debug backtrace](http://php.net/debug_backtrace) of the execution flow +6. Included files, loaded extensions, and global variables + +## Example + +Click any of the links to toggle the display of additional information: + +
    {{userguide/examples/error}}
    + +## Disabling Error/Exception Handling + +If you do not want to use the internal error handling, you can disable it when calling [Kohana::init]: + + Kohana::init(array('errors' => FALSE)); + +## Error Reporting + +By default, Kohana displays all errors, including strict mode warnings. This is set using [error_reporting](http://php.net/error_reporting): + + error_reporting(E_ALL | E_STRICT); + +When you application is live and in production, a more conservative setting is recommended, such as ignoring notices: + + error_reporting(E_ALL & ~E_NOTICE); + +If you get a white screen when an error is triggered, your host probably has disabled displaying errors. You can turn it on again by adding this line just after your `error_reporting` call: + + ini_set('display_errors', TRUE); + +Errors should **always** be displayed, even in production, because it allows you to use [exception and error handling](debugging.errors) to serve a nice error page rather than a blank white screen when an error happens. + + +## Last thoughts + +In production, **your application should never have any uncaught exceptions**, as this can expose sensitive information (via the stack trace). In the previous example we make the assumption that there is actually a view called 'views/errors/404', which is fairly safe to assume. One solution is to turn 'errors' off in Kohana::init for your production machine, so it displays the normal php errors rather than a stack trace. + +~~~ +// snippet from bootstrap.php +Kohana::init(array(' + ... + 'errors' => false, +)); +~~~ + +So rather than displaying the Kohana error page with the stack trace, it will display the default php error. Something like: + +**Fatal error: Uncaught Kohana_View_Exception [ 0 ]: The requested view errors/404 could not be found ~ SYSPATH/classes/kohana/view.php [ 215 ] thrown in /var/www/kohanut/docs.kohanaphp.com/3.0/system/classes/kohana/view.php on line 215** + +Keep in mind what I said earlier though: **your application should never have any uncaught exceptions**, so this should not be necesarry, though it is a good idea, simply because stack traces on a production environment are a *very* bad idea. + +Another solution is to always have a `catch` statement that can't fail, something like an `echo` and an `exit` or a `die()`. This should almost never be necesarry, but it makes some people feel better at night. You can either wrap your entire bootstrap in a try catch, or simply wrap the contents of the catch in another try catch. For example: + +~~~ +try +{ + // Execute the main request + $request->execute(); +} +catch (Exception $e) +{ + try + { + // Be sure to log the error + Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e)); + + // If there was an error, send a 404 response and display an error + $request->status = 404; + $request->response = View::factory('errors/404'); + } + catch + { + // This is completely overkill, but helps some people sleep at night + echo "Something went terribly wrong. Try again in a few minutes."; + exit; + } +} +~~~ \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/extension.md b/includes/kohana/system/guide/kohana/extension.md new file mode 100644 index 0000000..7a00a64 --- /dev/null +++ b/includes/kohana/system/guide/kohana/extension.md @@ -0,0 +1,101 @@ +# Transparent Class Extension + +The [cascading filesystem](files) allows transparent class extension. For instance, the class [Cookie] is defined in `SYSPATH/classes/cookie.php` as: + + class Cookie extends Kohana_Cookie {} + +The default Kohana classes, and many extensions, use this definition so that almost all classes can be extended. You extend any class transparently, by defining your own class in `APPPATH/classes/cookie.php` to add your own methods. + +[!!] You should **never** modify any of the files that are distributed with Kohana. Always make modifications to classes using transparent extension to prevent upgrade issues. + +For instance, if you wanted to create method that sets encrypted cookies using the [Encrypt] class, you would creat a file at `application/classes/cookie.php` that extends Kohana_Cookie, and adds your functions: + + encode((string) $value); + + parent::set($name, $value, $expiration); + } + + /** + * Gets an encrypted cookie. + * + * @uses Cookie::get + * @uses Encrypt::decode + */ + public static function decrypt($name, $default = NULL) + { + if ($value = parent::get($name, NULL)) + { + $value = Encrypt::instance(Cookie::$encryption)->decode($value); + } + + return isset($value) ? $value : $default; + } + + } // End Cookie + +Now calling `Cookie::encrypt('secret', $data)` will create an encrypted cookie which we can decrypt with `$data = Cookie::decrypt('secret')`. + +## How it works + +To understand how this works, let's look at what happens normally. When you use the Cookie class, [Kohana::autoload] looks for `classes/cookie.php` in the [cascading filesystem](files). It looks in `application`, then each module, then `system`. The file is found in `system` and is included. Of coures, `system/classes/cookie.php` is just an empty class which extends `Kohana_Cookie`. Again, [Kohana::autoload] is called this time looking for `classes/kohana/cookie.php` which it finds in `system`. + +When you add your transparently extended cookie class at `application/classes/cookie.php` this file essentially "replaces" the file at `system/classes/cookie.php` without actually touching it. This happens because this time when we use the Cookie class [Kohana::autoload] looks for `classes/cookie.php` and finds the file in `application` and includes that one, instead of the one in system. + +## Example: changing [Cookie] settings + +If you are using the [Cookie](cookies) class, and want to change a setting, you should do so using transparent extension, rather than editing the file in the system folder. If you edit it directly, and in the future you upgrade your Kohana version by replacing the system folder, your changes will be reverted and your cookies will probably be invalid. Instead, create a cookie.php file either in `application/classes/cookie.php` or a module (`MODPATH//classes/cookie.php`). + + class Cookie extends Kohana_Cookie { + + // Set a new salt + public $salt = "some new better random salt phrase"; + + // Don't allow javascript access to cookies + public $httponly = TRUE; + + } + +## Example: TODO: an example + +Just post the code and breif descript of what function it adds, you don't have to do the "How it works" like above. + +## Example: TODO: something else + +Just post the code and breif descript of what function it adds, you don't have to do the "How it works" like above. + +## More examples + +TODO: Provide some links to modules on github, etc that have examples of transparent extension in use. + +## Multiple Levels of Extension + +If you are extending a Kohana class in a module, you should maintain transparent extensions. In other words, do not include any variables or function in the "base" class (eg. Cookie). Instead make your own namespaced class, and have the "base" class extend that one. With our Encrypted cookie example we can create `MODPATH/mymod/encrypted/cookie.php`: + + class Encrypted_Cookie extends Kohana_Cookie { + + // Use the same encrypt() and decrypt() methods as above + + } + +And create `MODPATH/mymod/cookie.php`: + + class Cookie extends Encrypted_Cookie {} + +This will still allow users to add their own extension to [Cookie] while leaving your extensions intact. To do that they would make a cookie class that extends `Encrypted_Cookie` (rather than `Kohana_Cookie`) in their application folder. diff --git a/includes/kohana/system/guide/kohana/files.md b/includes/kohana/system/guide/kohana/files.md new file mode 100644 index 0000000..8725339 --- /dev/null +++ b/includes/kohana/system/guide/kohana/files.md @@ -0,0 +1,83 @@ +# Cascading Filesystem + +The Kohana filesystem is a heirarchy of similar directory structures that cascade. The heirarchy in Kohana (used when a file is loaded by [Kohana::find_file]) is in the following order: + +1. **Application Path** + Defined as `APPPATH` in `index.php`. The default value is `application`. + +2. **Module Paths** + This is set as an associative array using [Kohana::modules] in `APPPATH/bootstrap.php`. Each of the values of the array will be searched **in the order that the modules are added**. + +3. **System Path** + Defined as `SYSPATH` in `index.php`. The default value is `system`. All of the main or "core" files and classes are defined here. + +Files that are in directories higher up the include path order take precedence over files of the same name lower down the order, which makes it is possible to overload any file by placing a file with the same name in a "higher" directory: + +![Cascading Filesystem Infographic](cascading_filesystem.png) + +This image is only shows certain files, but we can use it to illustrate some examples of the cascading filesystem: + +* If Kohana catches an error, it would display the `kohana/error.php` view, So it would call `Kohana::find_file('views', 'kohana/error')`. This would return `application/views/kohana/error.php` because it takes precidence over `system/views/kohana/error.php`. By doing this we can change the error view without editing the system folder. + +* If we used `View::factory('welcome')` it would call `Kohana::find_file('views','welcome')` which would return `application/views/welcome.php` because it takes precidence over `modules/common/views/welcome.php`. By doing this, you can overwrite things in a module without editing the modules files. + +* If use the Cookie class, [Kohana::auto_load] will call `Kohana::find_file('classes', 'cookie')` which will return `application/classes/cookie.php`. Assuming Cookie extends Kohana_Cookie, the autoloader would then call `Kohana::find_file('classes','kohana/cookie')` which will return `system/classes/kohana/cookie.php` because that file does not exist anywhere higher in the cascade. This is an example of [transparent extension](extension). + +* If you used `View::factory('user')` it would call `Kohana::find_file('views','user')` which would return `modules/common/views/user.php`. + +* If we wanted to change something in `config/database.php` we could copy the file to `application/config/database.php` and make the changes there. Keep in mind that [config files are merged](files/config#merge) rather than overwritten by the cascade. + +## Types of Files + +The top level directories of the application, module, and system paths have the following default directories: + +classes/ +: All classes that you want to [autoload](autoloading) should be stored here. This includes [controllers](mvc/controllers), [models](mvc/models), and all other classes. All classes must follow the [class naming conventions](conventions#class-names-and-file-location). + +config/ +: Configuration files return an associative array of options that can be loaded using [Kohana::config]. Config files are merged rather than overwritten by the cascade. See [config files](files/config) for more information. + +i18n/ +: Translation files return an associative array of strings. Translation is done using the `__()` method. To translate "Hello, world!" into Spanish, you would call `__('Hello, world!')` with [I18n::$lang] set to "es-es". I18n files are merged rather than overwritten by the cascade. See [I18n files](files/i18n) for more information. + +messages/ +: Message files return an associative array of strings that can be loaded using [Kohana::message]. Messages and i18n files differ in that messages are not translated, but always written in the default language and referred to by a single key. Message files are merged rather than overwritten by the cascade. See [message files](files/messages) for more information. + +views/ +: Views are plain PHP files which are used to generate HTML or other output. The view file is loaded into a [View] object and assigned variables, which it then converts into an HTML fragment. Multiple views can be used within each other. See [views](mvc/views) for more information. + +*other* +: You can include any other folders in your cascading filesystem. Examples include, but are not limited to, `guide`, `vendor`, `media`, whatever you want. For example, to find `media/logo.png` in the cascading filesystem you would call `Kohana::find_file('media','logo','png')`. + +## Finding Files + +The path to any file within the filesystem can be found by calling [Kohana::find_file]: + + // Find the full path to "classes/cookie.php" + $path = Kohana::find_file('classes', 'cookie'); + + // Find the full path to "views/user/login.php" + $path = Kohana::find_file('views', 'user/login'); + +If the file doesn't have a `.php` extension, pass the extension as the third param. + + // Find the full path to "guide/menu.md" + $path = Kohana::find_file('guide', 'menu', 'md'); + + // If $name is "2000-01-01-first-post" this would look for "posts/2000-01-01-first-post.textile" + $path = Kohana::find_file('posts', $name, '.textile'); + + +## Vendor Extensions + +We call extensions or external libraries that are not specific to Kohana "vendor" extensions, and they go in the vendor folder, either in application or in a module. Because these libraries do not follow Kohana's file naming conventions, they cannot be autoloaded by Kohana, so you will have to manually included them. Some examples of vendor libraries are [Markdown](http://daringfireball.net/projects/markdown/), [DOMPDF](http://code.google.com/p/dompdf), [Mustache](http://github.com/bobthecow/mustache.php) and [Swiftmailer](http://swiftmailer.org/). + +For example, if you wanted to use [DOMPDF](http://code.google.com/p/dompdf), you would copy it to `application/vendor/dompdf` and include the DOMPDF autoloading class. It can be useful to do this in a controller's before method, as part of a module's init.php, or the contstructor of a singleton class. + + require Kohana::find_file('vendor', 'dompdf/dompdf/dompdf_config','inc'); + +Now you can use DOMPDF without loading any more files: + + $pdf = new DOMPDF; + +[!!] If you want to convert views into PDFs using DOMPDF, try the [PDFView](http://github.com/shadowhand/pdfview) module. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/files/classes.md b/includes/kohana/system/guide/kohana/files/classes.md new file mode 100644 index 0000000..cdffc60 --- /dev/null +++ b/includes/kohana/system/guide/kohana/files/classes.md @@ -0,0 +1,41 @@ +# Classes + +TODO: Brief intro to classes. + +[Models](mvc/models) and [Controllers](mvc/controllers) are classes as well, but are treated slightly differently by Kohana. Read their respective pages to learn more. + +## Helper or Library? + +Kohana 3 does not differentiate between "helper" classes and "library" classes like in previous versions. They are all placed in the `classes/` folder and follow the same conventions. The distinction is that in general, a "helper" class is used statically, (for examples see the [helpers included in Kohana](helpers)), and library classes are typically instanciated and used as objects (like the [Database query builders](../database/query/builder)). The distinction is not black and white, and is irrelevant anyways, since they are treated the same by Kohana. + +## Creating a class + +To create a new class, simply place a file in the `classes/` directory at any point in the [Cascading Filesystem](files), that follows the [Class naming conventions](conventions#class-names-and-file-location). For example, lets create a `Foobar` class. + + // classes/foobar.php + + class Foobar { + static function magic() { + // Does something + } + } + +We can now call `Foobar::magic()` any where and Kohana will [autoload](autoloading) the file for us. + +We can also put classes in subdirectories. + + // classes/professor/baxter.php + + class Professor_Baxter { + static function teach() { + // Does something + } + } + +We could now call `Professor_Baxter::teach()` any where we want. + +For examples of how to create and use classes, simply look at the 'classes' folder in `system` or any module. + +## Namespacing your classes + +TODO: Discuss namespacing to provide transparent extension functionality in your own classes/modules. diff --git a/includes/kohana/system/guide/kohana/files/config.md b/includes/kohana/system/guide/kohana/files/config.md new file mode 100644 index 0000000..107101e --- /dev/null +++ b/includes/kohana/system/guide/kohana/files/config.md @@ -0,0 +1,95 @@ +# Config Files + +Configuration files are used to store any kind of configuration needed for a module, class, or anything else you want. They are plain PHP files, stored in the `config/` directory, which return an associative array: + + 'value', + 'options' => array( + 'foo' => 'bar', + ), + ); + +If the above configuration file was called `myconf.php`, you could access it using: + + $config = Kohana::config('myconf'); + $options = $config['options']; + +[Kohana::config] also provides a shortcut for accessing individual keys from configuration arrays using "dot paths" similar to [Arr::path]. + +Get the "options" array: + + $options = Kohana::config('myconf.options'); + +Get the "foo" key from the "options" array: + + $foo = Kohana::config('myconf.options.foo'); + +Configuration arrays can also be accessed as objects, if you prefer that method: + + $options = Kohana::config('myconf')->options; + +Please note that you can only access the top level of keys as object properties, all child keys must be accessed using standard array syntax: + + $foo = Kohana::config('myconf')->options['foo']; + +## Merge + +Configuration files are slightly different from most other files within the [cascading filesystem](files) in that they are **merged** rather than overloaded. This means that all configuration files with the same file path are combined to produce the final configuration. The end result is that you can overload *individual* settings rather than duplicating an entire file. + +For example, if we wanted to change something in some file + + [TODO] + +TODO exmaple of adding something to inflector + +## Creating your own config files + +Let's say we want a config file to store and easily change things like the title of a website, or the google analytics code. We would create a config file, let's call it `site.php`: + + // config/site.php + + 'Our Shiny Website', + 'analytics' => FALSE, // analytics code goes here, set to FALSE to disable + ); + +We could now call `Kohana::config('site.title')` to get the site name, and `Kohana::config('site.analytics')` to get the analytics code. + +Let's say we want an archive of versions of some software. We could use config files to store each version, and include links to download, documentation, and issue tracking. + + // config/versions.php + + array( + 'codename' => 'Frog', + 'download' => 'files/ourapp-1.0.0.tar.gz', + 'documentation' => 'docs/1.0.0', + 'released' => '06/05/2009', + 'issues' => 'link/to/bug/tracker', + ), + '1.1.0' => array( + 'codename' => 'Lizard', + 'download' => 'files/ourapp-1.1.0.tar.gz', + 'documentation' => 'docs/1.1.0', + 'released' => '10/15/2009', + 'issues' => 'link/to/bug/tracker', + ), + /// ... etc ... + ); + +You could then do the following: + + // In your controller + $view->versions = Kohana::config('versions'); + + // In your view: + foreach ($versions as $version) + { + // echo some html to display each version + } diff --git a/includes/kohana/system/guide/kohana/files/i18n.md b/includes/kohana/system/guide/kohana/files/i18n.md new file mode 100644 index 0000000..88df52f --- /dev/null +++ b/includes/kohana/system/guide/kohana/files/i18n.md @@ -0,0 +1 @@ +Discuss the format of i18n files, and how to use them. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/files/messages.md b/includes/kohana/system/guide/kohana/files/messages.md new file mode 100644 index 0000000..b0c4a5c --- /dev/null +++ b/includes/kohana/system/guide/kohana/files/messages.md @@ -0,0 +1,5 @@ + + +Add that message files can be in subfolders, and you can use dot notation to retreive an array path: `Kohana::message('folder/subfolder/file','array.subarray.key')` + +Also reinforce that messages are merged by the cascade, not overwritten. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/flow.md b/includes/kohana/system/guide/kohana/flow.md new file mode 100644 index 0000000..bfd99d8 --- /dev/null +++ b/includes/kohana/system/guide/kohana/flow.md @@ -0,0 +1,26 @@ +# Request Flow + +Every application follows the same flow: + +1. Application starts from `index.php`. + 1. The application, module, and system paths are set. (`APPPATH`, `MODPATH`, and `SYSPATH`) + 2. Error reporting levels are set. + 3. Install file is loaded, if it exists. + 4. The [Kohana] class is loaded. + 5. The bootstrap file, `APPPATH/bootstrap.php`, is included. +2. Once we are in `bootstrap.php`: + 7. [Kohana::init] is called, which sets up error handling, caching, and logging. + 8. [Kohana_Config] readers and [Kohana_Log] writers are attached. + 9. [Kohana::modules] is called to enable additional modules. + * Module paths are added to the [cascading filesystem](files). + * Includes each module's `init.php` file, if it exists. + * The `init.php` file can perform additional environment setup, including adding routes. + 10. [Route::set] is called multiple times to define the [application routes](routing). + 11. [Request::instance] is called to start processing the request. + 1. Checks each route that has been set until a match is found. + 2. Creates the controller instance and passes the request to it. + 3. Calls the [Controller::before] method. + 4. Calls the controller action, which generates the request response. + 5. Calls the [Controller::after] method. + * The above 5 steps can be repeated multiple times when using [HMVC sub-requests](requests). + 12. The main [Request] response is displayed \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/fragments.md b/includes/kohana/system/guide/kohana/fragments.md new file mode 100644 index 0000000..fa4f0e3 --- /dev/null +++ b/includes/kohana/system/guide/kohana/fragments.md @@ -0,0 +1,135 @@ +# Fragments + +Fragments are a quick and simple way to cache HTML or other output. Fragments are not useful for caching objects or raw database results, in which case you should use a more robust caching method, which can be achieved with the [Cache module](../cache). Fragments use [Kohana::cache()] and will be placed in the cache directory (`application/cache` by default). + +You should use Fragment (or any caching solution) when reading the cache is faster than reprocessing the result. Reading and parsing a remote file, parsing a complicated template, calculating something, etc. + +Fragments are typically used in view files. + +## Usage + +Fragments are used by calling [Fragment::load()] in an `if` statement at the beginning of what you want cached, and [Fragment::save()] at the end. They use [output buffering](http://www.php.net/manual/en/function.ob-start.php) to capture the output between the two function calls. + +You can specify the lifetime (in seconds) of the Fragment using the second parameter of [Fragment::load()]. The default lifetime is 30 seconds. You can use the [Date] helper to make more readable times. + +Fragments will store a different cache for each language (using [I18n]) if you pass `true` as the third parameter to [Fragment::load()]; + +You can force the deletion of a Fragment using [Fragment::delete()], or specify a lifetime of 0. + +~~~ +// Cache for 5 minutes, and cache each language +if ( ! Fragment::load('foobar', Date::MINUTE * 5, true)) +{ + // Anything that is echo'ed here will be saved + Fragment::save(); +} +~~~ + +## Example: Calculating Pi + +In this example we will calculate pi to 1000 places, and cache the result using a fragment. The first time you run this it will probably take a few seconds, but subsequent loads will be much faster, until the fragment lifetime runs out. + +~~~ +if ( ! Fragment::load('pi1000', Date::HOUR * 4)) +{ + // Change function nesting limit + ini_set('xdebug.max_nesting_level',1000); + + // Source: http://mgccl.com/2007/01/22/php-calculate-pi-revisited + function bcfact($n) + { + return ($n == 0 || $n== 1) ? 1 : bcmul($n,bcfact($n-1)); + } + function bcpi($precision) + { + $num = 0;$k = 0; + bcscale($precision+3); + $limit = ($precision+3)/14; + while($k < $limit) + { + $num = bcadd($num, bcdiv(bcmul(bcadd('13591409',bcmul('545140134', $k)),bcmul(bcpow(-1, $k), bcfact(6*$k))),bcmul(bcmul(bcpow('640320',3*$k+1),bcsqrt('640320')), bcmul(bcfact(3*$k), bcpow(bcfact($k),3))))); + ++$k; + } + return bcdiv(1,(bcmul(12,($num))),$precision); + } + + echo bcpi(1000); + + Fragment::save(); +} + +echo View::factory('profiler/stats'); + +?> +~~~ + +## Example: Recent Wikipedia edits + +In this example we will use the [Feed] class to retrieve and parse an RSS feed of recent edits to [http://en.wikipedia.org](http://en.wikipedia.org), then use Fragment to cache the results. + +~~~ +$feed = "http://en.wikipedia.org/w/index.php?title=Special:RecentChanges&feed=rss"; +$limit = 50; + +// Displayed feeds are cached for 30 seconds (default) +if ( ! Fragment::load('rss:'.$feed)): + + // Parse the feed + $items = Feed::parse($feed, $limit); + + foreach ($items as $item): + + // Convert $item to object + $item = (object) $item; + + echo HTML::anchor($item->link,$item->title); + + ?> +
    +

    author: creator ?>

    +

    date: pubDate ?>

    +
    + Home page stuff

    "; + + // Pretend like we are actually doing something :) + sleep(2); + + // Cache this every hour since it doesn't change as often + if ( ! Fragment::load('homepage-subfragment', Date::HOUR)): + + echo "

    Home page special thingy

    "; + + // Pretend like this takes a long time + sleep(5); + + Fragment::save(); endif; + + echo "

    More home page stuff

    "; + + Fragment::save(); + +endif; + +echo View::factory('profiler/stats'); +~~~ \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/helpers.md b/includes/kohana/system/guide/kohana/helpers.md new file mode 100644 index 0000000..e8f6bcb --- /dev/null +++ b/includes/kohana/system/guide/kohana/helpers.md @@ -0,0 +1,53 @@ +# Helpers + +Kohana comes with many static helper functions to make certain tasks easier. + +You can make your own helpers by simply making a class and putting it in the `classes` directory, and you can also extend any helper to modify or add new functions using transparent extension. + + - **[Arr]** - Array functions. Get an array key or default to a set value, get an array key by path, etc. + + - **[CLI]** - Parse command line options. + + - **[Cookie]** - Covered in more detail on the [Cookies](cookies) page. + + - **[Date]** - Useful date functions and constants. Time between two dates, convert between am/pm and military, date offset, etc. + + - **[Encrypt]** - Covered in more detail on the [Security](security) page. + + - **[Feed]** - Parse and create RSS feeds. + + - **[File]** - Get file type by mime, split and merge a file into small pieces. + + - **[Form]** - Create HTML form elements. + + - **[Fragment]** - Simple file based caching. Covered in more detail on the [Fragments](fragments) page. + + - **[HTML]** - Useful HTML functions. Encode, obfuscate, create script, anchor, and image tags, etc. + + - **[I18n]** - Internationalization helper for creating multilanguage sites. + + - **[Inflector]** - Change a word into plural or singular form, camelize or humanize a phrase, etc. + + - **[Kohana]** - The Kohana class is also a helper. Debug variables (like print_r but better), file loading, etc. + + - **[Num]** - Provides locale aware formating and english ordinals (th, st, nd, etc). + + - **[Profiler]** - Covered in more detail on the [Profiling](profiling) page. + + - **[Remote]** - Remote server access helper using [CURL](http://php.net/curl). + + - **[Request]** - Get the current request url, create expire tags, send a file, get the user agent, etc. + + - **[Route]** - Create routes, create an internal link using a route. + + - **[Security]** - Covered in more detail on the [Security](security) page. + + - **[Session]** - Covered in more detail on the [Sessions](sessions) page. + + - **[Text]** - Autolink, prevent window words, convert a number to text, etc. + + - **[URL]** - Create a relative or absolute URL, make a URL-safe title, etc. + + - **[UTF8]** - Provides multi-byte aware string functions like strlen, strpos, substr, etc. + + - **[Upload]** - Helper for uploading files from a form. diff --git a/includes/kohana/system/guide/kohana/index.md b/includes/kohana/system/guide/kohana/index.md new file mode 100644 index 0000000..6f74f68 --- /dev/null +++ b/includes/kohana/system/guide/kohana/index.md @@ -0,0 +1,19 @@ +# What is Kohana? + +Kohana is an open source, [object oriented](http://wikipedia.org/wiki/Object-Oriented_Programming) [MVC](http://wikipedia.org/wiki/Model–View–Controller "Model View Controller") [web framework](http://wikipedia.org/wiki/Web_Framework) built using [PHP5](http://php.net/manual/intro-whatis "PHP Hypertext Preprocessor") by a team of volunteers that aims to be swift, secure, and small. + +[!!] Kohana is licensed under a [BSD license](http://kohanaframework.org/license), so you can legally use it for any kind of open source, commercial, or personal project. + +## What makes Kohana great? + +Anything can be extended using the unique [filesystem](about.filesystem) design, little or no [configuration](about.configuration) is necessary, [error handling](debugging.errors) helps locate the source of errors quickly, and [debugging](debugging) and [profiling](debugging.profiling) provide insight into the application. + +To help secure your applications, tools for [XSS removal](security.xss), [input validation](security.validation), [signed cookies](security.cookies), [form](security.forms) and [HTML](security.html) generators are all included. The [database](security.database) layer provides protection against [SQL injection](http://wikipedia.org/wiki/SQL_Injection). Of course, all official code is carefully written and reviewed for security. + +## Contribute to the Documentation + +We are working very hard to provide complete documentation. To help improve the guide, please [fork the userguide](http://github.com/kohana/userguide), make your changes, and send a pull request. If you are not familiar with git, you can also submit a [feature request](http://dev.kohanaframework.org/projects/kohana3/issues) (requires registration). + +## Unofficial Documentation + +If you are having trouble finding an answer here, have a look through the [unofficial wiki](http://kerkness.ca/wiki/doku.php). Your answer may also be found by searching the [forum](http://forum.kohanaphp.com/) or [stackoverflow](http://stackoverflow.com/questions/tagged/kohana) followed by asking your question on either. Additionally, you can chat with the community of developers on the freenode [#kohana](irc://irc.freenode.net/kohana) IRC channel. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/install.md b/includes/kohana/system/guide/kohana/install.md new file mode 100644 index 0000000..876fb11 --- /dev/null +++ b/includes/kohana/system/guide/kohana/install.md @@ -0,0 +1,33 @@ +# Installation + +1. Download the latest **stable** release from the [Kohana website](http://kohanaframework.org/). +2. Unzip the downloaded package to create a `kohana` directory. +3. Upload the contents of this folder to your webserver. +4. Open `application/bootstrap.php` and make the following changes: + - Set the default [timezone](http://php.net/timezones) for your application. + - Set the `base_url` in the [Kohana::init] call to reflect the location of the kohana folder on your server relative to the document root. +6. Make sure the `application/cache` and `application/logs` directories are writable by the web server. +7. Test your installation by opening the URL you set as the `base_url` in your favorite browser. + +[!!] Depending on your platform, the installation's subdirs may have lost their permissions thanks to zip extraction. Chmod them all to 755 by running `find . -type d -exec chmod 0755 {} \;` from the root of your Kohana installation. + +You should see the installation page. If it reports any errors, you will need to correct them before continuing. + +![Install Page](install.png "Example of install page") + +Once your install page reports that your environment is set up correctly you need to either rename or delete `install.php` in the root directory. Kohana is now installed and you should see the output of the welcome controller: + +![Welcome Page](welcome.png "Example of welcome page") + +## Installing Kohana 3.0 From GitHub + +The [source code](http://github.com/kohana/kohana) for Kohana 3.0 is hosted with [GitHub](http://github.com). To install Kohana using the github source code first you need to install git. Visit [http://help.github.com](http://help.github.com) for details on how to install git on your platform. + +To install the last stable release of Kohana using git run these commands: + + git clone git://github.com/kohana/kohana.git + cd kohana/ + git submodule init + git submodule update + +[!!] For more information on using Git and Kohana see the [Working with Git](tutorials/git) tutorial. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/menu.md b/includes/kohana/system/guide/kohana/menu.md new file mode 100644 index 0000000..06da9d3 --- /dev/null +++ b/includes/kohana/system/guide/kohana/menu.md @@ -0,0 +1,48 @@ +## [Kohana]() + +- Getting Started + - [Installation](install) + - [Conventions and Style](conventions) + - [Model View Controller](mvc) + - [Controllers](mvc/controllers) + - [Models](mvc/models) + - [Views](mvc/views) + - [Cascading Filesystem](files) + - [Class Files](files/classes) + - [Config Files](files/config) + - [Translation Files](files/i18n) + - [Message Files](files/messages) + - [Request Flow](flow) + - [Bootstrap](bootstrap) + - [Modules](modules) + - [Routing](routing) + - [Error Handling](errors) + - [Tips & Common Mistakes](tips) + - [Upgrading from v2.x](upgrading) +- Basic Usage + - [Debugging](debugging) + - [Loading Classes](autoloading) + - [Transparent Extension](extension) + - [Helpers](helpers) + - [Requests](requests) + - [Sessions](sessions) + - [Cookies](cookies) + - [Fragments](fragments) + - [Profiling](profiling) +- [Security](security) + - [XSS](security/xss) + - [Validation](security/validation) + - [Cookies](security/cookies) + - [Database](security/database) + - [Encryption](security/encryption) + - [Deploying](security/deploying) +- [Tutorials](tutorials) + - [Hello World](tutorials/hello-world) + - [Simple MVC](tutorials/simple-mvc) + - [Routes & Links](tutorials/routes-and-links) + - [Custom Error Pages](tutorials/error-pages) + - [Content Translation](tutorials/translation) + - [Clean URLs](tutorials/clean-urls) + - [Sharing Kohana](tutorials/sharing-kohana) + - [Template Driven Site](tutorials/templates) + - [Working with Git](tutorials/git) diff --git a/includes/kohana/system/guide/kohana/models.md b/includes/kohana/system/guide/kohana/models.md new file mode 100644 index 0000000..f6c960b --- /dev/null +++ b/includes/kohana/system/guide/kohana/models.md @@ -0,0 +1 @@ +This will discuss models, explain what should be in a model, and give *breif* examples of extending models, like using modeling systems. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/modules.md b/includes/kohana/system/guide/kohana/modules.md new file mode 100644 index 0000000..62bf574 --- /dev/null +++ b/includes/kohana/system/guide/kohana/modules.md @@ -0,0 +1,38 @@ +# Modules + +Modules are simply an addition to the [Cascading Filesystem](files). A module can add any kind of file (controllers, views, classes, config files, etc.) to the filesystem available to Kohana (via [Kohana::find_file]). This is useful to make any part of your application more transportable or shareable between different apps. For example, creating a new modeling system, a search engine, a css/js manager, etc. + +## Where to find modules + +Kolanos has created [kohana-universe](http://github.com/kolanos/kohana-universe/tree/master/modules/), a fairly comprehensive list of modules that are available on Github. To get your module listed there, send him a message via Github. + +Mon Geslani created a [very nice site](http://kohana.mongeslani.com/) that allows you to sort Github modules by activity, watchers, forks, etc. It seems to not be as comprehensive as kohana-universe. + +## Enabling modules + +Modules are enabled by calling [Kohana::modules] and passing an array of `'name' => 'path'`. The name isn't important, but the path obviously is. A module's path does not have to be in `MODPATH`, but usually is. You can only call [Kohana::modules] once. + + Kohana::modules(array( + 'auth' => MODPATH.'auth', // Basic authentication + 'cache' => MODPATH.'cache', // Caching with multiple backends + 'codebench' => MODPATH.'codebench', // Benchmarking tool + 'database' => MODPATH.'database', // Database access + 'image' => MODPATH.'image', // Image manipulation + 'orm' => MODPATH.'orm', // Object Relationship Mapping + 'oauth' => MODPATH.'oauth', // OAuth authentication + 'pagination' => MODPATH.'pagination', // Paging of results + 'unittest' => MODPATH.'unittest', // Unit testing + 'userguide' => MODPATH.'userguide', // User guide and API documentation + )); + +## Init.php + +When a module is activated, if an `init.php` file exists in that module's directory, it is included. This is the ideal place to have a module include routes or other initialization necessary for the module to function. The Userguide and Codebench modules have init.php files you can look at. + +## How modules work + +A file in an enabled module is virtually the same as having that exact file in the same place in the application folder. The main difference being that it can be overwritten by a file of the same name in a higher location (a module enabled after it, or the application folder) via the [Cascading Filesystem](files). It also provides an easy way to organize and share your code. + +## Creating your own module + +To create a module simply create a folder (usually in `DOCROOT/modules`) and place the files you want to be in the module there, and activate that module in your bootstrap. To share your module, you can upload it to [Github](http://github.com). You can look at examples of modules made by [Kohana](http://github.com/kohana) or [other users](#where-to-find-modules). \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/mvc.md b/includes/kohana/system/guide/kohana/mvc.md new file mode 100644 index 0000000..2ee8549 --- /dev/null +++ b/includes/kohana/system/guide/kohana/mvc.md @@ -0,0 +1,3 @@ + + +Discus the MVC pattern, as it pertains to Kohana. Perhaps have an image, etc. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/mvc/controllers.md b/includes/kohana/system/guide/kohana/mvc/controllers.md new file mode 100644 index 0000000..ec15bea --- /dev/null +++ b/includes/kohana/system/guide/kohana/mvc/controllers.md @@ -0,0 +1,189 @@ +# Controllers + +A Controller is a class file that stands in between the models and the views in an application. It passes information on to the model when data needs to be changed and it requests information from the model when data needs to be loaded. Controllers then pass on the information of the model to the views where the final output can be rendered for the users. Controllers essentially control the flow of the application. + +Controllers are called by the [Request::execute()] function based on the [Route] that the url matched. Be sure to read the [routing](routing) page to understand how to use routes to map urls to your controllers. + +## Creating Controllers + +In order to function, a controller must do the following: + +* Reside in `classes/controller` (or a sub-directory) +* Filename must be lowercase, e.g. `articles.php` +* The class name must map to the filename (with `/` replaced with `_`) and each word is capitalized +* Must have the Controller class as a (grand)parent + +Some examples of controller names and file locations: + + // classes/controller/foobar.php + class Controller_Foobar extends Controller { + + // classes/controller/admin.php + class Controller_Admin extends Controller { + +Controllers can be in sub-folders: + + // classes/controller/baz/bar.php + class Controller_Baz_Bar extends Controller { + + // classes/controller/product/category.php + class Controller_Product_Category extends Controller { + +[!!] Note that controllers in sub-folders can not be called by the default route, you will need to define a route that has a [directory](routing#directory) param or sets a default value for directory. + +Controllers can extend other controllers. + + // classes/controller/users.php + class Controller_Users extends Controller_Template + + // classes/controller/api.php + class Controller_Api extends Controller_REST + +[!!] [Controller_Template] and [Controller_REST] are some example controllers provided in Kohana. + +You can also have a controller extend another controller to share common things, such as requiring you to be logged in to use all of those controllers. + + // classes/controller/admin.php + class Controller_Admin extends Controller { + // This controller would have a before() that checks if the user is logged in + + // classes/controller/admin/plugins.php + class Controller_Admin_Plugins extends Controller_Admin { + // Because this controller extends Controller_Admin, it would have the same logged in check + +## $this->request + +Every controller has the `$this->request` property which is the [Request] object that called the controller. You can use this to get information about the current request, as well as set the response via `$this->request->response`. + +Here is a partial list of the properties and methods available to `$this->request`. These can also be accessed via `Request::instance()`, but `$this->request` is provided as a shortcut. See the [Request] class for more information on any of these. + +Property/method | What it does +--- | --- +[$this->request->route](../api/Request#property:route) | The [Route] that matched the current request url +[$this->request->directory](../api/Request#property:directory),
    [$this->request->controller](../api/Request#property:controller),
    [$this->request->action](../api/Request#property:action) | The directory, controller and action that matched for the current route +[$this->request->param()](../api/Request#param) | Any other params defined in your route +[$this->request->response](../api/Request#property:response) | The content to return for this request +[$this->request->status](../api/Request#property:status) | The HTTP status for the request (200, 404, 500, etc.) +[$this->request->headers](../api/Request#property:headers) | The HTTP headers to return with the response +[$this->request->redirect()](../api/Request#redirect) | Redirect the request to a different url + + +## Actions + +You create actions for your controller by defining a public function with an `action_` prefix. Any method that is not declared as `public` and prefixed with `action_` can NOT be called via routing. + +An action method will decide what should be done based on the current request, it *controls* the application. Did the user want to save a blog post? Did they provide the necesarry fields? Do they have permission to da that? The controller will call other classes, including models, to accomplish this. Every action should set `$this->request->response` to the [view file](mvc/views) to be sent to the browser, unless it [redirected](../api/Request#redirect) or otherwise ended the script earlier. + +A very basic action method that simply loads a [view](mvc/views) file. + + public function action_hello() + { + $this->request->response = View::factory('hello/world'); // This will load views/hello/world.php + } + +### Parameters + +Parameters can be accessed in two ways. The first is by calling `$this->request->param('name')` where `name` is the name defined in the route. + + // Assuming Route::set('example','(/(/(/)))'); + + public function action_foobar() + { + $id = $this->request->param('id'); + $new = $this->request->param('new'); + +If that parameter is not set it will be returned as NULL. You can provide a second parameter to set a default value if that param is not set. + + public function action_foobar() + { + // $id will be false if it was not supplied in the url + $id = $this->request->param('user',FALSE); + +The second way you can access route parameters is from the actions function definition. Any extra keys in your route (keys besides ``, ``, and ``) are passed as parameters to your action *in the order they appear in the route*. + + // Assuming Route::set('example','(/(/(/)))'); + + public function action_foobar($id, $new) + { + +Note that the names do not actually matter, *only the order*. You could name the parameters anything you want in both the route and the function definition, they don't even need to match. The following code is identical in function to the previous example. + + // Assuming Route::set('example','(/(/(/)))'); + + public function action_foobar($foo, $bar) + { + +You can provide default values in the same way you do for any php function. + + public function action_foobar($id = 0, $new = NULL) + { + +You can use whichever method you prefer. Using function params is quick and easy and saves on `$this->request->param()` calls, but keep in mind that if your routes ever change it could change the paramater order and break things. Therefore, it is recommended you use `$this->request->param()`. For example, assuming the following route + + Route::set('example','(/(/(/)))'); + +If you called "example/foobar/4/bobcat" you could access the parameters by either: + + public function action_foobar($id, $new) + { + + // OR + + public function action_foobar() + { + $id = $this->request->param('id'); + $new = $this->request->param('new'); + +Then, let's say sometime in the future you change your url schemes and your routes. The new route is: + + // Note that id and new are switched + Route::set('example','(/(/(/)))'); + +Because the `` and `` keys are in a different order, you will need to fix your function definition to be `action_foobar($new, $id)` whereas the function that used `$this->request->param()` calls would continue to function as desired. + +### Examples + +TODO: some examples of actions + +## Before and after + +You can use the `before()` and `after()` functions to have code executed before or after the action is executed. For example, you could check if the user is logged in, set a template view, loading a required file, etc. + +For example, if you look in `Controller_Template` you can see that in the be + +You can check what action has been requested (via `$this->request->action`) and do something based on that, such as requiring the user to be logged in to use a controller, unless they are using the login action. + + // Checking auth/login in before, and redirecting if necessary: + + Controller_Admin extends Controller { + + public function before() + { + // If this user doesn't have the admin role, and is not trying to login, redirect to login + if ( ! Auth::instance()->logged_in('admin') AND $this->request->action !== 'login') + { + $this->request->redirect('admin/login'); + } + } + + public function action_login() { + ... + +### Custom __construct() function + +In general, you should not have to change the `__construct()` function, as anything you need for all actions can be done in `before()`. If you need to change the controller constructor, you must preserve the parameters or PHP will complain. This is so the Request object that called the controller is available. *Again, in most cases you should probably be using `before()`, and not changing the constructor*, but if you really, *really* need to it should look like this: + + // You should almost never need to do this, use before() instead! + + // Be sure Kohana_Request is in the params + public function __construct(Kohana_Request $request) + { + // You must call parent::__construct at some point in your function + parent::__construct($request); + + // Do whatever else you want + } + +## Extending other controllers + +TODO: More description and examples of extending other controllers, multiple extension, etc. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/mvc/models.md b/includes/kohana/system/guide/kohana/mvc/models.md new file mode 100644 index 0000000..2fbcf0b --- /dev/null +++ b/includes/kohana/system/guide/kohana/mvc/models.md @@ -0,0 +1 @@ +Discuss models. What should go in a model, what shouldn't be in a model. Provide **very simple** examples using prepared statements, the query builder, as well as mention modeling libraries. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/mvc/views.md b/includes/kohana/system/guide/kohana/mvc/views.md new file mode 100644 index 0000000..77d757f --- /dev/null +++ b/includes/kohana/system/guide/kohana/mvc/views.md @@ -0,0 +1,161 @@ +# Views + +Views are files that contain the display information for your application. This is most commonly HTML, CSS and Javascript but can be anything you require such as XML or JSON for AJAX output. The purpose of views is to keep this information separate from your application logic for easy reusability and cleaner code. + +Views themselves can contain code used for displaying the data you pass into them. For example, looping through an array of product information and display each one on a new table row. Views are still PHP files so you can use any code you normally would. However, you should try to keep your views as "dumb" as possible and retreive all data you need in your controllers, then pass it to the view. + +# Creating View Files + +View files are stored in the `views` directory of the [filesystem](files). You can also create sub-directories within the `views` directory to organize your files. All of the following examples are reasonable view files: + + APPPATH/views/home.php + APPPATH/views/pages/about.php + APPPATH/views/products/details.php + MODPATH/error/views/errors/404.php + MODPATH/common/views/template.php + +## Loading Views + +[View] objects will typically be created inside a [Controller](mvc/controllers) using the [View::factory] method. Typically the view is then assigned as the [Request::$response] property or to another view. + + public function action_about() + { + $this->request->response = View::factory('pages/about'); + } + +When a view is assigned as the [Request::$response], as in the example above, it will automatically be rendered when necessary. To get the rendered result of a view you can call the [View::render] method or just type cast it to a string. When a view is rendered, the view file is loaded and HTML is generated. + + public function action_index() + { + $view = View::factory('pages/about'); + + // Render the view + $about_page = $view->render(); + + // Or just type cast it to a string + $about_page = (string) $view; + + $this->request->response = $about_page; + } + +## Variables in Views + +Once view has been loaded, variables can be assigned to it using the [View::set] and [View::bind] methods. + + public function action_roadtrip() + { + $view = View::factory('user/roadtrip') + ->set('places', array('Rome', 'Paris', 'London', 'New York', 'Tokyo')); + ->bind('user', $this->user); + + // The view will have $places and $user variables + $this->request->response = $view; + } + +[!!] The only difference between `set()` and `bind()` is that `bind()` assigns the variable by reference. If you `bind()` a variable before it has been defined, the variable will be created with a value of `NULL`. + +You can also assign variables directly to the View object. This is identical to calling `set()`; + + public function action_roadtrip() + { + $view = View::factory('user/roadtrip'); + + $view->places = array('Rome', 'Paris', 'London', 'New York', 'Tokyo'); + $view->user = $this->user; + + // The view will have $places and $user variables + $this->request->response = $view; + } + +### Global Variables + +An application may have several view files that need access to the same variables. For example, to display a page title in both the header of your template and in the body of the page content. You can create variables that are accessible in any view using the [View::set_global] and [View::bind_global] methods. + + // Assign $page_title to all views + View::bind_global('page_title', $page_title); + +If the application has three views that are rendered for the home page: `template`, `template/sidebar`, and `pages/home`. First, an abstract controller to create the template will be created: + + abstract class Controller_Website extends Controller_Template { + + public $page_title; + + public function before() + { + parent::before(); + + // Make $page_title available to all views + View::bind_global('page_title', $this->page_title); + + // Load $sidebar into the template as a view + $this->template->sidebar = View::factory('template/sidebar'); + } + + } + +Next, the home controller will extend `Controller_Website`: + + class Controller_Home extends Controller_Website { + + public function action_index() + { + $this->page_title = 'Home'; + + $this->template->content = View::factory('pages/home'); + } + + } + +## Views Within Views + +If you want to include another view within a view, there are two choices. By calling [View::factory] you can sandbox the included view. This means that you will have to provide all of the variables to the view using [View::set] or [View::bind]: + + // In your view file: + + // Only the $user variable will be available in "views/user/login.php" + bind('user', $user) ?> + +The other option is to include the view directly, which makes all of the current variables available to the included view: + + // In your view file: + + // Any variable defined in this view will be included in "views/message.php" + + +You can also assign a variable of your parent view to be the child view from within your controller. For example: + + // In your controller: + + public functin action_index() + { + $view = View::factory('common/template); + + $view->title = "Some title"; + $view->body = View::factory('pages/foobar'); + } + + // In views/common/template.php: + + + + <?php echo $title> + + + + + + + +Of course, you can also load an entire [Request] within a view: + + execute() ?> + +This is an example of \[HMVC], which makes it possible to create and read calls to other URLs within your application. + +## Differences From v2.x + +Unlike version 2.x of Kohana, the view is not loaded within the context of +the [Controller], so you will not be able to access `$this` as the controller +that loaded the view. Passing the controller to the view must be done explictly: + + $view->bind('controller', $this); \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/profiling.md b/includes/kohana/system/guide/kohana/profiling.md new file mode 100644 index 0000000..e7303c8 --- /dev/null +++ b/includes/kohana/system/guide/kohana/profiling.md @@ -0,0 +1,54 @@ +# Profiling + +Kohana provides a very simple way to display statistics about your application: + +1. Common [Kohana] method calls, such as [Kohana::find_file()]. +2. Requests. Including the main request, as well as any sub-requests. +3. [Database] queries +4. Average execution times for your application + +[!!] In order for profiling to work, the `profile` setting must be `TRUE` in your [Kohana::init()] call in your bootstrap. + +## Profiling your code + +You can easily add profiling to your own functions and code. This is done using the [Profiler::start()] function. The first parameter is the group, the second parameter is the name of the benchmark. + + public function foobar($input) + { + // Be sure to only profile if it's enabled + if (Kohana::$profiling === TRUE) + { + // Start a new benchmark + $benchmark = Profiler::start('Your Category', __FUNCTION__); + } + + // Do some stuff + + if (isset($benchmark)) + { + // Stop the benchmark + Profiler::stop($benchmark); + } + + return $something; + } + +## How to read the profiling report + +The benchmarks are sorted into groups. Each benchmark will show its name, how many times it was run (show in parenthesis after the benchmark name), and then the min, max, average, and total time and memory spent on that benchmark. The total column will have shaded backgrounds to show the relative times between benchmarks in the same group. + +At the very end is a group called "Application Execution". This keeps track of how long each execution has taken. The number in parenthesis is how many executions are being compared. It shows the fastest, slowest, and average time and memory usage of the last several requsets. The last box is the time and memory usage of the current request. + +((This could use a picture of a profiler with some database queries, etc. with annotations to point out each area as just described.)) + +## Displaying the profiler + +You can display or collect the current [profiler] statistics at any time: + + + +## Preview + +(This is the actual profiler stats for this page.) + +{{profiler/stats}} \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/requests.md b/includes/kohana/system/guide/kohana/requests.md new file mode 100644 index 0000000..82a2c6e --- /dev/null +++ b/includes/kohana/system/guide/kohana/requests.md @@ -0,0 +1,15 @@ +# Requests + +blah + +## The main request + +request::instance() gets the main request, you set the response in the bootstrap (usually), you use $request->status to send a 404 or other status, $request->headers to send headers, is_ajax, etc. + +## Subrequests + +TODO: This will talk about subrequests. + + + + diff --git a/includes/kohana/system/guide/kohana/routing.md b/includes/kohana/system/guide/kohana/routing.md new file mode 100644 index 0000000..47eed9a --- /dev/null +++ b/includes/kohana/system/guide/kohana/routing.md @@ -0,0 +1,240 @@ +# Routing + +Kohana provides a very powerful routing system. In essence, routes provide an interface between the urls and your controllers and actions. With the correct routes you could make almost any url scheme correspond to almost any arrangement of controllers, and you could change one without impacting the other. + +As mentioned in the [Request Flow](flow) section, a request is handled by the [Request] class, which will look for a matching [Route] and load the appropriate controller to handle that request. + +[!!] It is important to understand that **routes are matched in the order they are added**, and as soon as a URL matches a route, routing is essentially "stopped" and *the remaining routes are never tried*. Because the default route matches almost anything, including an empty url, new routes must be place before it. + +## Creating routes + +If you look in `APPPATH/bootstrap.php` you will see the "default" route as follows: + + Route::set('default', '((/(/)))') + ->defaults(array( + 'controller' => 'welcome', + 'action' => 'index', + )); + +[!!] The default route is simply provided as a sample, you can remove it and replace it with your own routes. + +So this creates a route with the name `default` that will match urls in the format of `((/(/)))`. + +Let's take a closer look at each of the parameters of [Route::set], which are `name`, `uri`, and an optional array `regex`. + +### Name + +The name of the route must be a **unique** string. If it is not it will overwrite the older route with the same name. The name is used for creating urls by reverse routing, or checking which route was matched. + +### URI + +The uri is a string that represents the format of urls that should be matched. The tokens surrounded with `<>` are *keys* and anything surrounded with `()` are *optional* parts of the uri. In Kohana routes, any character is allowed and treated literally aside from `()<>`. The `/` has no meaning besides being a character that must match in the uri. Usually the `/` is used as a static seperator but as long as the regex makes sense, there are no restrictions to how you can format your routes. + +Lets look at the default route again, the uri is `((/(/)))`. We have three keys or params: controller, action, and id. In this case, the entire uri is optional, so a blank uri would match and the default controller and action (set by defaults(), [covered below](#defaults)) would be assumed resulting in the `Controller_Welcome` class being loaded and the `action_index` method being called to handle the request. + +You can use any name you want for your keys, but the following keys have special meaning to the [Request] object, and will influence which controller and action are called: + + * **Directory** - The sub-directory of `classes/controller` to look for the controller (\[covered below]\(#directory)) + * **Controller** - The controller that the request should execute. + * **Action** - The action method to call. + +### Regex + +The Kohana route system uses [perl compatible regular expressions](http://perldoc.perl.org/perlre.html) in its matching process. By default each key (surrounded by `<>`) will match `[^/.,;?\n]++` (or in english: anything that is not a slash, period, comma, semicolon, question mark, or newline). You can define your own patterns for each key by passing an associative array of keys and patterns as an additional third argument to Route::set. + +In this example, we have controllers in two directories, `admin` and `affiliate`. Because this route will only match urls that begin with `admin` or `affiliate`, the default route would still work for controllers in `classes/controller`. + + Route::set('sections', '(/(/(/)))', + array( + 'directory' => '(admin|affiliate)' + )) + ->defaults(array( + 'controller' => 'home', + 'action' => 'index', + )); + +You can also use a less restrictive regex to match unlimited parameters, or to ignore overflow in a route. In this example, the url `foobar/baz/and-anything/else_that/is-on-the/url` would be routed to `Controller_Foobar::action_baz()` and the `"stuff"` parameter would be `"and-anything/else_that/is-on-the/url"`. If you wanted to use this for unlimited parameters, you could [explode](http://php.net/manual/en/function.explode.php) it, or you just ignore the overflow. + + Route::set('default', '((/(/)))', array('stuff' => '.*')) + ->defaults(array( + 'controller' => 'welcome', + 'action' => 'index', + )); + + +### Default values + +If a key in a route is optional (or not present in the route), you can provide a default value for that key by passing an associated array of keys and default values to [Route::defaults], chained after your [Route::set]. This can be useful to provide a default controller or action for your site, among other things. + +[!!] The `controller` and `action` key must always have a value, so they either need to be required in your route (not inside of parentheses) or have a default value provided. + +In the default route, all the keys are optional, and the controller and action are given a default. If we called an empty url, the defaults would fill in and `Controller_Welcome::action_index()` would be called. If we called `foobar` then only the default for action would be used, so it would call `Controller_Foobar::action_index()` and finally, if we called `foobar/baz` then neither default would be used and `Controller_Foobar::action_baz()` would be called. + +TODO: need an example here + +You can also use defaults to set a key that isn't in the route at all. + +TODO: example of either using directory or controller where it isn't in the route, but set by defaults + +### Directory + +## Examples + +TODO: a million billion examples, you can use the following as a guide for some routes to include: + + + + + +There are countless other possibilities for routes. Here are some more examples: + + /* + * Authentication shortcuts + */ + Route::set('auth', '', + array( + 'action' => '(login|logout)' + )) + ->defaults(array( + 'controller' => 'auth' + )); + + /* + * Multi-format feeds + * 452346/comments.rss + * 5373.json + */ + Route::set('feeds', '(/).', + array( + 'user_id' => '\d+', + 'format' => '(rss|atom|json)', + )) + ->defaults(array( + 'controller' => 'feeds', + 'action' => 'status', + )); + + /* + * Static pages + */ + Route::set('static', '.html', + array( + 'path' => '[a-zA-Z0-9_/]+', + )) + ->defaults(array( + 'controller' => 'static', + 'action' => 'index', + )); + + /* + * You don't like slashes? + * EditGallery:bahamas + * Watch:wakeboarding + */ + Route::set('gallery', '():', + array( + 'controller' => '[A-Z][a-z]++', + 'action' => '[A-Z][a-z]++', + )) + ->defaults(array( + 'controller' => 'Slideshow', + )); + + /* + * Quick search + */ + Route::set('search', ':', array('query' => '.*')) + ->defaults(array( + 'controller' => 'search', + 'action' => 'index', + )); + +## Request parameters + +The `directory`, `controller` and `action` can be accessed from the [Request] as public properties like so: + + // From within a controller: + $this->request->action; + $this->request->controller; + $this->request->directory; + + // Can be used anywhere: + Request::instance()->action; + Request::instance()->controller; + Request::instance()->directory; + +All other keys specified in a route can be accessed via [Request::param()]: + + // From within a controller: + $this->request->param('key_name'); + + // Can be used anywhere: + Request::instance()->param('key_name'); + +The [Request::param] method takes an optional second argument to specify a default return value in case the key is not set by the route. If no arguments are given, all keys are returned as an associative array. In addition, `action`, `controller` and `directory` are not accessible via [Request::param()]. + +For example, with the following route: + + Route::set('ads','ad/(/)') + ->defaults(array( + 'controller' => 'ads', + 'action' => 'index', + )); + +If a url matches the route, then `Controller_Ads::index()` will be called. You could access the parameters in two ways: + +First, any non-special parameters (parameters other than controller, action, and directory) in a route are passed as parameters to the action method in the order they appear in the route. Be sure to define a default value for optional parameters if you don't define them in the route's `->defaults()`. + + class Controller_Ads extends Controller { + public function action_index($ad, $affiliate = NULL) + { + + } + +Secondly, you can access the parameters using the `param()` method of the [Request] class. Again, remember to define a default value (via the second, optional parameter of [Request::param]) if you didn't in `->defaults()`. + + class Controller_Ads extends Controller { + public function action_index() + { + $ad = $this->request->param('ad'); + $affiliate = $this->request->param('affiliate',NULL); + } + + +## Where should routes be defined? + +The established convention is to either place your custom routes in the `MODPATH//init.php` file of your module if the routes belong to a module, or simply insert them into the `APPPATH/bootstrap.php` file (be sure to put them **above** the default route) if they are specific to the application. Of course, nothing stops you from including them from an external file, or even generating them dynamically. + +## A deeper look at how routes work + +TODO: talk about how routes are compiled + +## Creating URLs and links using routes + +Along with Kohana's powerful routing capabilities are included some methods for generating URLs for your routes' uris. You can always specify your uris as a string using [URL::site] to create a full URL like so: + + URL::site('admin/edit/user/'.$user_id); + +However, Kohana also provides a method to generate the uri from the route's definition. This is extremely useful if your routing could ever change since it would relieve you from having to go back through your code and change everywhere that you specified a uri as a string. Here is an example of dynamic generation that corresponds to the `feeds` route example from above: + + Route::get('feeds')->uri(array( + 'user_id' => $user_id, + 'action' => 'comments', + 'format' => 'rss' + )); + +Let's say you decided later to make that route definition more verbose by changing it to `feeds/(/).`. If you wrote your code with the above uri generation method you wouldn't have to change a single line! When a part of the uri is enclosed in parentheses and specifies a key for which there in no value provided for uri generation and no default value specified in the route, then that part will be removed from the uri. An example of this is the `(/)` part of the default route; this will not be included in the generated uri if an id is not provided. + +One method you might use frequently is the shortcut [Request::uri] which is the same as the above except it assumes the current route, directory, controller and action. If our current route is the default and the uri was `users/list`, we can do the following to generate uris in the format `users/view/$id`: + + $this->request->uri(array('action' => 'view', 'id' => $user_id)); + +Or if within a view, the preferable method is: + + Request::instance()->uri(array('action' => 'view', 'id' => $user_id)); + +TODO: examples of using html::anchor in addition to the above examples + +## Testing routes + +TODO: mention bluehawk's devtools module \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/security.md b/includes/kohana/system/guide/kohana/security.md new file mode 100644 index 0000000..2f90a04 --- /dev/null +++ b/includes/kohana/system/guide/kohana/security.md @@ -0,0 +1 @@ +General security concerns, like using the Security class, CSRF, and a brief intro to XSS, database security, etc. Also mention the security features that Kohana provides, like cleaning globals. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/security/cookies.md b/includes/kohana/system/guide/kohana/security/cookies.md new file mode 100644 index 0000000..3966f6c --- /dev/null +++ b/includes/kohana/system/guide/kohana/security/cookies.md @@ -0,0 +1,3 @@ +Discuss security of cookies, like changing the encryption key in the config. + +Not sure why I'm linking to this: \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/security/database.md b/includes/kohana/system/guide/kohana/security/database.md new file mode 100644 index 0000000..e6190b7 --- /dev/null +++ b/includes/kohana/system/guide/kohana/security/database.md @@ -0,0 +1,5 @@ +Discuss database security. + +How to avoid injection, etc. + +Not sure why I'm linking to this: \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/security/deploying.md b/includes/kohana/system/guide/kohana/security/deploying.md new file mode 100644 index 0000000..538533f --- /dev/null +++ b/includes/kohana/system/guide/kohana/security/deploying.md @@ -0,0 +1,81 @@ +Changes that should happen when you deploy. (Production) + +Security settings from: + + + + +## Setting up a production environment + +There are a few things you'll want to do with your application before moving into production. + +1. See the [Bootstrap page](bootstrap) in the docs. + This covers most of the global settings that would change between environments. + As a general rule, you should enable caching and disable profiling ([Kohana::init] settings) for production sites. + [Route::cache] can also help if you have a lot of routes. +2. Catch all exceptions in `application/bootstrap.php`, so that sensitive data is cannot be leaked by stack traces. + See the example below which was taken from Shadowhand's [wingsc.com source](http://github.com/shadowhand/wingsc). +3. Turn on APC or some kind of opcode caching. + This is the single easiest performance boost you can make to PHP itself. The more complex your application, the bigger the benefit of using opcode caching. + + /** + * Set the environment string by the domain (defaults to Kohana::DEVELOPMENT). + */ + Kohana::$environment = ($_SERVER['SERVER_NAME'] !== 'localhost') ? Kohana::PRODUCTION : Kohana::DEVELOPMENT; + /** + * Initialise Kohana based on environment + */ + Kohana::init(array( + 'base_url' => '/', + 'index_file' => FALSE, + 'profile' => Kohana::$environment !== Kohana::PRODUCTION, + 'caching' => Kohana::$environment === Kohana::PRODUCTION, + )); + + /** + * Execute the main request using PATH_INFO. If no URI source is specified, + * the URI will be automatically detected. + */ + $request = Request::instance($_SERVER['PATH_INFO']); + + try + { + // Attempt to execute the response + $request->execute(); + } + catch (Exception $e) + { + if (Kohana::$environment === Kohana::DEVELOPMENT) + { + // Just re-throw the exception + throw $e; + } + + // Log the error + Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e)); + + // Create a 404 response + $request->status = 404; + $request->response = View::factory('template') + ->set('title', '404') + ->set('content', View::factory('errors/404')); + } + + if ($request->send_headers()->response) + { + // Get the total memory and execution time + $total = array( + '{memory_usage}' => number_format((memory_get_peak_usage() - KOHANA_START_MEMORY) / 1024, 2).'KB', + '{execution_time}' => number_format(microtime(TRUE) - KOHANA_START_TIME, 5).' seconds'); + + // Insert the totals into the response + $request->response = str_replace(array_keys($total), $total, $request->response); + } + + + /** + * Display the request response. + */ + echo $request->response; + + diff --git a/includes/kohana/system/guide/kohana/security/encryption.md b/includes/kohana/system/guide/kohana/security/encryption.md new file mode 100644 index 0000000..8ba6ecf --- /dev/null +++ b/includes/kohana/system/guide/kohana/security/encryption.md @@ -0,0 +1 @@ +Discuss using encryption, including setting the encryption key in config. \ No newline at end of file diff --git a/includes/kohana/system/guide/kohana/security/validation.md b/includes/kohana/system/guide/kohana/security/validation.md new file mode 100644 index 0000000..94a868a --- /dev/null +++ b/includes/kohana/system/guide/kohana/security/validation.md @@ -0,0 +1,247 @@ +# Validation + +*This page needs to be reviewed for accuracy by the development team. Better examples would be helpful.* + +Validation can be performed on any array using the [Validate] class. Labels, filters, rules, and callbacks can be attached to a Validate object by the array key, called a "field name". + +labels +: A label is a human-readable version of the field name. + +filters +: A filter modifies the value of an field before rules and callbacks are run. + +rules +: A rule is a check on a field that returns `TRUE` or `FALSE`. If a rule + returns `FALSE`, an error will be added to the field. + +callbacks +: A callback is custom method that can access the entire Validate object. + The return value of a callback is ignored. Instead, the callback must + manually add an error to the object using [Validate::error] on failure. + +[!!] Note that [Validate] callbacks and [PHP callbacks](http://php.net/manual/language.pseudo-types.php#language.types.callback) are not the same. + +Using `TRUE` as the field name when adding a filter, rule, or callback will by applied to all named fields. + +**The [Validate] object will remove all fields from the array that have not been specifically named by a label, filter, rule, or callback. This prevents access to fields that have not been validated as a security precaution.** + +Creating a validation object is done using the [Validate::factory] method: + + $post = Validate::factory($_POST); + +[!!] The `$post` object will be used for the rest of this tutorial. This tutorial will show you how to validate the registration of a new user. + +### Default Rules + +Validation also comes with several default rules: + +Rule name | Function +------------------------- |------------------------------------------------- +[Validate::not_empty] | Value must be a non-empty value +[Validate::regex] | Match the value against a regular expression +[Validate::min_length] | Minimum number of characters for value +[Validate::max_length] | Maximum number of characters for value +[Validate::exact_length] | Value must be an exact number of characters +[Validate::email] | An email address is required +[Validate::email_domain] | Check that the domain of the email exists +[Validate::url] | Value must be a URL +[Validate::ip] | Value must be an IP address +[Validate::phone] | Value must be a phone number +[Validate::credit_card] | Require a credit card number +[Validate::date] | Value must be a date (and time) +[Validate::alpha] | Only alpha characters allowed +[Validate::alpha_dash] | Only alpha and hyphens allowed +[Validate::alpha_numeric] | Only alpha and numbers allowed +[Validate::digit] | Value must be an integer digit +[Validate::decimal] | Value must be a decimal or float value +[Validate::numeric] | Only numeric characters allowed +[Validate::range] | Value must be within a range +[Validate::color] | Value must be a valid HEX color +[Validate::matches] | Value matches another field value + +[!!] Any method that exists within the [Validate] class may be used as a validation rule without specifying a complete callback. For example, adding `'not_empty'` is the same as `array('Validate', 'not_empty')`. + +## Adding Filters + +All validation filters are defined as a field name, a method or function (using the [PHP callback](http://php.net/manual/language.pseudo-types.php#language.types.callback) syntax), and an array of parameters: + + $object->filter($field, $callback, $parameter); + +Filters modify the field value before it is checked using rules or callbacks. + +If we wanted to convert the "username" field to lowercase: + + $post->filter('username', 'strtolower'); + +If we wanted to remove all leading and trailing whitespace from *all* fields: + + $post->filter(TRUE, 'trim'); + +## Adding Rules + +All validation rules are defined as a field name, a method or function (using the [PHP callback](http://php.net/callback) syntax), and an array of parameters: + + $object->rule($field, $callback, $parameter); + +To start our example, we will perform validation on a `$_POST` array that contains user registration information: + + $post = Validate::factory($_POST); + +Next we need to process the POST'ed information using [Validate]. To start, we need to add some rules: + + $post + ->rule('username', 'not_empty') + ->rule('username', 'regex', array('/^[a-z_.]++$/iD')) + + ->rule('password', 'not_empty') + ->rule('password', 'min_length', array('6')) + ->rule('confirm', 'matches', array('password')) + + ->rule('use_ssl', 'not_empty'); + +Any existing PHP function can also be used a rule. For instance, if we want to check if the user entered a proper value for the SSL question: + + $post->rule('use_ssl', 'in_array', array(array('yes', 'no'))); + +Note that all array parameters must still be wrapped in an array! Without the wrapping array, `in_array` would be called as `in_array($value, 'yes', 'no')`, which would result in a PHP error. + +Any custom rules can be added using a [PHP callback](http://php.net/manual/language.pseudo-types.php#language.types.callback]: + + $post->rule('username', 'User_Model::unique_username'); + +[!!] Currently (v3.0.7) it is not possible to use an object for a rule, only static methods and functions. + +The method `User_Model::unique_username()` would be defined similar to: + + public static function unique_username($username) + { + // Check if the username already exists in the database + return ! DB::select(array(DB::expr('COUNT(username)'), 'total')) + ->from('users') + ->where('username', '=', $username) + ->execute() + ->get('total'); + } + +[!!] Custom rules allow many additional checks to be reused for multiple purposes. These methods will almost always exist in a model, but may be defined in any class. + +## Adding callbacks + +All validation callbacks are defined as a field name and a method or function (using the [PHP callback](http://php.net/manual/language.pseudo-types.php#language.types.callback) syntax): + + $object->callback($field, $callback); + +The user password must be hashed if it validates, so we will hash it using a callback: + + $post->callback('password', array($model, 'hash_password')); + +This would assume that the `$model->hash_password()` method would be defined similar to: + + public function hash_password(Validate $array, $field) + { + if ($array[$field]) + { + // Hash the password if it exists + $array[$field] = sha1($array[$field]); + } + } + +# A Complete Example + +First, we need a [View] that contains the HTML form, which will be placed in `application/views/user/register.php`: + + + +

    Some errors were encountered, please check the details you entered.

    +