diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..7b57b10e --- /dev/null +++ b/composer.json @@ -0,0 +1,7 @@ +{ + "require": { + "brandonwamboldt/utilphp": "^1.1", + "sergeytsalkov/meekrodb": "^2.3", + "league/plates": "^3.3" + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 00000000..742982da --- /dev/null +++ b/composer.lock @@ -0,0 +1,162 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "content-hash": "08d6fa0a77eca6b860aa39d42081eea9", + "packages": [ + { + "name": "brandonwamboldt/utilphp", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/brandonwamboldt/utilphp.git", + "reference": "36c32efc4f0679c05163464a550f45c8d83fe683" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brandonwamboldt/utilphp/zipball/36c32efc4f0679c05163464a550f45c8d83fe683", + "reference": "36c32efc4f0679c05163464a550f45c8d83fe683", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "satooshi/php-coveralls": "dev-master" + }, + "type": "library", + "autoload": { + "psr-0": { + "utilphp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brandon Wamboldt", + "email": "brandon.wamboldt@gmail.com" + } + ], + "description": "util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects", + "homepage": "https://github.com/brandonwamboldt/utilphp", + "keywords": [ + "collection", + "helpers", + "php", + "utility" + ], + "time": "2015-02-02T17:56:14+00:00" + }, + { + "name": "league/plates", + "version": "3.3.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/plates.git", + "reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/plates/zipball/b1684b6f127714497a0ef927ce42c0b44b45a8af", + "reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af", + "shasum": "" + }, + "require": { + "php": "^5.3 | ^7.0" + }, + "require-dev": { + "mikey179/vfsstream": "^1.4", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~1.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "League\\Plates\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jonathan Reinink", + "email": "jonathan@reinink.ca", + "role": "Developer" + } + ], + "description": "Plates, the native PHP template system that's fast, easy to use and easy to extend.", + "homepage": "http://platesphp.com", + "keywords": [ + "league", + "package", + "templates", + "templating", + "views" + ], + "time": "2016-12-28T00:14:17+00:00" + }, + { + "name": "sergeytsalkov/meekrodb", + "version": "v2.3", + "source": { + "type": "git", + "url": "https://github.com/SergeyTsalkov/meekrodb.git", + "reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/SergeyTsalkov/meekrodb/zipball/eb36858f1aff94ae1665900e681a1cfb78563ee1", + "reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1", + "shasum": "" + }, + "require": { + "php": ">=5.2.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "db.class.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0" + ], + "authors": [ + { + "name": "Sergey Tsalkov", + "email": "stsalkov@gmail.com" + } + ], + "description": "The Simple PHP/MySQL Library", + "homepage": "http://www.meekro.com", + "keywords": [ + "database", + "mysql", + "mysqli", + "pdo" + ], + "time": "2014-06-16T22:40:22+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [] +} diff --git a/d_setting/conf.orig.php b/d_setting/conf.orig.php index e566e043..a40cbf3c 100644 --- a/d_setting/conf.orig.php +++ b/d_setting/conf.orig.php @@ -1,6 +1,5 @@ queryFirstField("select plock from plock where no=1") != 0; } -function lock() { +function tryLock() { //NOTE: 게임 로직과 관련한 모든 insert, update 함수들은 lock을 거칠것을 권장함. $db = newDB(); //테이블 락 $db->query("lock tables plock write"); // 잠금 - $db->query("update plock set plock=1 where no=1"); + $isUnlocked = $db->queryFirstField("select plock from plock where no=1") != 0; + if($isUnlocked){ + $db->query("update plock set plock=1 where no=1"); + } + //테이블 언락 $db->query("unlock tables"); + + return $isUnlocked; } function unlock() { // 풀림 + //NOTE: unlock에는 table lock이 필요없는가? newDB()->query("update plock set plock=0 where no=1"); } @@ -2440,23 +2447,21 @@ function checkTurn($connect) { // 잦은 갱신 금지 현재 10초당 1회 if(!timeover($connect)) { return; } // 현재 처리중이면 접근 불가 - if(isLock()) { return; } + + // 파일락 획득 + //FIXME:이미 DB 테이블로 lock을 시도하는데 이게 따로 필요한가? + $fp = fopen('lock.txt', 'r'); + if(!flock($fp, LOCK_EX)) { + return; + } + + if(!tryLock()){ + return; + } $locklog[0] = "- checkTurn() : ".date('Y-m-d H:i:s')." : ".$_SESSION['p_id']; pushLockLog($connect, $locklog); - // 파일락 획득 - $fp = fopen('lock.txt', 'r'); - if(!flock($fp, LOCK_EX)) { return; } - // 세마포어 획득(윈도우서버 불가) - //$sema = @sem_get(fileinode('stylesheet.php')); - //if(!@sem_acquire($sema)) { echo "치명적 에러! 유기체에게 문의하세요!"; exit(1); } - - // 현재 처리중이면 접근 불가 - if(isLock()) { return; } - // 락 걸고 처리 - lock(); - // 파일락 해제 if(!flock($fp, LOCK_UN)) { return; } // 세마포어 해제 diff --git a/vendor/autoload.php b/vendor/autoload.php new file mode 100644 index 00000000..97db69ce --- /dev/null +++ b/vendor/autoload.php @@ -0,0 +1,7 @@ +=5.3.3" + } +} diff --git a/vendor/brandonwamboldt/utilphp/docs/css/docs.css b/vendor/brandonwamboldt/utilphp/docs/css/docs.css new file mode 100644 index 00000000..77993435 --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/docs/css/docs.css @@ -0,0 +1,168 @@ +body { + background: #f4f4f4 url('../images/background.png'); + color: #333; + font: 18px/30px "Droid Serif", "Helvetica Neue", Helvetica, Arial; +} + +a { + text-decoration: none; + color: #f00; + padding: 2px; +} + +a:hover { + background: #277585; + color: #fff; + border-radius: 3px; +} + +h1, h2, h3, h4, h5, h6 { + padding-top: 20px; +} + +h2 { + font-size: 40px; + font-weight: normal; + margin: 0 0 15px; +} + +p { + margin: 20px 0; + min-width: 550px; + max-width: 900px; +} + +table, tr, td { + margin: 0; padding: 0; +} + +td { + padding: 2px 12px 2px 0; +} + +ul { + list-style-type: circle; + padding: 0 0 0 20px; +} + +li { + width: 500px; + margin-bottom: 10px; +} + +code, pre, tt { + font-family: Monaco, Consolas, "Lucida Console", monospace; + font-size: 12px; + line-height: 18px; + font-style: normal; +} + +tt { + padding: 0px 3px; + background: #fff; + border: 1px solid #ddd; + zoom: 1; +} + +code { + margin-left: 20px; +} + +pre { + font-size: 12px; + padding: 12px; + background: #fff; + margin: 0px 0 30px; + border-radius: 0 0 2px 2px; + box-shadow: inset 0 0 0 1px rgba(0,0,0,.15); +} + +span.header { + font-size: 24px; + line-height: 30px; + border-left: 10px solid #ddd; + padding-left: 10px; +} + +.desc-text code { + margin-left: 0; + font-size: 18px; + color: #0E04C8; +} + +#sidebar { + background: #fff; + position: fixed; + top: 0; left: 0; bottom: 0; + width: 220px; + overflow-y: auto; + overflow-x: hidden; + padding: 5px 0 30px 10px; + border-right: 1px solid #bbb; + + box-shadow: 0 0 20px #ccc; + -webkit-box-shadow: 0 0 20px #ccc; + -moz-box-shadow: 0 0 20px #ccc; + -webkit-overflow-scrolling: touch; +} + +.toc_title, .toc_title:visited { + display: block; + color: #000; + margin-top: 15px; +} + +.toc_title:hover { + background: none; + color: #f00; +} + +.toc_title .version { + font-size: 12px; + font-weight: normal; +} + +.toc_section { + font-size: 14px; + line-height: 24px; + margin: 5px 0 0 0; + padding-left: 10px; + list-style-type: none; +} + +.toc_section li { + cursor: pointer; + margin: 0 0 3px 0; +} + +.toc_section li a { + text-decoration: none; + color: black; +} + +.toc_section li a:hover { + background: none; + color: #f00; +} + +.container { + min-width: 550px; + max-width: 1000px; + margin: 40px 0 50px 260px; +} + +#documentation section > article > p > code { + color: #999; +} + +#documentation section > article > p > code > .util_class { + color: #bbb; +} + +#documentation section > article > p > code > .func_name { + color: #0E04C8; +} + +#documentation section > article > p > code > .param { + color: #DA72F3; +} diff --git a/vendor/brandonwamboldt/utilphp/docs/favicon.png b/vendor/brandonwamboldt/utilphp/docs/favicon.png new file mode 100644 index 00000000..5f17cf1d Binary files /dev/null and b/vendor/brandonwamboldt/utilphp/docs/favicon.png differ diff --git a/vendor/brandonwamboldt/utilphp/docs/images/awesome_var_dump.jpg b/vendor/brandonwamboldt/utilphp/docs/images/awesome_var_dump.jpg new file mode 100644 index 00000000..a697c734 Binary files /dev/null and b/vendor/brandonwamboldt/utilphp/docs/images/awesome_var_dump.jpg differ diff --git a/vendor/brandonwamboldt/utilphp/docs/images/background.png b/vendor/brandonwamboldt/utilphp/docs/images/background.png new file mode 100644 index 00000000..1e6fddd7 Binary files /dev/null and b/vendor/brandonwamboldt/utilphp/docs/images/background.png differ diff --git a/vendor/brandonwamboldt/utilphp/docs/images/utility_logo.png b/vendor/brandonwamboldt/utilphp/docs/images/utility_logo.png new file mode 100644 index 00000000..434c7bc5 Binary files /dev/null and b/vendor/brandonwamboldt/utilphp/docs/images/utility_logo.png differ diff --git a/vendor/brandonwamboldt/utilphp/docs/index.html b/vendor/brandonwamboldt/utilphp/docs/index.html new file mode 100644 index 00000000..3b47bba7 --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/docs/index.html @@ -0,0 +1,1234 @@ + + + + + + + + + + + + + + + + util.php - The PHP programmers best friend - UtilityPHP + + + + + +
+

+ +

+ +

+ util.php is a collection of useful functions and snippets + that you need or could use every day. It's implemented as a class with static methods, to avoid conflicts with your + existing code-base. Just drop it in and start using it immediately. +

+ +

+ Included are 60+ functions that provide you with the ability to do common tasks much easier and more efficiently, + without having to find that one comment on php.net where you know its been done already. Access superglobals + without checking to see if certain indexes are set first and pass default values, use a nicely formatted var dump, + validate emails, generate random strings, flatten an array, pull a single column out of a multidimensional array + and much more. +

+ +

+ Although it's implemented as one giant class, util.php has extensive documentation and a full suite of unit tests + to avoid breaking backwards-compatibility unintentionally. +

+ +

+ The project is hosted on GitHub. + You can report bugs and discuss features on the + issues page, + or send tweets to @brandonwamboldt. +

+ +

Downloads (Right-click, and use "Save As")

+ +

+ Stable Version (1.1.0)
+ Unstable Version (master) +

+ +

Installation

+ + Server Requirements
+ + + + Standalone File
+ +

+ Simply drop util.php in any project and call include 'util.php'; in your project. + You can then access the Util class. +

+ + Composer
+ +

+ Add the following dependency to your composer.json: + +

"brandonwamboldt/utilphp": "1.1.*"
+ + When used with composer, the class is namespaced (\utilphp\util) instead of + just util. +

+ +
+

Debugging Functions

+ +
+
+

+ var_dump + + util::var_dump(mixed $var[, bool $return = FALSE]) + +

+ +

+ Nicely prints out the contents of a passed variable. Booleans are properly displayed as 'true' or 'false', + null values are shown as 'NULL', variable types are displayed, and arrays and objects are displayed as a + collapsible tree powered by JavaScript. +

+ +

Usage:

+ +
util::var_dump($var);
+ + +
+
+ +

Array/Object Functions

+ +
+
+

+ array_first + + util::array_first(array $array) + +

+ +

+ Retrieve the first value from an array. Can be run on function callbacks, and it will not modify the pointer + of the source array unlike most other methods of doing this. +

+ +

Usage:

+ +
util::array_first( ['a', 'b', 'c'] );
=> Returns 'a'
+
+ +
+

+ array_first_key + + util::array_first_key(array $array) + +

+ +

+ Retrieve the first key from an array. Can be run on function callbacks, and it will not modify the pointer of + the source array unlike most other methods of doing this. +

+ +

Usage:

+ +
util::array_first_key( $users );
=> Returns 'brandon'
+
+ +
+

+ array_flatten + + util::array_flatten(array $array[, bool $preserve_keys = TRUE]) + +

+ +

Flattens a multi-dimensional array into a one dimensional array

+ +

Usage:

+ +
util::array_flatten( [ 'a', 'b', [ 'c', 'd', 'e', [ 'f', 'g', [ [ [ [ 'h', 'i', 'j' ] ] ] ] ] ] ] );
+=> Returns [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]
+
+ +
+

+ array_get + + util::array_get($var[, mixed $default = NULL]) + +

+ +

Retrieve a value from an array, or return a given default if the index isn't set

+ +

Usage:

+ +
util::array_get($_POST['action'], 'index');
+=> If $_POST['action'] is set, returns its value, otherwise returns 'index'
+util::array_get($_POST['action']['do'], 'index');
+=> Returns the value of $_POST['action']['do'] or 'index'
+
+ +
+

+ array_last + + util::array_last(array $array) + +

+ +

+ Retrieve the last value from an array. Can be run on function callbacks, and it will not modify the pointer + of the source array unlike most other methods of doing this. +

+ +

Usage:

+ +
util::array_last( [ 'a', 'b', 'c'] );
+=> Returns 'c'
+
+ +
+

+ array_last_key + + util::array_last_key(array $array) + +

+ +

+ Retrieve the last key from an array. Can be run on function callbacks, and it will not modify the pointer of + the source array unlike most other methods of doing this. +

+ +

Usage:

+ +
util::array_last_key( $users );
+=> Returns 'zane'
+
+ +
+

+ array_map_deep + + util::array_map_deep(array $array, callable $callback[, bool $on_nonscalar = FALSE]) + +

+ +

+ Returns an array containing all the elements of $array after applying the callback function to each one recursively. + Particularly useful for avoiding errors when calling functions that only accept scalar values on an array that could + contain nested arrays, such as $_GET or $_POST. +

+ +

Usage:

+ +
util::array_map_deep($_POST, 'htmlentities');
+=> Recursively escapes each scalar value in $_POST
+util::array_map_deep($_POST, 'htmlentities', TRUE);
+=> Recursively escapes each value in $_POST regardless of its type
+
+ +
+

+ array_pluck + + util::array_pluck(array $array, string $field[, bool $preserve_keys, bool $remove_nomatches]) + +

+ +

+ Replaces each value in an array with the specified field of the array or object that used to be the value. Very + useful when you have an array of objects or arrays from a database, and you only want one specific field. For + example, you want an array of emails from an array of users. +

+ +

Usage:

+ +
util::array_pluck([['val' => 1], ['val' => 2], ['val' => 3]], 'val');
+=> Returns [1, 2, 3]
+util::array_pluck($users, 'email');
+=> Returns an array of email addresses for each user
+
+ +
+

+ array_search_deep + + util::array_search_deep(array $array, mixed $search[, string $field = FALSE]) + +

+ +

+ Allows you to search for a value in an array of arrays or an array of objects, and return the key of the value + that matches the search criteria. If $field is unspecified, the entire array/object is searched. +

+ +

Usage:

+ +
util::array_search_deep($_POST, 'delete_post');
+=> Might return 'do' if $_POST['do']['action'] = 'delete_post'
+util::array_search_deep($users, 'rogue_coder', 'username');
+=> Might return 5 if $users[5]->username = 'rogue_coder'
+
+ +
+

+ array_clean + + util::array_clean(array $array) + +

+ +

+ Remove all null/empty/false values from the given array. +

+ +

Usage:

+ +
util::array_clean( array( 'a', 'b', '', null, false, 0) );
=> Returns array('a', 'b');
+
+ +
+ +

URL Functions

+ +
+
+

+ add_query_arg + + util::add_query_arg() + +

+ +

Adds one ore more query args to the query string of the current URL or a given URL

+ +

Usage:

+ +
util::add_query_arg( 'user', '5', '/admin/users?action=edit' );
+=> Returns '/admin/users?action=edit&user=5'
+util::add_query_arg( [ 'user' => 5, 'action' => 'edit' ], '/admin/users' );
+=> Returns '/admin/users?user=5&action=edit'
+
+ +
+

+ get_current_url + + util::get_current_url() + +

+ +

Returns the current URL with hostname

+ +

Usage:

+ +
util::get_current_url();
+=> Returns 'http://brandonwamboldt.ca/utilphp/'
+
+ +
+

+ is_https + + util::is_https() + +

+ +

Returns true if the current page is being loaded over https, false if it isn't

+ +

Usage:

+ +
util::is_https();
+=> Returns false
+
+ +
+

+ http_build_url + + util::http_build_url([mixed $url[, mixed $parts[, int $flags = HTTP_URL_REPLACE[, array &amo;$new_url]]]]) + +

+ +

+ Pure PHP implementation/polyfill for http_build_url + which requires pecl_http to be installed. +

+ +

Usage:

+ +
echo util::http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
+    array(
+        "scheme" => "ftp",
+        "host" => "ftp.example.com",
+        "path" => "files/current/",
+        "query" => "a=c"
+    ),
+    HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
+);
+ +

The above example will output:

+ +
ftp://ftp.example.com/pub/files/current/?a=c
+
+ +
+

+ is_https + + util::is_https() + +

+ +

Returns true if the current page is being loaded over https, false if it isn't

+ +

Usage:

+ +
util::is_https();
+=> Returns false
+
+ +
+

+ remove_query_arg + + util::remove_query_arg( array|string $query_args[, string $url]) + +

+ +

Removes one ore more query args from the query string of the current URL or a given URL

+ +

Usage:

+ +
util::remove_query_arg( 'action', '/admin/users?action=edit&user=5' );
+=> Returns '/admin/users?user=5'
+util::remove_query_arg( [ 'user', 'action'], '/admin/users?action=edit&user=5' );
+=> Returns '/admin/users'
+
+ +
+

+ slugify + + util::slugify(string $string[, string $separator = "-", bool $css_mode = FALSE]) + +

+ +

+ Generate a string safe for use in URLs from any given string. Converts any accent characters + to their equivalent normal characters and converts any other non-alphanumeric characters to + dashes, then converts any sequence of two or more dashes to a single dash. This function + generates slugs safe for use as URLs, and if you pass TRUE as the second parameter, it will + create strings safe for use as CSS classes or IDs. +

+ +

Usage:

+ +
util::slugify('This is a random --string with an Ãccent');
+=> Returns 'this-is-a-random-string-with-an-accent'
+util::slugify('Another String', '.');
+=> Returns 'another.string'
+
+
+ +

String Functions

+ +
+
+

+ htmlentities + + util::htmlentities(string $string[, bool $preserve_encoded_entities = FALSE]) + +

+ +

+ Executes htmlentities with ENT_QUOTES set by default. However, if you pass TRUE as + the second parameter, it will not re-encode entities that are already encoded. +

+ +

Usage:

+ +
util::htmlentities('this string < this string', TRUE);
+=> Returns 'this string < this string'
+
+ +
+

+ htmlspecialchars + + util::htmlspecialchars(string $string[, bool $preserve_encoded_entities = FALSE]) + +

+ +

+ Executes htmlspecialchars with ENT_QUOTES set by default. However, if you pass TRUE as + the second parameter, it will not re-encode entities that are already encoded. +

+ +

Usage:

+ +
util::htmlspecialchars('this string < this string', TRUE);
+=> Returns 'this string < this string'
+
+ +
+

+ linkify + + util::linkify(string $text) + +

+ +

Find's any URLs in the specified text and wraps them with HTML anchor tags

+ +

Usage:

+ +
util::linkify('this string has a link to www.google.com');
+=> Returns 'this string has a link to <a href="http://wwww.google.com/">www.google.com</a>'
+
+ +
+

+ match_string + + util::match_string(string $pattern, string $string[, bool $caseSensitive = true]) + +

+ +

+ Check if a string matches a given pattern. You can use '*' as a wildcard character. +

+ +

Usage:

+ +
util::match_string("test/*", "test/my/test");
+=> Returns true
+util::match_string("test/", "test/my/test");
+=> Returns false
+
+ +
+

+ random_string + + util::random_string(int $length[, bool $human_friendly = TRUE, bool $include_symbols = FALSE, bool $no_duplicate_chars = FALSE]) + +

+ +

+ Generates a random string of the specified length. Human friendly mode + will exclude characters that can be confused with other characters, such + as 0 (zero) and O (capital o), 1 (one) and l (lowercase L). +

+ +

Usage:

+ +
util::random_string(8);
+=> Returns 'a6BiF4UW'
+
+ +
+

+ number_to_word + + util::number_to_word(int|float $number) + +

+ +

Converts a number into its text equivalent. For example, 56 becomes fifty-six.

+ +
util::number_to_word(512.5);
+=> Returns 'five hundred and twelve point five'
+
+ +
+

+ ordinal + + util::ordinal(int $number) + +

+ +

Returns the ordinal version of a number (appends th, st, nd, rd)

+ +

Usage:

+ +
util::ordinal(22);
+=> Returns '22nd'
+
+ +
+

+ remove_accents + + util::remove_accents(string $string) + +

+ +

Converts all accent characters to their ASCII equivalents

+ +

Usage:

+ +
util::remove_accents('Àccent');
+=> Returns 'Accent'
+
+ +
+

+ secure_random_string + + util::secure_random_string(int $length) + +

+ +

Generate a random string of characters. Will attempt to use a secure source (openssl).

+ +

Usage:

+ +
util::secure_random_string(16);
+=> Returns '5bB1RJH0cQhNjviT'
+
+ +
+

+ seems_utf8 + + util::seems_utf8(string $string) + +

+ +

Checks to see if a given string is UTF-8 encoded/safe

+ +

Usage:

+ +
util::seems_utf8('This is some random string user input');
+=> Returns true
+
+ +
+

+ safe_truncate + + util::safe_truncate(string $string, int $length[, string $append = '...']) + +

+ +

Truncate a string to a specified length without cutting a word off

+ +

Usage:

+ +
util::safe_truncate('The quick brown fox jumps over the lazy dog', 24);
+=> Returns 'The quick brown fox...'
+
+ +
+

+ size_format + + util::size_format(int $bytes[, int $decimals = 0]) + +

+ +

Formats an integer as a human friendly size string, such as 4 KiB.

+ +

Usage:

+ +
util::size_format( 25151251, 2 );
+=> Returns '23.99 MiB'
+
+ +
+

+ str_to_bool + + util::str_to_bool(string $string) + +

+ +

Converts a string to boolean, looking for yes/no words like 'yes', 'no', 'true', 'false', 'y', 'n', etc

+ +

Usage:

+ +
util::str_to_bool('yes');
+=> Returns true
+
+ +
+

+ zero_pad + + util::zero_pad(int $number, int $length) + +

+ +

Pads a given number with zeroes on the left

+ +

Usage:

+ +
util::zero_pad(341, 8);
+=> Returns '00000341'
+
+ +
+

+ strip_space + + util::strip_space(string $string) + +

+ +

Strip all withspace from the given string

+ +

Usage:

+ +
util::strip_space(' The quick brown fox jumps over the lazy dog ');
+=> Returns 'Thequickbrownfoxjumpsoverthelazydog'
+
+ +
+

+ sanitize_string + + util::sanitize_string(string $string) + +

+ +

+ Sanitize a string by performing the following operation : +

    +
  • Remove accents
  • +
  • Lower the string
  • +
  • Remove punctuation characters
  • +
  • Strip whitespaces
  • +
+ +

+

Usage:

+ +
util::sanitize_string(' Benoit! à New-York? j’ai perçu 1 % : Qu’as-tu "gagné" chez M. V. Noël? Dix francs.');
+=> Returns 'benoitanewyorkjaipercu1quastugagnechezmvnoeldixfrancs'
+
+
+ +

Files

+ +
+
+

+ full_permissions + + util::full_permissions(string $file) + +

+ +

Returns the file permissions as a nice string, like -rw-r--r--

+ +

Usage:

+ +
util::full_permissions('/etc/passwd');
+=> Returns '-rw-r--r--'
+
+ +
+

+ rmdir + + util::rmdir(string $dir[, bool $traverseSymlinks = false]) + +

+ +

Recursively deletes a directories (including all contents).

+ +

Usage:

+ +
util::rmdir('/tmp/working/dir');
+=> Returns true
+
+
+ +

Serialization

+ +
+
+

+ is_serialized + + util::is_serialized(mixed $data) + +

+ +

Checks to see if a given variable is a seralized data structure

+ +

Usage:

+ +
util::is_serialized( 'a:0:{}' );
+=> Returns true
+
+ +
+

+ maybe_serialize + + util::maybe_serialize(mixed $data) + +

+ +

Serialize data, if needed to store in plaintext (Arrays or objects)

+ +

Usage:

+ +
util::maybe_serialize( 5 );
+=> Returns 5
+util::maybe_serialize( array() );
+=> Returns 'a:0:{}'
+
+ +
+

+ maybe_unserialize + + util::maybe_unserialize(mixed $data) + +

+ +

Unserialize data, if it's a serialized string

+ +

Usage:

+ +
util::maybe_unserialize(5);
+=> Returns 5
+util::maybe_unserialize("a:0:{}");
+=> Returns array()
+
+ +
+

+ fix_broken_serialization + + util::fix_broken_serialization(mixed $data) + +

+ +

+ Attempt to fix a broken serialization string (e.g. where string offsets are incorrect). Can fix + errors that frequently occur with mismatched character sets or higher-than-ASCII characters. +

+ +

Usage:

+ +
util::fix_broken_serialization('a:1:{s:4:"test";s:4:"abc";}');
+=> Returns 'a:1:{s:4:"test";s:3:"abc";}'
+
+
+ +

Other

+ +
+
+

+ force_download + + util::force_download(string $filename, string $content = FALSE) + +

+ +

+ Transmit headers that force a browser to display the download file dialog. Cross + browser compatible. Only fires if headers have not already been sent. +

+ +

Usage:

+ +
util::force_download( 'export.csv', file_get_contents( 'securefile.csv' ) );
+=> The user will be prompted to download the file
+
+ +
+

+ get_client_ip + + util::get_client_ip(bool $trust_proxy_headers = FALSE) + +

+ +

+ Returns the IP address of the client. Only enable $trust_proxy_headers if your server is behind a proxy + that sets the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR headers. +

+ +

Usage:

+ +
util::get_client_ip();
+=> Returns '12.123.12.100'
+
+ +
+

+ get_gravatar + + util::get_gravatar(string $email, int $size = 32) + +

+ +

Return the URL to a user's gravatar

+ +

Usage:

+ +
util::get_gravatar('brandon.wamboldt@gmail.com');
+=> Returns 'http://www.gravatar.com/avatar/46679faeb6780ecb1ea57527fdc66eb3?s=32'
+
+ +
+

+ human_time_diff + + util::human_time_diff(int $from, int $to = '', int $as_text = FALSE, string $suffix = ' ago') + +

+ +

Converts a unix timestamp to a relative time string, such as "3 days ago" or "2 weeks ago"

+ +

Usage:

+ +
util::human_time_diff(time() - 7400);
+=> Returns '2 hours ago'
+util::human_time_diff(time() - 7400, '', TRUE);
+=> Returns 'two hours ago'
+
+ +
+

+ nocache_headers + + util::nocache_headers(mixed $data) + +

+ +

Sets the headers to prevent caching for the different browsers

+ +

+ Different browsers support different nocache headers, so several headers must be sent + so that all of them get the point that no caching should occur +

+ +

Usage:

+ +
util::nocache_headers();
+
+ +
+

+ utf8_headers + + util::utf8_headers(mixed $content_type = 'text/html') + +

+ +

Transmit UTF-8 content headers if the headers haven't already been sent

+ +

Usage:

+ +
util::utf8_headers();
+
+ +
+

+ validate_email + + util::validate_email(string $possible_email) + +

+ +

Validate an email address

+ +

Usage:

+ +
util::validate_email( 'brandon.wamboldt@gmail.com' );
+=> Returns true
+util::validate_email( 'not an email' );
+=> Returns false
+
+
+ +

Constants

+ +
+
+

+ SECONDS_IN_A_MINUTE + + util::SECONDS_IN_A_MINUTE + +

+ +

The number of seconds in a minute, useful for making code more verbose

+
+ +
+

+ SECONDS_IN_AN_HOUR + + util::SECONDS_IN_AN_HOUR + +

+ +

The number of seconds in an hour, useful for making code more verbose

+
+ +
+

+ SECONDS_IN_A_DAY + + util::SECONDS_IN_A_DAY + +

+ +

The number of seconds in a day, useful for making code more verbose

+
+ +
+

+ SECONDS_IN_A_WEEK + + util::SECONDS_IN_A_WEEK + +

+ +

The number of seconds in a week (7 days), useful for making code more verbose

+
+ +
+

+ SECONDS_IN_A_MONTH + + util::SECONDS_IN_A_MONTH + +

+ +

The number of seconds in a month (30 days), useful for making code more verbose

+
+ +
+

+ SECONDS_IN_A_YEAR + + util::SECONDS_IN_A_YEAR + +

+ +

The number of seconds in a year (365 days), useful for making code more verbose

+
+
+ +

Change Log

+ + + +

+ 1.1.0
+ + This release introduces a deprecation notice for slugify(), please update your code.

+ + - Added a cryptographically secure random string function secure_random_string. Thanks to @abhimanyusharma003 via Pull Request #53
+ - Added limit_characters and limit_words functions. Thanks to @abhimanyusharma003 via Pull Request #55
+ - Added rmdir method to recursively delete a directory. Thanks to @ARACOOOL via Pull Request #56
+ - Added set_executable, set_readable, set_writable, directory_size, directory_contents and get_user_dir functions. Thanks to @sergserg via Pull Request #70
+ - Changed parameter ordering for slugify, $css_mode is now the third argument. For backwards compatibility, the old order will still work but it will generate an E_USER_DEPRECATED warning. Thanks to @abhimanyusharma003 via Pull Request #71
+ - Added match_string method. Thanks to @abhimanyusharma003 via Pull Request #72
+ - Renamed internal methods (protected ones) for PSR-2 compliance
+ - General performance improvements, code quality improvements, and increased unit test coverage (special thanks to @hopeseekr for getting us near 100% coverage)
+

+ +

+ 1.0.7
+ - Added fix_broken_serialization to fix broken serialized strings (Thanks to @hopeseekr via Pull Request #48)
+ - Fixed get_current_url appending port 80 or 443 when not needed (Thanks to @scottchiefbaker via Pull Request #49)
+ - var_dump can now handle recursive data structures without crashing
+ - var_dump code was minified and cleaned up
+ - array_flatten was optimized (thanks to @hopeseekr via Pull Request #47)
+ - remove_accents was completely rewritten and is now ~4x faster
+

+ +

+ 1.0.6
+ - Added start_with function
+ - Added ends_with function
+ - Added str_contains function
+ - Added str_icontains function
+ - Added get_file_ext function
+ - Fixing permissions on the files & directories
+ - Fixing a bug with the include path of util.php
+

+ +

+ 1.0.5
+ - Issue #29 Fixed error in var_dump if mbstring extension wasn't present
+ - Adding Composer support
+ - Updating license from GPL to MIT
+ - Adding Changelog to project
+ - Bumping minimum version to PHP 5.3.3
+

+ +

+ 1.0.4
+ - Issue #22 Removed all superglobal *_get functions, you can use the modified array_get now
+ - Issue #22 Modifed the behaviour of array_get, see documentation
+ - Pull Request #21 Added multibyte support to html* functions
+ - Issue #9 Removed the str_to_utf8 function
+ - Issue #3 Removed the absint function
+ - Removed declare() from util.php to avoid errors
+ - Updated PHPUnit tests to use PHPUnit 3.6 +

+ +

+ 1.0.3
+ - Issue #16 Improved performance of slugify
+ - Issue #14 Modified the regex for seems_utf8 to be more accurate
+ - Issue #13 Changed validate_email to be wrapper for filter_var
+ - Added 'ok' to the list of yes words for str_to_bool
+ - str_to_bool matches no followed by any number of 'o's +

+ +

+ 1.0.2
+ - Issue #12 get_current_url now includes the port and user/password if required
+ - Issue #11 human_time_diff now uses the DateTime functions
+ - Issue #10 is_https no longer checks the port as well +

+ +

+ 1.0.1
+ - Issue #7 Added the $trust_proxy_headers parameter to get_client_ip
+ - Issue #6 Removed is_isset as the function did not work as intended
+ - Issue #6 Removed is_empty as it is redundant, use ! with function calls instead
+ - Fixed a bug with get_gravatar +

+ +

+ 1.0.0
+ Initial release of util.php. +

+
+
+ + + diff --git a/vendor/brandonwamboldt/utilphp/phpunit.xml.dist b/vendor/brandonwamboldt/utilphp/phpunit.xml.dist new file mode 100644 index 00000000..d4b9366c --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/phpunit.xml.dist @@ -0,0 +1,25 @@ + + + + + ./tests + + + + + ./src + + + + + + \ No newline at end of file diff --git a/vendor/brandonwamboldt/utilphp/src/utilphp/util.php b/vendor/brandonwamboldt/utilphp/src/utilphp/util.php new file mode 100644 index 00000000..0932d7d1 --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/src/utilphp/util.php @@ -0,0 +1,2535 @@ + + * @link http://github.com/brandonwamboldt/utilphp/ Official Documentation + */ +class util +{ + /** + * A constant representing the number of seconds in a minute, for + * making code more verbose + * + * @var integer + */ + const SECONDS_IN_A_MINUTE = 60; + + /** + * A constant representing the number of seconds in an hour, for making + * code more verbose + * + * @var integer + */ + const SECONDS_IN_A_HOUR = 3600; + const SECONDS_IN_AN_HOUR = 3600; + + /** + * A constant representing the number of seconds in a day, for making + * code more verbose + * + * @var integer + */ + const SECONDS_IN_A_DAY = 86400; + + /** + * A constant representing the number of seconds in a week, for making + * code more verbose + * + * @var integer + */ + const SECONDS_IN_A_WEEK = 604800; + + /** + * A constant representing the number of seconds in a month (30 days), + * for making code more verbose + * + * @var integer + */ + const SECONDS_IN_A_MONTH = 2592000; + + /** + * A constant representing the number of seconds in a year (365 days), + * for making code more verbose + * + * @var integer + */ + const SECONDS_IN_A_YEAR = 31536000; + + /** + * URL constants as defined in the PHP Manual under "Constants usable with + * http_build_url()". + * + * @see http://us2.php.net/manual/en/http.constants.php#http.constants.url + */ + const HTTP_URL_REPLACE = 1; + const HTTP_URL_JOIN_PATH = 2; + const HTTP_URL_JOIN_QUERY = 4; + const HTTP_URL_STRIP_USER = 8; + const HTTP_URL_STRIP_PASS = 16; + const HTTP_URL_STRIP_AUTH = 32; + const HTTP_URL_STRIP_PORT = 64; + const HTTP_URL_STRIP_PATH = 128; + const HTTP_URL_STRIP_QUERY = 256; + const HTTP_URL_STRIP_FRAGMENT = 512; + const HTTP_URL_STRIP_ALL = 1024; + + /** + * A collapse icon, using in the dump_var function to allow collapsing + * an array or object + * + * @var string + */ + public static $icon_collapse = 'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAMAAADXT/YiAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3MjlFRjQ2NkM5QzJFMTExOTA0MzkwRkI0M0ZCODY4RCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpFNzFDNDQyNEMyQzkxMUUxOTU4MEM4M0UxRDA0MUVGNSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpFNzFDNDQyM0MyQzkxMUUxOTU4MEM4M0UxRDA0MUVGNSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo3NDlFRjQ2NkM5QzJFMTExOTA0MzkwRkI0M0ZCODY4RCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo3MjlFRjQ2NkM5QzJFMTExOTA0MzkwRkI0M0ZCODY4RCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuF4AWkAAAA2UExURU9t2DBStczM/1h16DNmzHiW7iNFrypMvrnD52yJ4ezs7Onp6ejo6P///+Tk5GSG7D9h5SRGq0Q2K74AAAA/SURBVHjaLMhZDsAgDANRY3ZISnP/y1ZWeV+jAeuRSky6cKL4ryDdSggP8UC7r6GvR1YHxjazPQDmVzI/AQYAnFQDdVSJ80EAAAAASUVORK5CYII='; + + /** + * A collapse icon, using in the dump_var function to allow collapsing + * an array or object + * + * @var string + */ + public static $icon_expand = 'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAMAAADXT/YiAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3MTlFRjQ2NkM5QzJFMTExOTA0MzkwRkI0M0ZCODY4RCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpFQzZERTJDNEMyQzkxMUUxODRCQzgyRUNDMzZEQkZFQiIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpFQzZERTJDM0MyQzkxMUUxODRCQzgyRUNDMzZEQkZFQiIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo3MzlFRjQ2NkM5QzJFMTExOTA0MzkwRkI0M0ZCODY4RCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo3MTlFRjQ2NkM5QzJFMTExOTA0MzkwRkI0M0ZCODY4RCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PkmDvWIAAABIUExURU9t2MzM/3iW7ubm59/f5urq85mZzOvr6////9ra38zMzObm5rfB8FZz5myJ4SNFrypMvjBStTNmzOvr+mSG7OXl8T9h5SRGq/OfqCEAAABKSURBVHjaFMlbEoAwCEPRULXF2jdW9r9T4czcyUdA4XWB0IgdNSybxU9amMzHzDlPKKu7Fd1e6+wY195jW0ARYZECxPq5Gn8BBgCr0gQmxpjKAwAAAABJRU5ErkJggg=='; + + private static $hasArray = false; + + /** + * Map of special non-ASCII characters and suitable ASCII replacement + * characters. + * + * Part of the URLify.php Project + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + */ + public static $maps = array( + 'de' => array(/* German */ + 'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss', + 'ẞ' => 'SS' + ), + 'latin' => array( + 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A','Ă' => 'A', 'Æ' => 'AE', 'Ç' => + 'C', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', + 'Ï' => 'I', 'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => + 'O', 'Ő' => 'O', 'Ø' => 'O','Ș' => 'S','Ț' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', + 'Ý' => 'Y', 'Þ' => 'TH', 'ß' => 'ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => + 'a', 'å' => 'a', 'ă' => 'a', 'æ' => 'ae', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', + 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => + 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o', 'ø' => 'o', 'ș' => 's', 'ț' => 't', 'ù' => 'u', 'ú' => 'u', + 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th', 'ÿ' => 'y' + ), + 'latin_symbols' => array( + '©' => '(c)' + ), + 'el' => array(/* Greek */ + 'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8', + 'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p', + 'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w', + 'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's', + 'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i', + 'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8', + 'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P', + 'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W', + 'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I', + 'Ϋ' => 'Y' + ), + 'tr' => array(/* Turkish */ + 'ş' => 's', 'Ş' => 'S', 'ı' => 'i', 'İ' => 'I', 'ç' => 'c', 'Ç' => 'C', 'ü' => 'u', 'Ü' => 'U', + 'ö' => 'o', 'Ö' => 'O', 'ğ' => 'g', 'Ğ' => 'G' + ), + 'ru' => array(/* Russian */ + 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh', + 'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', + 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', + 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu', + 'я' => 'ya', + 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh', + 'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', + 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', + 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu', + 'Я' => 'Ya', + '№' => '' + ), + 'uk' => array(/* Ukrainian */ + 'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G', 'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g' + ), + 'cs' => array(/* Czech */ + 'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u', + 'ž' => 'z', 'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', + 'Ů' => 'U', 'Ž' => 'Z' + ), + 'pl' => array(/* Polish */ + 'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z', + 'ż' => 'z', 'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'O', 'Ś' => 'S', + 'Ź' => 'Z', 'Ż' => 'Z' + ), + 'ro' => array(/* Romanian */ + 'ă' => 'a', 'â' => 'a', 'î' => 'i', 'ș' => 's', 'ț' => 't', 'Ţ' => 'T', 'ţ' => 't' + ), + 'lv' => array(/* Latvian */ + 'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n', + 'š' => 's', 'ū' => 'u', 'ž' => 'z', 'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', + 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N', 'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z' + ), + 'lt' => array(/* Lithuanian */ + 'ą' => 'a', 'č' => 'c', 'ę' => 'e', 'ė' => 'e', 'į' => 'i', 'š' => 's', 'ų' => 'u', 'ū' => 'u', 'ž' => 'z', + 'Ą' => 'A', 'Č' => 'C', 'Ę' => 'E', 'Ė' => 'E', 'Į' => 'I', 'Š' => 'S', 'Ų' => 'U', 'Ū' => 'U', 'Ž' => 'Z' + ), + 'vn' => array(/* Vietnamese */ + 'Á' => 'A', 'À' => 'A', 'Ả' => 'A', 'Ã' => 'A', 'Ạ' => 'A', 'Ă' => 'A', 'Ắ' => 'A', 'Ằ' => 'A', 'Ẳ' => 'A', 'Ẵ' => 'A', 'Ặ' => 'A', 'Â' => 'A', 'Ấ' => 'A', 'Ầ' => 'A', 'Ẩ' => 'A', 'Ẫ' => 'A', 'Ậ' => 'A', + 'á' => 'a', 'à' => 'a', 'ả' => 'a', 'ã' => 'a', 'ạ' => 'a', 'ă' => 'a', 'ắ' => 'a', 'ằ' => 'a', 'ẳ' => 'a', 'ẵ' => 'a', 'ặ' => 'a', 'â' => 'a', 'ấ' => 'a', 'ầ' => 'a', 'ẩ' => 'a', 'ẫ' => 'a', 'ậ' => 'a', + 'É' => 'E', 'È' => 'E', 'Ẻ' => 'E', 'Ẽ' => 'E', 'Ẹ' => 'E', 'Ê' => 'E', 'Ế' => 'E', 'Ề' => 'E', 'Ể' => 'E', 'Ễ' => 'E', 'Ệ' => 'E', + 'é' => 'e', 'è' => 'e', 'ẻ' => 'e', 'ẽ' => 'e', 'ẹ' => 'e', 'ê' => 'e', 'ế' => 'e', 'ề' => 'e', 'ể' => 'e', 'ễ' => 'e', 'ệ' => 'e', + 'Í' => 'I', 'Ì' => 'I', 'Ỉ' => 'I', 'Ĩ' => 'I', 'Ị' => 'I', 'í' => 'i', 'ì' => 'i', 'ỉ' => 'i', 'ĩ' => 'i', 'ị' => 'i', + 'Ó' => 'O', 'Ò' => 'O', 'Ỏ' => 'O', 'Õ' => 'O', 'Ọ' => 'O', 'Ô' => 'O', 'Ố' => 'O', 'Ồ' => 'O', 'Ổ' => 'O', 'Ỗ' => 'O', 'Ộ' => 'O', 'Ơ' => 'O', 'Ớ' => 'O', 'Ờ' => 'O', 'Ở' => 'O', 'Ỡ' => 'O', 'Ợ' => 'O', + 'ó' => 'o', 'ò' => 'o', 'ỏ' => 'o', 'õ' => 'o', 'ọ' => 'o', 'ô' => 'o', 'ố' => 'o', 'ồ' => 'o', 'ổ' => 'o', 'ỗ' => 'o', 'ộ' => 'o', 'ơ' => 'o', 'ớ' => 'o', 'ờ' => 'o', 'ở' => 'o', 'ỡ' => 'o', 'ợ' => 'o', + 'Ú' => 'U', 'Ù' => 'U', 'Ủ' => 'U', 'Ũ' => 'U', 'Ụ' => 'U', 'Ư' => 'U', 'Ứ' => 'U', 'Ừ' => 'U', 'Ử' => 'U', 'Ữ' => 'U', 'Ự' => 'U', + 'ú' => 'u', 'ù' => 'u', 'ủ' => 'u', 'ũ' => 'u', 'ụ' => 'u', 'ư' => 'u', 'ứ' => 'u', 'ừ' => 'u', 'ử' => 'u', 'ữ' => 'u', 'ự' => 'u', + 'Ý' => 'Y', 'Ỳ' => 'Y', 'Ỷ' => 'Y', 'Ỹ' => 'Y', 'Ỵ' => 'Y', 'ý' => 'y', 'ỳ' => 'y', 'ỷ' => 'y', 'ỹ' => 'y', 'ỵ' => 'y', + 'Đ' => 'D', 'đ' => 'd' + ), + 'ar' => array(/* Arabic */ + 'أ' => 'a', 'ب' => 'b', 'ت' => 't', 'ث' => 'th', 'ج' => 'g', 'ح' => 'h', 'خ' => 'kh', 'د' => 'd', + 'ذ' => 'th', 'ر' => 'r', 'ز' => 'z', 'س' => 's', 'ش' => 'sh', 'ص' => 's', 'ض' => 'd', 'ط' => 't', + 'ظ' => 'th', 'ع' => 'aa', 'غ' => 'gh', 'ف' => 'f', 'ق' => 'k', 'ك' => 'k', 'ل' => 'l', 'م' => 'm', + 'ن' => 'n', 'ه' => 'h', 'و' => 'o', 'ي' => 'y' + ), + 'sr' => array(/* Serbian */ + 'ђ' => 'dj', 'ј' => 'j', 'љ' => 'lj', 'њ' => 'nj', 'ћ' => 'c', 'џ' => 'dz', 'đ' => 'dj', + 'Ђ' => 'Dj', 'Ј' => 'j', 'Љ' => 'Lj', 'Њ' => 'Nj', 'Ћ' => 'C', 'Џ' => 'Dz', 'Đ' => 'Dj' + ), + 'az' => array(/* Azerbaijani */ + 'ç' => 'c', 'ə' => 'e', 'ğ' => 'g', 'ı' => 'i', 'ö' => 'o', 'ş' => 's', 'ü' => 'u', + 'Ç' => 'C', 'Ə' => 'E', 'Ğ' => 'G', 'İ' => 'I', 'Ö' => 'O', 'Ş' => 'S', 'Ü' => 'U' + ), + ); + + /** + * The character map for the designated language + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + */ + private static $map = array(); + + /** + * The character list as a string. + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + */ + private static $chars = ''; + + /** + * The character list as a regular expression. + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + */ + private static $regex = ''; + + /** + * The current language + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + */ + private static $language = ''; + + /** + * Initializes the character map. + * + * Part of the URLify.php Project + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + */ + private static function initLanguageMap($language = '') + { + if (count(self::$map) > 0 && (($language == '') || ($language == self::$language))) { + return; + } + + // Is a specific map associated with $language? + if (isset(self::$maps[$language]) && is_array(self::$maps[$language])) { + // Move this map to end. This means it will have priority over others + $m = self::$maps[$language]; + unset(self::$maps[$language]); + self::$maps[$language] = $m; + } + + // Reset static vars + self::$language = $language; + self::$map = array(); + self::$chars = ''; + + foreach (self::$maps as $map) { + foreach ($map as $orig => $conv) { + self::$map[$orig] = $conv; + self::$chars .= $orig; + } + } + + self::$regex = '/[' . self::$chars . ']/u'; + } + + + /** + * Access an array index, retrieving the value stored there if it + * exists or a default if it does not. This function allows you to + * concisely access an index which may or may not exist without + * raising a warning. + * + * @param array $var Array value to access + * @param mixed $default Default value to return if the key is not + * present in the array + * @return mixed + */ + public static function array_get(&$var, $default = null) + { + if (isset($var)) { + return $var; + } + + return $default; + } + + /** + * Display a variable's contents using nice HTML formatting and will + * properly display the value of booleans as true or false + * + * @see var_dump_plain() + * + * @param mixed $var The variable to dump + * @return string + */ + public static function var_dump($var, $return = false, $expandLevel = 1) + { + self::$hasArray = false; + $toggScript = 'var colToggle = function(toggID) {var img = document.getElementById(toggID);if (document.getElementById(toggID + "-collapsable").style.display == "none") {document.getElementById(toggID + "-collapsable").style.display = "inline";setImg(toggID, 0);var previousSibling = document.getElementById(toggID + "-collapsable").previousSibling;while (previousSibling != null && (previousSibling.nodeType != 1 || previousSibling.tagName.toLowerCase() != "br")) {previousSibling = previousSibling.previousSibling;}} else {document.getElementById(toggID + "-collapsable").style.display = "none";setImg(toggID, 1);var previousSibling = document.getElementById(toggID + "-collapsable").previousSibling; while (previousSibling != null && (previousSibling.nodeType != 1 || previousSibling.tagName.toLowerCase() != "br")) {previousSibling = previousSibling.previousSibling;}}};'; + $imgScript = 'var setImg = function(objID,imgID,addStyle) {var imgStore = ["data:image/png;base64,' . self::$icon_collapse . '", "data:image/png;base64,' . self::$icon_expand . '"];if (objID) {document.getElementById(objID).setAttribute("src", imgStore[imgID]);if (addStyle){document.getElementById(objID).setAttribute("style", "position:relative;left:-5px;top:-1px;cursor:pointer;");}}};'; + $jsCode = preg_replace('/ +/', ' ', ''); + $html = '
';
+        $done  = array();
+        $html .= self::var_dump_plain($var, intval($expandLevel), 0, $done);
+        $html .= '
'; + + if (self::$hasArray) { + $html = $jsCode . $html; + } + + if (!$return) { + echo $html; + } + + return $html; + } + + /** + * Display a variable's contents using nice HTML formatting (Without + * the
 tag) and will properly display the values of variables
+     * like booleans and resources. Supports collapsable arrays and objects
+     * as well.
+     *
+     * @param  mixed $var The variable to dump
+     * @return string
+     */
+    public static function var_dump_plain($var, $expLevel, $depth = 0, $done = array())
+    {
+        $html = '';
+
+        if ($expLevel > 0) {
+            $expLevel--;
+            $setImg = 0;
+            $setStyle = 'display:inline;';
+        } elseif ($expLevel == 0) {
+            $setImg = 1;
+            $setStyle='display:none;';
+        } elseif ($expLevel < 0) {
+            $setImg = 0;
+            $setStyle = 'display:inline;';
+        }
+
+        if (is_bool($var)) {
+            $html .= 'bool(' . (($var) ? 'true' : 'false') . ')';
+        } elseif (is_int($var)) {
+            $html .= 'int(' . $var . ')';
+        } elseif (is_float($var)) {
+            $html .= 'float(' . $var . ')';
+        } elseif (is_string($var)) {
+            $html .= 'string(' . strlen($var) . ') "' . self::htmlentities($var) . '"';
+        } elseif (is_null($var)) {
+            $html .= 'NULL';
+        } elseif (is_resource($var)) {
+            $html .= 'resource("' . get_resource_type($var) . '") "' . $var . '"';
+        } elseif (is_array($var)) {
+            // Check for recursion
+            if ($depth > 0) {
+                foreach ($done as $prev) {
+                    if ($prev === $var) {
+                        $html .= 'array(' . count($var) . ') *RECURSION DETECTED*';
+                        return $html;
+                    }
+                }
+
+                // Keep track of variables we have already processed to detect recursion
+                $done[] = &$var;
+            }
+
+            self::$hasArray = true;
+            $uuid = 'include-php-' . uniqid() . mt_rand(1, 1000000);
+
+            $html .= (!empty($var) ? ' ' : '') . 'array(' . count($var) . ')';
+            if (!empty($var)) {
+                $html .= ' 
[
'; + + $indent = 4; + $longest_key = 0; + + foreach ($var as $key => $value) { + if (is_string($key)) { + $longest_key = max($longest_key, strlen($key) + 2); + } else { + $longest_key = max($longest_key, strlen($key)); + } + } + + foreach ($var as $key => $value) { + if (is_numeric($key)) { + $html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' '); + } else { + $html .= str_repeat(' ', $indent) . str_pad('"' . self::htmlentities($key) . '"', $longest_key, ' '); + } + + $html .= ' => '; + + $value = explode('
', self::var_dump_plain($value, $expLevel, $depth + 1, $done)); + + foreach ($value as $line => $val) { + if ($line != 0) { + $value[$line] = str_repeat(' ', $indent * 2) . $val; + } + } + + $html .= implode('
', $value) . '
'; + } + + $html .= ']
'; + } + } elseif (is_object($var)) { + // Check for recursion + foreach ($done as $prev) { + if ($prev === $var) { + $html .= 'object(' . get_class($var) . ') *RECURSION DETECTED*'; + return $html; + } + } + + // Keep track of variables we have already processed to detect recursion + $done[] = &$var; + + self::$hasArray=true; + $uuid = 'include-php-' . uniqid() . mt_rand(1, 1000000); + + $html .= ' object(' . get_class($var) . ')
[
'; + + $varArray = (array) $var; + + $indent = 4; + $longest_key = 0; + + foreach ($varArray as $key => $value) { + if (substr($key, 0, 2) == "\0*") { + unset($varArray[$key]); + $key = 'protected:' . substr($key, 3); + $varArray[$key] = $value; + } elseif (substr($key, 0, 1) == "\0") { + unset($varArray[$key]); + $key = 'private:' . substr($key, 1, strpos(substr($key, 1), "\0")) . ':' . substr($key, strpos(substr($key, 1), "\0") + 2); + $varArray[$key] = $value; + } + + if (is_string($key)) { + $longest_key = max($longest_key, strlen($key) + 2); + } else { + $longest_key = max($longest_key, strlen($key)); + } + } + + foreach ($varArray as $key => $value) { + if (is_numeric($key)) { + $html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' '); + } else { + $html .= str_repeat(' ', $indent) . str_pad('"' . self::htmlentities($key) . '"', $longest_key, ' '); + } + + $html .= ' => '; + + $value = explode('
', self::var_dump_plain($value, $expLevel, $depth + 1, $done)); + + foreach ($value as $line => $val) { + if ($line != 0) { + $value[$line] = str_repeat(' ', $indent * 2) . $val; + } + } + + $html .= implode('
', $value) . '
'; + } + + $html .= ']
'; + } + + return $html; + } + + /** + * Converts any accent characters to their equivalent normal characters + * and converts any other non-alphanumeric characters to dashes, then + * converts any sequence of two or more dashes to a single dash. This + * function generates slugs safe for use as URLs, and if you pass true + * as the second parameter, it will create strings safe for use as CSS + * classes or IDs. + * + * @param string $string A string to convert to a slug + * @param string $separator The string to separate words with + * @param boolean $css_mode Whether or not to generate strings safe for + * CSS classes/IDs (Default to false) + * @return string + */ + public static function slugify($string, $separator = '-', $css_mode = false) + { + // Compatibility with 1.0.* parameter ordering for semvar + if ($separator === true || $separator === false) { + $css_mode = $separator; + $separator = '-'; + + // Raise deprecation error + trigger_error( + 'util::slugify() now takes $css_mode as the third parameter, please update your code', + E_USER_DEPRECATED + ); + } + + $slug = preg_replace('/([^a-z0-9]+)/', $separator, strtolower(self::remove_accents($string))); + + if ($css_mode) { + $digits = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'); + + if (is_numeric(substr($slug, 0, 1))) { + $slug = $digits[substr($slug, 0, 1)] . substr($slug, 1); + } + } + + return $slug; + } + + /** + * Checks to see if a string is utf8 encoded. + * + * NOTE: This function checks for 5-Byte sequences, UTF8 + * has Bytes Sequences with a maximum length of 4. + * + * Written by Tony Ferrara + * + * @param string $string The string to be checked + * @return boolean + */ + public static function seems_utf8($string) + { + if (function_exists('mb_check_encoding')) { + // If mbstring is available, this is significantly faster than + // using PHP regexps. + return mb_check_encoding($string, 'UTF-8'); + } + + // @codeCoverageIgnoreStart + return self::seemsUtf8Regex($string); + // @codeCoverageIgnoreEnd + } + + /** + * A non-Mbstring UTF-8 checker. + * + * @param $string + * @return bool + */ + protected static function seemsUtf8Regex($string) + { + // Obtained from http://stackoverflow.com/a/11709412/430062 with permission. + $regex = '/( + [\xC0-\xC1] # Invalid UTF-8 Bytes + | [\xF5-\xFF] # Invalid UTF-8 Bytes + | \xE0[\x80-\x9F] # Overlong encoding of prior code point + | \xF0[\x80-\x8F] # Overlong encoding of prior code point + | [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start + | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start + | [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start + | (?<=[\x0-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle + | (? + * + * @param string $brokenSerializedData + * @return string + */ + public static function fix_broken_serialization($brokenSerializedData) + { + $fixdSerializedData = preg_replace_callback('!s:(\d+):"(.*?)";!', function($matches) { + $snip = $matches[2]; + return 's:' . strlen($snip) . ':"' . $snip . '";'; + }, $brokenSerializedData); + + return $fixdSerializedData; + } + + /** + * Checks to see if the page is being server over SSL or not + * + * @return boolean + */ + public static function is_https() + { + return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'; + } + + /** + * Add or remove query arguments to the URL. + * + * @param mixed $newKey Either newkey or an associative array + * @param mixed $newValue Either newvalue or oldquery or uri + * @param mixed $uri URI or URL to append the queru/queries to. + * @return string + */ + public static function add_query_arg($newKey, $newValue = null, $uri = null) + { + // Was an associative array of key => value pairs passed? + if (is_array($newKey)) { + $newParams = $newKey; + + // Was the URL passed as an argument? + if (!is_null($newValue)) { + $uri = $newValue; + } elseif (!is_null($uri)) { + $uri = $uri; + } else { + $uri = self::array_get($_SERVER['REQUEST_URI'], ''); + } + } else { + $newParams = array($newKey => $newValue); + + // Was the URL passed as an argument? + $uri = is_null($uri) ? self::array_get($_SERVER['REQUEST_URI'], '') : $uri; + } + + // Parse the URI into it's components + $puri = parse_url($uri); + + if (isset($puri['query'])) { + parse_str($puri['query'], $queryParams); + $queryParams = array_merge($queryParams, $newParams); + } elseif (isset($puri['path']) && strstr($puri['path'], '=') !== false) { + $puri['query'] = $puri['path']; + unset($puri['path']); + parse_str($puri['query'], $queryParams); + $queryParams = array_merge($queryParams, $newParams); + } else { + $queryParams = $newParams; + } + + // Strip out any query params that are set to false + foreach ($queryParams as $param => $value) { + if ($value === false) { + unset($queryParams[$param]); + } + } + + // Re-construct the query string + $puri['query'] = http_build_query($queryParams); + + // Re-construct the entire URL + $nuri = self::http_build_url($puri); + + // Make the URI consistent with our input + if ($nuri[0] === '/' && strstr($uri, '/') === false) { + $nuri = substr($nuri, 1); + } + + if ($nuri[0] === '?' && strstr($uri, '?') === false) { + $nuri = substr($nuri, 1); + } + + return rtrim($nuri, '?'); + } + + /** + * Removes an item or list from the query string. + * + * @param string|array $keys Query key or keys to remove. + * @param bool $uri When false uses the $_SERVER value + * @return string + */ + public static function remove_query_arg($keys, $uri = null) + { + if (is_array($keys)) { + return self::add_query_arg(array_combine($keys, array_fill(0, count($keys), null)), $uri); + } + + return self::add_query_arg(array($keys => null), $uri); + } + + /** + * Build a URL. + * + * The parts of the second URL will be merged into the first according to + * the flags argument. + * + * @author Jake Smith + * @see https://github.com/jakeasmith/http_build_url/ + * + * @param mixed $url (part(s) of) an URL in form of a string or + * associative array like parse_url() returns + * @param mixed $parts same as the first argument + * @param int $flags a bitmask of binary or'ed HTTP_URL constants; + * HTTP_URL_REPLACE is the default + * @param array $new_url if set, it will be filled with the parts of the + * composed url like parse_url() would return + * @return string + */ + public static function http_build_url($url, $parts = array(), $flags = self::HTTP_URL_REPLACE, &$new_url = array()) + { + is_array($url) || $url = parse_url($url); + is_array($parts) || $parts = parse_url($parts); + + isset($url['query']) && is_string($url['query']) || $url['query'] = null; + isset($parts['query']) && is_string($parts['query']) || $parts['query'] = null; + + $keys = array('user', 'pass', 'port', 'path', 'query', 'fragment'); + + // HTTP_URL_STRIP_ALL and HTTP_URL_STRIP_AUTH cover several other flags. + if ($flags & self::HTTP_URL_STRIP_ALL) { + $flags |= self::HTTP_URL_STRIP_USER | self::HTTP_URL_STRIP_PASS + | self::HTTP_URL_STRIP_PORT | self::HTTP_URL_STRIP_PATH + | self::HTTP_URL_STRIP_QUERY | self::HTTP_URL_STRIP_FRAGMENT; + } elseif ($flags & self::HTTP_URL_STRIP_AUTH) { + $flags |= self::HTTP_URL_STRIP_USER | self::HTTP_URL_STRIP_PASS; + } + + // Schema and host are alwasy replaced + foreach (array('scheme', 'host') as $part) { + if (isset($parts[$part])) { + $url[$part] = $parts[$part]; + } + } + + if ($flags & self::HTTP_URL_REPLACE) { + foreach ($keys as $key) { + if (isset($parts[$key])) { + $url[$key] = $parts[$key]; + } + } + } else { + if (isset($parts['path']) && ($flags & self::HTTP_URL_JOIN_PATH)) { + if (isset($url['path']) && substr($parts['path'], 0, 1) !== '/') { + $url['path'] = rtrim( + str_replace(basename($url['path']), '', $url['path']), + '/' + ) . '/' . ltrim($parts['path'], '/'); + } else { + $url['path'] = $parts['path']; + } + } + + if (isset($parts['query']) && ($flags & self::HTTP_URL_JOIN_QUERY)) { + if (isset($url['query'])) { + parse_str($url['query'], $url_query); + parse_str($parts['query'], $parts_query); + + $url['query'] = http_build_query( + array_replace_recursive( + $url_query, + $parts_query + ) + ); + } else { + $url['query'] = $parts['query']; + } + } + } + + if (isset($url['path']) && substr($url['path'], 0, 1) !== '/') { + $url['path'] = '/' . $url['path']; + } + + foreach ($keys as $key) { + $strip = 'HTTP_URL_STRIP_' . strtoupper($key); + if ($flags & constant('utilphp\\util::' . $strip)) { + unset($url[$key]); + } + } + + $parsed_string = ''; + + if (isset($url['scheme'])) { + $parsed_string .= $url['scheme'] . '://'; + } + + if (isset($url['user'])) { + $parsed_string .= $url['user']; + + if (isset($url['pass'])) { + $parsed_string .= ':' . $url['pass']; + } + + $parsed_string .= '@'; + } + + if (isset($url['host'])) { + $parsed_string .= $url['host']; + } + + if (isset($url['port'])) { + $parsed_string .= ':' . $url['port']; + } + + if (!empty($url['path'])) { + $parsed_string .= $url['path']; + } else { + $parsed_string .= '/'; + } + + if (isset($url['query'])) { + $parsed_string .= '?' . $url['query']; + } + + if (isset($url['fragment'])) { + $parsed_string .= '#' . $url['fragment']; + } + + $new_url = $url; + + return $parsed_string; + } + + /** + * Converts many english words that equate to true or false to boolean. + * + * Supports 'y', 'n', 'yes', 'no' and a few other variations. + * + * @param string $string The string to convert to boolean + * @param bool $default The value to return if we can't match any + * yes/no words + * @return boolean + */ + public static function str_to_bool($string, $default = false) + { + $yes_words = 'affirmative|all right|aye|indubitably|most assuredly|ok|of course|okay|sure thing|y|yes+|yea|yep|sure|yeah|true|t|on|1|oui|vrai'; + $no_words = 'no*|no way|nope|nah|na|never|absolutely not|by no means|negative|never ever|false|f|off|0|non|faux'; + + if (preg_match('/^(' . $yes_words . ')$/i', $string)) { + return true; + } elseif (preg_match('/^(' . $no_words . ')$/i', $string)) { + return false; + } + + return $default; + } + + /** + * Check if a string starts with the given string. + * + * @param string $string + * @param string $starts_with + * @return boolean + */ + public static function starts_with($string, $starts_with) + { + return strpos($string, $starts_with) === 0; + } + + /** + * Check if a string ends with the given string. + * + * @param string $string + * @param string $starts_with + * @return boolean + */ + public static function ends_with($string, $ends_with) + { + return substr($string, -strlen($ends_with)) === $ends_with; + } + + /** + * Check if a string contains another string. + * + * @param string $haystack + * @param string $needle + * @return boolean + */ + public static function str_contains($haystack, $needle) + { + return strpos($haystack, $needle) !== false; + } + + /** + * Check if a string contains another string. This version is case + * insensitive. + * + * @param string $haystack + * @param string $needle + * @return boolean + */ + public static function str_icontains($haystack, $needle) + { + return stripos($haystack, $needle) !== false; + } + + /** + * Return the file extension of the given filename. + * + * @param string $filename + * @return string + */ + public static function get_file_ext($filename) + { + return pathinfo($filename, PATHINFO_EXTENSION); + } + + /** + * Removes a directory (and its contents) recursively. + * + * Contributed by Askar (ARACOOL) + * + * @param string $dir The directory to be deleted recursively + * @param bool $traverseSymlinks Delete contents of symlinks recursively + * @return bool + * @throws \RuntimeException + */ + public static function rmdir($dir, $traverseSymlinks = false) + { + if (!file_exists($dir)) { + return true; + } elseif (!is_dir($dir)) { + throw new \RuntimeException('Given path is not a directory'); + } + + if (!is_link($dir) || $traverseSymlinks) { + foreach (scandir($dir) as $file) { + if ($file === '.' || $file === '..') { + continue; + } + + $currentPath = $dir . '/' . $file; + + if (is_dir($currentPath)) { + self::rmdir($currentPath, $traverseSymlinks); + } elseif (!unlink($currentPath)) { + // @codeCoverageIgnoreStart + throw new \RuntimeException('Unable to delete ' . $currentPath); + // @codeCoverageIgnoreEnd + } + } + } + + // Windows treats removing directory symlinks identically to removing directories. + if (is_link($dir) && !defined('PHP_WINDOWS_VERSION_MAJOR')) { + if (!unlink($dir)) { + // @codeCoverageIgnoreStart + throw new \RuntimeException('Unable to delete ' . $dir); + // @codeCoverageIgnoreEnd + } + } else { + if (!rmdir($dir)) { + // @codeCoverageIgnoreStart + throw new \RuntimeException('Unable to delete ' . $dir); + // @codeCoverageIgnoreEnd + } + } + + return true; + } + + /** + * Convert entities, while preserving already-encoded entities. + * + * @param string $string The text to be converted + * @return string + */ + public static function htmlentities($string, $preserve_encoded_entities = false) + { + if ($preserve_encoded_entities) { + // @codeCoverageIgnoreStart + if (defined('HHVM_VERSION')) { + $translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES); + } else { + $translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES, self::mbInternalEncoding()); + } + // @codeCoverageIgnoreEnd + + $translation_table[chr(38)] = '&'; + return preg_replace('/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', strtr($string, $translation_table)); + } + + return htmlentities($string, ENT_QUOTES, self::mbInternalEncoding()); + } + + /** + * Convert >, <, ', " and & to html entities, but preserves entities that + * are already encoded. + * + * @param string $string The text to be converted + * @return string + */ + public static function htmlspecialchars($string, $preserve_encoded_entities = false) + { + if ($preserve_encoded_entities) { + // @codeCoverageIgnoreStart + if (defined('HHVM_VERSION')) { + $translation_table = get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES); + } else { + $translation_table = get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES, self::mbInternalEncoding()); + } + // @codeCoverageIgnoreEnd + + $translation_table[chr(38)] = '&'; + + return preg_replace('/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', strtr($string, $translation_table)); + } + + return htmlentities($string, ENT_QUOTES, self::mbInternalEncoding()); + } + + /** + * Transliterates characters to their ASCII equivalents. + * + * Part of the URLify.php Project + * + * @see https://github.com/jbroadway/urlify/blob/master/URLify.php + * + * @param string $text Text that might have not-ASCII characters + * @param string $language Specifies a priority for a specific language. + * @return string Filtered string with replaced "nice" characters + */ + public static function downcode($text, $language = '') + { + self::initLanguageMap($language); + + if (self::seems_utf8($text)) { + if (preg_match_all(self::$regex, $text, $matches)) { + for ($i = 0; $i < count($matches[0]); $i++) { + $char = $matches[0][$i]; + if (isset(self::$map[$char])) { + $text = str_replace($char, self::$map[$char], $text); + } + } + } + } else { + // Not a UTF-8 string so we assume its ISO-8859-1 + $search = "\x80\x83\x8a\x8e\x9a\x9e\x9f\xa2\xa5\xb5\xc0\xc1\xc2\xc3\xc4\xc5\xc7\xc8\xc9\xca\xcb\xcc\xcd"; + $search .= "\xce\xcf\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9"; + $search .= "\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xff"; + $text = strtr($text, $search, 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'); + + // These latin characters should be represented by two characters so + // we can't use strtr + $complexSearch = array("\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe"); + $complexReplace = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); + $text = str_replace($complexSearch, $complexReplace, $text); + } + + return $text; + } + + /** + * Converts all accent characters to ASCII characters. + * + * If there are no accent characters, then the string given is just + * returned. + * + * @param string $string Text that might have accent characters + * @param string $language Specifies a priority for a specific language. + * @return string Filtered string with replaced "nice" characters + */ + public static function remove_accents($string, $language = '') + { + if (!preg_match('/[\x80-\xff]/', $string)) { + return $string; + } + + return self::downcode($string, $language); + } + + /** + * Strip all witespaces from the given string. + * + * @param string $string The string to strip + * @return string + */ + public static function strip_space($string) + { + return preg_replace('/\s+/', '', $string); + } + + /** + * Sanitize a string by performing the following operation : + * - Remove accents + * - Lower the string + * - Remove punctuation characters + * - Strip whitespaces + * + * @param string $string the string to sanitize + * @return string + */ + public static function sanitize_string($string) + { + $string = self::remove_accents($string); + $string = strtolower($string); + $string = preg_replace('/[^a-zA-Z 0-9]+/', '', $string); + $string = self::strip_space($string); + + return $string; + } + + /** + * Pads a given string with zeroes on the left. + * + * @param int $number The number to pad + * @param int $length The total length of the desired string + * @return string + */ + public static function zero_pad($number, $length) + { + return str_pad($number, $length, '0', STR_PAD_LEFT); + } + + /** + * Converts a unix timestamp to a relative time string, such as "3 days ago" + * or "2 weeks ago". + * + * @param int $from The date to use as a starting point + * @param int $to The date to compare to, defaults to now + * @param string $suffix The string to add to the end, defaults to " ago" + * @return string + */ + public static function human_time_diff($from, $to = '', $as_text = false, $suffix = ' ago') + { + if ($to == '') { + $to = time(); + } + + $from = new \DateTime(date('Y-m-d H:i:s', $from)); + $to = new \DateTime(date('Y-m-d H:i:s', $to)); + $diff = $from->diff($to); + + if ($diff->y > 1) { + $text = $diff->y . ' years'; + } elseif ($diff->y == 1) { + $text = '1 year'; + } elseif ($diff->m > 1) { + $text = $diff->m . ' months'; + } elseif ($diff->m == 1) { + $text = '1 month'; + } elseif ($diff->d > 7) { + $text = ceil($diff->d / 7) . ' weeks'; + } elseif ($diff->d == 7) { + $text = '1 week'; + } elseif ($diff->d > 1) { + $text = $diff->d . ' days'; + } elseif ($diff->d == 1) { + $text = '1 day'; + } elseif ($diff->h > 1) { + $text = $diff->h . ' hours'; + } elseif ($diff->h == 1) { + $text = ' 1 hour'; + } elseif ($diff->i > 1) { + $text = $diff->i . ' minutes'; + } elseif ($diff->i == 1) { + $text = '1 minute'; + } elseif ($diff->s > 1) { + $text = $diff->s . ' seconds'; + } else { + $text = '1 second'; + } + + if ($as_text) { + $text = explode(' ', $text, 2); + $text = self::number_to_word($text[0]) . ' ' . $text[1]; + } + + return trim($text) . $suffix; + } + + /** + * Converts a number into the text equivalent. For example, 456 becomes four + * hundred and fifty-six. + * + * Part of the IntToWords Project. + * + * @param int|float $number The number to convert into text + * @return string + */ + public static function number_to_word($number) + { + $number = (string) $number; + + if (strpos($number, '.') !== false) { + list($number, $decimal) = explode('.', $number); + } else { + $decimal = false; + } + + $output = ''; + + if ($number[0] == '-') { + $output = 'negative '; + $number = ltrim($number, '-'); + } elseif ($number[0] == '+') { + $output = 'positive '; + $number = ltrim($number, '+'); + } + + if ($number[0] == '0') { + $output .= 'zero'; + } else { + $length = 19; + $number = str_pad($number, 60, '0', STR_PAD_LEFT); + $group = rtrim(chunk_split($number, 3, ' '), ' '); + $groups = explode(' ', $group); + $groups2 = array(); + + foreach ($groups as $group) { + $group[1] = isset($group[1]) ? $group[1] : null; + $group[2] = isset($group[2]) ? $group[2] : null; + $groups2[] = self::numberToWordThreeDigits($group[0], $group[1], $group[2]); + } + + for ($z = 0; $z < count($groups2); $z++) { + if ($groups2[$z] != '') { + $output .= $groups2[$z] . self::numberToWordConvertGroup($length - $z); + $output .= ($z < $length && ! array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[$length] != '' && $groups[$length][0] == '0' ? ' and ' : ', '); + } + } + + $output = rtrim($output, ', '); + } + + if ($decimal > 0) { + $output .= ' point'; + + for ($i = 0; $i < strlen($decimal); $i++) { + $output .= ' ' . self::numberToWordConvertDigit($decimal[$i]); + } + } + + return $output; + } + + protected static function numberToWordConvertGroup($index) + { + switch($index) { + case 11: + return ' decillion'; + case 10: + return ' nonillion'; + case 9: + return ' octillion'; + case 8: + return ' septillion'; + case 7: + return ' sextillion'; + case 6: + return ' quintrillion'; + case 5: + return ' quadrillion'; + case 4: + return ' trillion'; + case 3: + return ' billion'; + case 2: + return ' million'; + case 1: + return ' thousand'; + case 0: + return ''; + } + + return ''; + } + + protected static function numberToWordThreeDigits($digit1, $digit2, $digit3) + { + $output = ''; + + if ($digit1 == '0' && $digit2 == '0' && $digit3 == '0') { + return ''; + } + + if ($digit1 != '0') { + $output .= self::numberToWordConvertDigit($digit1) . ' hundred'; + + if ($digit2 != '0' || $digit3 != '0') { + $output .= ' and '; + } + } + if ($digit2 != '0') { + $output .= self::numberToWordTwoDigits($digit2, $digit3); + } elseif ($digit3 != '0') { + $output .= self::numberToWordConvertDigit($digit3); + } + + return $output; + } + + protected static function numberToWordTwoDigits($digit1, $digit2) + { + if ($digit2 == '0') { + switch ($digit1) { + case '1': + return 'ten'; + case '2': + return 'twenty'; + case '3': + return 'thirty'; + case '4': + return 'forty'; + case '5': + return 'fifty'; + case '6': + return 'sixty'; + case '7': + return 'seventy'; + case '8': + return 'eighty'; + case '9': + return 'ninety'; + } + } elseif ($digit1 == '1') { + switch ($digit2) { + case '1': + return 'eleven'; + case '2': + return 'twelve'; + case '3': + return 'thirteen'; + case '4': + return 'fourteen'; + case '5': + return 'fifteen'; + case '6': + return 'sixteen'; + case '7': + return 'seventeen'; + case '8': + return 'eighteen'; + case '9': + return 'nineteen'; + } + } else { + $second_digit = self::numberToWordConvertDigit($digit2); + + switch ($digit1) { + case '2': + return "twenty-{$second_digit}"; + case '3': + return "thirty-{$second_digit}"; + case '4': + return "forty-{$second_digit}"; + case '5': + return "fifty-{$second_digit}"; + case '6': + return "sixty-{$second_digit}"; + case '7': + return "seventy-{$second_digit}"; + case '8': + return "eighty-{$second_digit}"; + case '9': + return "ninety-{$second_digit}"; + } + } + } + + /** + * @param $digit + * @return string + * @throws \LogicException + */ + protected static function numberToWordConvertDigit($digit) + { + switch ($digit) { + case '0': + return 'zero'; + case '1': + return 'one'; + case '2': + return 'two'; + case '3': + return 'three'; + case '4': + return 'four'; + case '5': + return 'five'; + case '6': + return 'six'; + case '7': + return 'seven'; + case '8': + return 'eight'; + case '9': + return 'nine'; + default: + throw new \LogicException('Not a number'); + } + } + + /** + * Transmit UTF-8 content headers if the headers haven't already been sent. + * + * @param string $content_type The content type to send out + * @return boolean + */ + public static function utf8_headers($content_type = 'text/html') + { + // @codeCoverageIgnoreStart + if (!headers_sent()) { + header('Content-type: ' . $content_type . '; charset=utf-8'); + + return true; + } + + return false; + // @codeCoverageIgnoreEnd + } + + /** + * Transmit headers that force a browser to display the download file + * dialog. Cross browser compatible. Only fires if headers have not + * already been sent. + * + * @param string $filename The name of the filename to display to + * browsers + * @param string $content The content to output for the download. + * If you don't specify this, just the + * headers will be sent + * @return boolean + */ + public static function force_download($filename, $content = false) + { + // @codeCoverageIgnoreStart + if (!headers_sent()) { + // Required for some browsers + if (ini_get('zlib.output_compression')) { + @ini_set('zlib.output_compression', 'Off'); + } + + header('Pragma: public'); + header('Expires: 0'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + + // Required for certain browsers + header('Cache-Control: private', false); + + header('Content-Disposition: attachment; filename="' . basename(str_replace('"', '', $filename)) . '";'); + header('Content-Type: application/force-download'); + header('Content-Transfer-Encoding: binary'); + + if ($content) { + header('Content-Length: ' . strlen($content)); + } + + ob_clean(); + flush(); + + if ($content) { + echo $content; + } + + return true; + } + + return false; + // @codeCoverageIgnoreEnd + } + + /** + * Sets the headers to prevent caching for the different browsers. + * + * Different browsers support different nocache headers, so several + * headers must be sent so that all of them get the point that no + * caching should occur + * + * @return boolean + */ + public static function nocache_headers() + { + // @codeCoverageIgnoreStart + if (!headers_sent()) { + header('Expires: Wed, 11 Jan 1984 05:00:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + header('Cache-Control: no-cache, must-revalidate, max-age=0'); + header('Pragma: no-cache'); + + return true; + } + + return false; + // @codeCoverageIgnoreEnd + } + + /** + * Generates a string of random characters. + * + * @throws LengthException If $length is bigger than the available + * character pool and $no_duplicate_chars is + * enabled + * + * @param integer $length The length of the string to + * generate + * @param boolean $human_friendly Whether or not to make the + * string human friendly by + * removing characters that can be + * confused with other characters ( + * O and 0, l and 1, etc) + * @param boolean $include_symbols Whether or not to include + * symbols in the string. Can not + * be enabled if $human_friendly is + * true + * @param boolean $no_duplicate_chars Whether or not to only use + * characters once in the string. + * @return string + */ + public static function random_string($length = 16, $human_friendly = true, $include_symbols = false, $no_duplicate_chars = false) + { + $nice_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjkmnprstuvwxyz23456789'; + $all_an = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'; + $symbols = '!@#$%^&*()~_-=+{}[]|:;<>,.?/"\'\\`'; + $string = ''; + + // Determine the pool of available characters based on the given parameters + if ($human_friendly) { + $pool = $nice_chars; + } else { + $pool = $all_an; + + if ($include_symbols) { + $pool .= $symbols; + } + } + + if (!$no_duplicate_chars) { + return substr(str_shuffle(str_repeat($pool, $length)), 0, $length); + } + + // Don't allow duplicate letters to be disabled if the length is + // longer than the available characters + if ($no_duplicate_chars && strlen($pool) < $length) { + throw new \LengthException('$length exceeds the size of the pool and $no_duplicate_chars is enabled'); + } + + // Convert the pool of characters into an array of characters and + // shuffle the array + $pool = str_split($pool); + $poolLength = count($pool); + $rand = mt_rand(0, $poolLength - 1); + + // Generate our string + for ($i = 0; $i < $length; $i++) { + $string .= $pool[$rand]; + + // Remove the character from the array to avoid duplicates + array_splice($pool, $rand, 1); + + // Generate a new number + if (($poolLength - 2 - $i) > 0) { + $rand = mt_rand(0, $poolLength - 2 - $i); + } else { + $rand = 0; + } + } + + return $string; + } + + /** + * Generate secure random string of given length + * If 'openssl_random_pseudo_bytes' is not available + * then generate random string using default function + * + * Part of the Laravel Project + * + * @param int $length length of string + * @return bool + */ + public static function secure_random_string($length = 16) + { + if (function_exists('openssl_random_pseudo_bytes')) { + $bytes = openssl_random_pseudo_bytes($length * 2); + + if ($bytes === false) { + throw new \LengthException('$length is not accurate, unable to generate random string'); + } + + return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length); + } + + // @codeCoverageIgnoreStart + return static::random_string($length); + // @codeCoverageIgnoreEnd + } + + /** + * Check if a given string matches a given pattern. + * + * Contributed by Abhimanyu Sharma + * + * @param string $pattern Parttern of string exptected + * @param string $string String that need to be matched + * @return bool + */ + public static function match_string($pattern, $string, $caseSensitive = true) + { + if ($pattern == $string) { + return true; + } + + // Preg flags + $flags = $caseSensitive ? '' : 'i'; + + // Escape any regex special characters + $pattern = preg_quote($pattern, '#'); + + // Unescape * which is our wildcard character and change it to .* + $pattern = str_replace('\*', '.*', $pattern); + + return (bool) preg_match('#^' . $pattern . '$#' . $flags, $string); + } + + /** + * Validate an email address. + * + * @param string $possible_email An email address to validate + * @return bool + */ + public static function validate_email($possible_email) + { + return (bool) filter_var($possible_email, FILTER_VALIDATE_EMAIL); + } + + /** + * Return the URL to a user's gravatar. + * + * @param string $email The email of the user + * @param integer $size The size of the gravatar + * @return string + */ + public static function get_gravatar($email, $size = 32) + { + if (self::is_https()) { + $url = 'https://secure.gravatar.com/'; + } else { + $url = 'http://www.gravatar.com/'; + } + + $url .= 'avatar/' . md5($email) . '?s=' . (int) abs($size); + + return $url; + } + + /** + * Turns all of the links in a string into HTML links. + * + * Part of the LinkifyURL Project + * + * @param string $text The string to parse + * @return string + */ + public static function linkify($text) + { + $text = preg_replace('/'/', ''', $text); // IE does not handle ' entity! + $section_html_pattern = '%# Rev:20100913_0900 github.com/jmrware/LinkifyURL + # Section text into HTML tags and everything else. + ( # $1: Everything not HTML tag. + [^<]+(?:(?!... tag. + ]*> # opening tag. + [^<]*(?:(?! # closing tag. + ) # End $2: + %ix'; + + return preg_replace_callback($section_html_pattern, array(__CLASS__, 'linkifyCallback'), $text); + } + + /** + * Callback for the preg_replace in the linkify() method. + * + * Part of the LinkifyURL Project + * + * @param array $matches Matches from the preg_ function + * @return string + */ + protected static function linkifyRegex($text) + { + $url_pattern = '/# Rev:20100913_0900 github.com\/jmrware\/LinkifyURL + # Match http & ftp URL that is not already linkified. + # Alternative 1: URL delimited by (parentheses). + (\() # $1 "(" start delimiter. + ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+) # $2: URL. + (\)) # $3: ")" end delimiter. + | # Alternative 2: URL delimited by [square brackets]. + (\[) # $4: "[" start delimiter. + ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+) # $5: URL. + (\]) # $6: "]" end delimiter. + | # Alternative 3: URL delimited by {curly braces}. + (\{) # $7: "{" start delimiter. + ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+) # $8: URL. + (\}) # $9: "}" end delimiter. + | # Alternative 4: URL delimited by . + (<|&(?:lt|\#60|\#x3c);) # $10: "<" start delimiter (or HTML entity). + ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+) # $11: URL. + (>|&(?:gt|\#62|\#x3e);) # $12: ">" end delimiter (or HTML entity). + | # Alternative 5: URL not delimited by (), [], {} or <>. + (# $13: Prefix proving URL not already linked. + (?: ^ # Can be a beginning of line or string, or + | [^=\s\'"\]] # a non-"=", non-quote, non-"]", followed by + ) \s*[\'"]? # optional whitespace and optional quote; + | [^=\s]\s+ # or... a non-equals sign followed by whitespace. + ) # End $13. Non-prelinkified-proof prefix. + (\b # $14: Other non-delimited URL. + (?:ht|f)tps?:\/\/ # Required literal http, https, ftp or ftps prefix. + [a-z0-9\-._~!$\'()*+,;=:\/?#[\]@%]+ # All URI chars except "&" (normal*). + (?: # Either on a "&" or at the end of URI. + (?! # Allow a "&" char only if not start of an... + &(?:gt|\#0*62|\#x0*3e); # HTML ">" entity, or + | &(?:amp|apos|quot|\#0*3[49]|\#x0*2[27]); # a [&\'"] entity if + [.!&\',:?;]? # followed by optional punctuation then + (?:[^a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]|$) # a non-URI char or EOS. + ) & # If neg-assertion true, match "&" (special). + [a-z0-9\-._~!$\'()*+,;=:\/?#[\]@%]* # More non-& URI chars (normal*). + )* # Unroll-the-loop (special normal*)*. + [a-z0-9\-_~$()*+=\/#[\]@%] # Last char can\'t be [.!&\',;:?] + ) # End $14. Other non-delimited URL. + /imx'; + + $url_replace = '$1$4$7$10$13$2$5$8$11$14$3$6$9$12'; + + return preg_replace($url_pattern, $url_replace, $text); + } + + /** + * Callback for the preg_replace in the linkify() method. + * + * Part of the LinkifyURL Project + * + * @param array $matches Matches from the preg_ function + * @return string + */ + protected static function linkifyCallback($matches) + { + if (isset($matches[2])) { + return $matches[2]; + } + + return self::linkifyRegex($matches[1]); + } + + /** + * Return the current URL. + * + * @return string + */ + public static function get_current_url() + { + $url = ''; + + // Check to see if it's over https + $is_https = self::is_https(); + if ($is_https) { + $url .= 'https://'; + } else { + $url .= 'http://'; + } + + // Was a username or password passed? + if (isset($_SERVER['PHP_AUTH_USER'])) { + $url .= $_SERVER['PHP_AUTH_USER']; + + if (isset($_SERVER['PHP_AUTH_PW'])) { + $url .= ':' . $_SERVER['PHP_AUTH_PW']; + } + + $url .= '@'; + } + + + // We want the user to stay on the same host they are currently on, + // but beware of security issues + // see http://shiflett.org/blog/2006/mar/server-name-versus-http-host + $url .= $_SERVER['HTTP_HOST']; + + $port = $_SERVER['SERVER_PORT']; + + // Is it on a non standard port? + if ($is_https && ($port != 443)) { + $url .= ':' . $_SERVER['SERVER_PORT']; + } elseif (!$is_https && ($port != 80)) { + $url .= ':' . $_SERVER['SERVER_PORT']; + } + + // Get the rest of the URL + if (!isset($_SERVER['REQUEST_URI'])) { + // Microsoft IIS doesn't set REQUEST_URI by default + $url .= $_SERVER['PHP_SELF']; + + if (isset($_SERVER['QUERY_STRING'])) { + $url .= '?' . $_SERVER['QUERY_STRING']; + } + } else { + $url .= $_SERVER['REQUEST_URI']; + } + + return $url; + } + + /** + * Returns the IP address of the client. + * + * @param boolean $trust_proxy_headers Whether or not to trust the + * proxy headers HTTP_CLIENT_IP + * and HTTP_X_FORWARDED_FOR. ONLY + * use if your server is behind a + * proxy that sets these values + * @return string + */ + public static function get_client_ip($trust_proxy_headers = false) + { + if (!$trust_proxy_headers) { + return $_SERVER['REMOTE_ADDR']; + } + + if (!empty($_SERVER['HTTP_CLIENT_IP'])) { + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } else { + $ip = $_SERVER['REMOTE_ADDR']; + } + + return $ip; + } + + /** + * Truncate a string to a specified length without cutting a word off. + * + * @param string $string The string to truncate + * @param integer $length The length to truncate the string to + * @param string $append Text to append to the string IF it gets + * truncated, defaults to '...' + * @return string + */ + public static function safe_truncate($string, $length, $append = '...') + { + $ret = substr($string, 0, $length); + $last_space = strrpos($ret, ' '); + + if ($last_space !== false && $string != $ret) { + $ret = substr($ret, 0, $last_space); + } + + if ($ret != $string) { + $ret .= $append; + } + + return $ret; + } + + + /** + * Truncate the string to given length of charactes. + * + * @param $string + * @param $limit + * @param string $append + * @return string + */ + public static function limit_characters($string, $limit = 100, $append = '...') + { + if (mb_strlen($string) <= $limit) { + return $string; + } + + return rtrim(mb_substr($string, 0, $limit, 'UTF-8')) . $append; + } + + /** + * Truncate the string to given length of words. + * + * @param $string + * @param $limit + * @param string $append + * @return string + */ + public static function limit_words($string, $limit = 100, $append = '...') + { + preg_match('/^\s*+(?:\S++\s*+){1,' . $limit . '}/u', $string, $matches); + + if (!isset($matches[0]) || strlen($string) === strlen($matches[0])) { + return $string; + } + + return rtrim($matches[0]).$append; + } + + /** + * Returns the ordinal version of a number (appends th, st, nd, rd). + * + * @param string $number The number to append an ordinal suffix to + * @return string + */ + public static function ordinal($number) + { + $test_c = abs($number) % 10; + $ext = ((abs($number) % 100 < 21 && abs($number) % 100 > 4) ? 'th' : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th')); + + return $number . $ext; + } + + /** + * Returns the file permissions as a nice string, like -rw-r--r-- or false + * if the file is not found. + * + * @param string $file The name of the file to get permissions form + * @param int $perms Numerical value of permissions to display as text. + * @return string + */ + public static function full_permissions($file, $perms = null) + { + if (is_null($perms)) { + if (!file_exists($file)) { + return false; + } + $perms = fileperms($file); + } + + if (($perms & 0xC000) == 0xC000) { + // Socket + $info = 's'; + } elseif (($perms & 0xA000) == 0xA000) { + // Symbolic Link + $info = 'l'; + } elseif (($perms & 0x8000) == 0x8000) { + // Regular + $info = '-'; + } elseif (($perms & 0x6000) == 0x6000) { + // Block special + $info = 'b'; + } elseif (($perms & 0x4000) == 0x4000) { + // Directory + $info = 'd'; + } elseif (($perms & 0x2000) == 0x2000) { + // Character special + $info = 'c'; + } elseif (($perms & 0x1000) == 0x1000) { + // FIFO pipe + $info = 'p'; + } else { + // Unknown + $info = 'u'; + } + + // Owner + $info .= (($perms & 0x0100) ? 'r' : '-'); + $info .= (($perms & 0x0080) ? 'w' : '-'); + $info .= (($perms & 0x0040) ? + (($perms & 0x0800) ? 's' : 'x') : + (($perms & 0x0800) ? 'S' : '-')); + + // Group + $info .= (($perms & 0x0020) ? 'r' : '-'); + $info .= (($perms & 0x0010) ? 'w' : '-'); + $info .= (($perms & 0x0008) ? + (($perms & 0x0400) ? 's' : 'x') : + (($perms & 0x0400) ? 'S' : '-')); + + // World + $info .= (($perms & 0x0004) ? 'r' : '-'); + $info .= (($perms & 0x0002) ? 'w' : '-'); + $info .= (($perms & 0x0001) ? + (($perms & 0x0200) ? 't' : 'x') : + (($perms & 0x0200) ? 'T' : '-')); + + return $info; + } + + /** + * Returns the first element in an array. + * + * @param array $array + * @return mixed + */ + public static function array_first(array $array) + { + return reset($array); + } + + /** + * Returns the last element in an array. + * + * @param array $array + * @return mixed + */ + public static function array_last(array $array) + { + return end($array); + } + + /** + * Returns the first key in an array. + * + * @param array $array + * @return int|string + */ + public static function array_first_key(array $array) + { + reset($array); + + return key($array); + } + + /** + * Returns the last key in an array. + * + * @param array $array + * @return int|string + */ + public static function array_last_key(array $array) + { + end($array); + + return key($array); + } + + /** + * Flatten a multi-dimensional array into a one dimensional array. + * + * Contributed by Theodore R. Smith of PHP Experts, Inc. + * + * @param array $array The array to flatten + * @param boolean $preserve_keys Whether or not to preserve array keys. + * Keys from deeply nested arrays will + * overwrite keys from shallowy nested arrays + * @return array + */ + public static function array_flatten(array $array, $preserve_keys = true) + { + $flattened = array(); + + array_walk_recursive($array, function($value, $key) use (&$flattened, $preserve_keys) { + if ($preserve_keys && !is_int($key)) { + $flattened[$key] = $value; + } else { + $flattened[] = $value; + } + }); + + return $flattened; + } + + /** + * Accepts an array, and returns an array of values from that array as + * specified by $field. For example, if the array is full of objects + * and you call util::array_pluck($array, 'name'), the function will + * return an array of values from $array[]->name. + * + * @param array $array An array + * @param string $field The field to get values from + * @param boolean $preserve_keys Whether or not to preserve the + * array keys + * @param boolean $remove_nomatches If the field doesn't appear to be set, + * remove it from the array + * @return array + */ + public static function array_pluck(array $array, $field, $preserve_keys = true, $remove_nomatches = true) + { + $new_list = array(); + + foreach ($array as $key => $value) { + if (is_object($value)) { + if (isset($value->{$field})) { + if ($preserve_keys) { + $new_list[$key] = $value->{$field}; + } else { + $new_list[] = $value->{$field}; + } + } elseif (!$remove_nomatches) { + $new_list[$key] = $value; + } + } else { + if (isset($value[$field])) { + if ($preserve_keys) { + $new_list[$key] = $value[$field]; + } else { + $new_list[] = $value[$field]; + } + } elseif (!$remove_nomatches) { + $new_list[$key] = $value; + } + } + } + + return $new_list; + } + + /** + * Searches for a given value in an array of arrays, objects and scalar + * values. You can optionally specify a field of the nested arrays and + * objects to search in. + * + * @param array $array The array to search + * @param scalar $search The value to search for + * @param string $field The field to search in, if not specified + * all fields will be searched + * @return boolean|scalar False on failure or the array key on success + */ + public static function array_search_deep(array $array, $search, $field = false) + { + // *grumbles* stupid PHP type system + $search = (string) $search; + + foreach ($array as $key => $elem) { + // *grumbles* stupid PHP type system + $key = (string) $key; + + if ($field) { + if (is_object($elem) && $elem->{$field} === $search) { + return $key; + } elseif (is_array($elem) && $elem[$field] === $search) { + return $key; + } elseif (is_scalar($elem) && $elem === $search) { + return $key; + } + } else { + if (is_object($elem)) { + $elem = (array) $elem; + + if (in_array($search, $elem)) { + return $key; + } + } elseif (is_array($elem) && in_array($search, $elem)) { + return $key; + } elseif (is_scalar($elem) && $elem === $search) { + return $key; + } + } + } + + return false; + } + + /** + * Returns an array containing all the elements of arr1 after applying + * the callback function to each one. + * + * @param string $callback Callback function to run for each + * element in each array + * @param array $array An array to run through the callback + * function + * @param boolean $on_nonscalar Whether or not to call the callback + * function on nonscalar values + * (Objects, resources, etc) + * @return array + */ + public static function array_map_deep(array $array, $callback, $on_nonscalar = false) + { + foreach ($array as $key => $value) { + if (is_array($value)) { + $args = array($value, $callback, $on_nonscalar); + $array[$key] = call_user_func_array(array(__CLASS__, __FUNCTION__), $args); + } elseif (is_scalar($value) || $on_nonscalar) { + $array[$key] = call_user_func($callback, $value); + } + } + + return $array; + } + + public static function array_clean(array $array) + { + return array_filter($array); + } + + /** + * Wrapper to prevent errors if the user doesn't have the mbstring + * extension installed. + * + * @param string $encoding + * @return string + */ + protected static function mbInternalEncoding($encoding = null) + { + if (function_exists('mb_internal_encoding')) { + return $encoding ? mb_internal_encoding($encoding) : mb_internal_encoding(); + } + + // @codeCoverageIgnoreStart + return 'UTF-8'; + // @codeCoverageIgnoreEnd + } + + /** + * Set the writable bit on a file to the minimum value that allows the user + * running PHP to write to it. + * + * @param string $filename The filename to set the writable bit on + * @param boolean $writable Whether to make the file writable or not + * @return boolean + */ + public static function set_writable($filename, $writable = true) + { + $stat = @stat($filename); + + if ($stat === false) { + return false; + } + + // We're on Windows + if (strncasecmp(PHP_OS, 'WIN', 3) === 0) { + return true; + } + + list($myuid, $mygid) = array(posix_geteuid(), posix_getgid()); + + if ($writable) { + // Set only the user writable bit (file is owned by us) + if ($stat['uid'] == $myuid) { + return chmod($filename, fileperms($filename) | 0200); + } + + // Set only the group writable bit (file group is the same as us) + if ($stat['gid'] == $mygid) { + return chmod($filename, fileperms($filename) | 0220); + } + + // Set the world writable bit (file isn't owned or grouped by us) + return chmod($filename, fileperms($filename) | 0222); + } else { + // Set only the user writable bit (file is owned by us) + if ($stat['uid'] == $myuid) { + return chmod($filename, (fileperms($filename) | 0222) ^ 0222); + } + + // Set only the group writable bit (file group is the same as us) + if ($stat['gid'] == $mygid) { + return chmod($filename, (fileperms($filename) | 0222) ^ 0022); + } + + // Set the world writable bit (file isn't owned or grouped by us) + return chmod($filename, (fileperms($filename) | 0222) ^ 0002); + } + } + + /** + * Set the readable bit on a file to the minimum value that allows the user + * running PHP to read to it. + * + * @param string $filename The filename to set the readable bit on + * @param boolean $readable Whether to make the file readable or not + * @return boolean + */ + public static function set_readable($filename, $readable = true) + { + $stat = @stat($filename); + + if ($stat === false) { + return false; + } + + // We're on Windows + if (strncasecmp(PHP_OS, 'WIN', 3) === 0) { + return true; + } + + list($myuid, $mygid) = array(posix_geteuid(), posix_getgid()); + + if ($readable) { + // Set only the user readable bit (file is owned by us) + if ($stat['uid'] == $myuid) { + return chmod($filename, fileperms($filename) | 0400); + } + + // Set only the group readable bit (file group is the same as us) + if ($stat['gid'] == $mygid) { + return chmod($filename, fileperms($filename) | 0440); + } + + // Set the world readable bit (file isn't owned or grouped by us) + return chmod($filename, fileperms($filename) | 0444); + } else { + // Set only the user readable bit (file is owned by us) + if ($stat['uid'] == $myuid) { + return chmod($filename, (fileperms($filename) | 0444) ^ 0444); + } + + // Set only the group readable bit (file group is the same as us) + if ($stat['gid'] == $mygid) { + return chmod($filename, (fileperms($filename) | 0444) ^ 0044); + } + + // Set the world readable bit (file isn't owned or grouped by us) + return chmod($filename, (fileperms($filename) | 0444) ^ 0004); + } + } + + /** + * Set the executable bit on a file to the minimum value that allows the + * user running PHP to read to it. + * + * @param string $filename The filename to set the executable bit on + * @param boolean $executable Whether to make the file executable or not + * @return boolean + */ + public static function set_executable($filename, $executable = true) + { + $stat = @stat($filename); + + if ($stat === false) { + return false; + } + + // We're on Windows + if (strncasecmp(PHP_OS, 'WIN', 3) === 0) { + return true; + } + + list($myuid, $mygid) = array(posix_geteuid(), posix_getgid()); + + if ($executable) { + // Set only the user readable bit (file is owned by us) + if ($stat['uid'] == $myuid) { + return chmod($filename, fileperms($filename) | 0100); + } + + // Set only the group readable bit (file group is the same as us) + if ($stat['gid'] == $mygid) { + return chmod($filename, fileperms($filename) | 0110); + } + + // Set the world readable bit (file isn't owned or grouped by us) + return chmod($filename, fileperms($filename) | 0111); + } else { + // Set only the user readable bit (file is owned by us) + if ($stat['uid'] == $myuid) { + return chmod($filename, (fileperms($filename) | 0111) ^ 0111); + } + + // Set only the group readable bit (file group is the same as us) + if ($stat['gid'] == $mygid) { + return chmod($filename, (fileperms($filename) | 0111) ^ 0011); + } + + // Set the world readable bit (file isn't owned or grouped by us) + return chmod($filename, (fileperms($filename) | 0111) ^ 0001); + } + } + + /** + * Returns size of a given directory in bytes. + * + * @param string $dir + * @return integer + */ + public static function directory_size($dir) + { + $size = 0; + foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS)) as $file => $key) { + if ($key->isFile()) { + $size += $key->getSize(); + } + } + return $size; + } + + /** + * Returns a home directory of current user. + * + * @return string + */ + public static function get_user_directory() + { + if (isset($_SERVER['HOMEDRIVE'])) return $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH']; + else return $_SERVER['HOME']; + } + + /** + * Returns all paths inside a directory. + * + * @param string $dir + * @return array + */ + public static function directory_contents($dir) + { + $contents = array(); + foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS)) as $pathname => $fi) { + $contents[] = $pathname; + } + natsort($contents); + return $contents; + } +} diff --git a/vendor/brandonwamboldt/utilphp/tests/README.md b/vendor/brandonwamboldt/utilphp/tests/README.md new file mode 100644 index 00000000..e81d26c3 --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/tests/README.md @@ -0,0 +1,39 @@ +# UtilityPHP Unit Tests # + +### Introduction + +This is the testing documentation for util.php. The unit tests require PHPUnit, +and can be run in your web browser. + +### Requirements + +PHP Unit >= 3.5.6 + +#### Installation of PHPUnit + + # Download the PHPUnit phar. + wget https://phar.phpunit.de/phpunit.phar + + # You can just run it locally. (Preferred for Windows) + php phpunit.phar --version + + # Or install it system-wide. + mv phpunit.phar phpunit + chmod +x phpunit + sudo mv phpunit /usr/local/bin + phpunit --version + +## Test Suites: + +util.php includes a phpunit config file, so just run `phpunit` from the working +directory to run the test suite. + +``` +phpunit +``` + +If you want code coverage reports, use the following: + +``` +phpunit --coverage-html ./report +``` diff --git a/vendor/brandonwamboldt/utilphp/tests/UtilTest.php b/vendor/brandonwamboldt/utilphp/tests/UtilTest.php new file mode 100644 index 00000000..404cf7bd --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/tests/UtilTest.php @@ -0,0 +1,1183 @@ +data = (object)array('a', 'b', 'c'); + } +} + +/** + * PHPUnit test case for the util.php library + * + * @author Brandon Wamboldt + * @since 1.0.000 + */ +class UtilityPHPTest extends PHPUnit_Framework_TestCase +{ + /** + * Allows for the testing of private and protected methods. + * + * @param $name + * @return \ReflectionMethod + */ + protected static function getMethod($name) + { + $class = new \ReflectionClass('util'); + $method = $class->getMethod($name); + $method->setAccessible(true); + return $method; + } + + public function test_array_get() + { + $_GET = array(); + $_GET['abc'] = 'def'; + $_GET['nested'] = array( 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' ); + + // Looks for $array['abc'] + $this->assertEquals( 'def', util::array_get( $_GET['abc'] ) ); + + // Looks for $array['nested']['key2'] + $this->assertEquals( 'val2', util::array_get( $_GET['nested']['key2'] ) ); + + // Looks for $array['doesnotexist'] + $this->assertEquals( 'defaultval', util::array_get( $_GET['doesnotexist'], 'defaultval' ) ); + } + + public function test_slugify() + { + $this->assertEquals( 'a-simple-title', util::slugify( 'A simple title' ) ); + $this->assertEquals( 'this-post-it-has-a-dash', util::slugify( 'This post -- it has a dash' ) ); + $this->assertEquals( '123-1251251', util::slugify( '123----1251251' ) ); + $this->assertEquals( 'one23-1251251', util::slugify( '123----1251251', '-', true ) ); + + $this->assertEquals( 'a-simple-title', util::slugify( 'A simple title', '-' ) ); + $this->assertEquals( 'this-post-it-has-a-dash', util::slugify( 'This post -- it has a dash', '-' ) ); + $this->assertEquals( '123-1251251', util::slugify( '123----1251251', '-' ) ); + $this->assertEquals( 'one23-1251251', util::slugify( '123----1251251', '-', true ) ); + + $this->assertEquals( 'a_simple_title', util::slugify( 'A simple title', '_' ) ); + $this->assertEquals( 'this_post_it_has_a_dash', util::slugify( 'This post -- it has a dash', '_' ) ); + $this->assertEquals( '123_1251251', util::slugify( '123----1251251', '_' ) ); + $this->assertEquals( 'one23_1251251', util::slugify( '123----1251251', '_', true ) ); + + // Blank seperator test + $this->assertEquals( 'asimpletitle', util::slugify( 'A simple title', '' ) ); + $this->assertEquals( 'thispostithasadash', util::slugify( 'This post -- it has a dash', '' ) ); + $this->assertEquals( '1231251251', util::slugify( '123----1251251', '' ) ); + $this->assertEquals( 'one231251251', util::slugify( '123----1251251', '', true ) ); + + // Test old parameter ordering for backwards compatability + error_reporting(E_ALL ^ E_USER_DEPRECATED); + $this->assertEquals( 'one23-1251251', util::slugify( '123----1251251', true ) ); + $this->assertEquals( '123-1251251', util::slugify( '123----1251251', false ) ); + } + + public function test_seems_utf8() + { + // Test a valid UTF-8 sequence: "ÜTF-8 Fµñ". + $validUTF8 = "\xC3\x9CTF-8 F\xC2\xB5\xC3\xB1"; + $this->assertTrue( util::seems_utf8( $validUTF8 ) ); + + $this->assertTrue( util::seems_utf8( "\xEF\xBF\xBD this has \xEF\xBF\xBD\xEF\xBF\xBD some invalid utf8 \xEF\xBF\xBD" ) ); + + // Test invalid UTF-8 sequences + $invalidUTF8 = "\xc3 this has \xe6\x9d some invalid utf8 \xe6"; + $this->assertFalse( util::seems_utf8( $invalidUTF8 ) ); + + // And test some plain ASCII + $this->assertTrue( util::seems_utf8( 'The quick brown fox jumps over the lazy dog' ) ); + + // Test an invalid non-UTF-8 string. + if (function_exists('mb_convert_encoding')) { + mb_internal_encoding('UTF-8'); + // Converts the 'ç' UTF-8 character to UCS-2LE + $utf8Char = pack('n', 50087); + $ucsChar = mb_convert_encoding($utf8Char, 'UCS-2LE', 'UTF-8'); + + // Ensure that PHP's internal encoding system isn't malconfigured. + $this->assertEquals( $utf8Char, 'ç', 'This PHP system\'s internal character set is not properly set as UTF-8.' ); + $this->assertEquals( $utf8Char, pack('n', 50087), 'Something is wrong with your ICU unicode library.' ); + + // Test for not UTF-8. + $this->assertFalse( util::seems_utf8( $ucsChar) ); + + // Test the worker method. + $method = self::getMethod('seemsUtf8Regex'); + $this->assertFalse($method->invoke(null, $invalidUTF8), 'util::seemsUtf8Regex did not properly detect invalid UTF-8.'); + $this->assertTrue($method->invoke(null, $validUTF8), 'util::seemsUtf8Regex did not properly detect valid UTF-8.'); + } + } + + public function test_size_format() + { + $size = util::size_format( 512, 0 ); + $this->assertEquals( '512 B', $size ); + + $size = util::size_format( 2048, 1 ); + $this->assertEquals( '2.0 KiB', $size ); + + $size = util::size_format( 25151251, 2 ); + $this->assertEquals( '23.99 MiB', $size ); + + $size = util::size_format( 19971597926, 2 ); + $this->assertEquals( '18.60 GiB', $size ); + + $size = util::size_format( 2748779069440, 1 ); + $this->assertEquals( '2.5 TiB', $size ); + + $size = util::size_format( 2.81475e15, 1 ); + $this->assertEquals( '2.5 PiB', $size ); + + $size = util::size_format( 2.81475e19, 1 ); + $this->assertEquals( '25000.0 PiB', $size ); + } + + public function test_maybe_serialize() + { + $obj = new stdClass(); + $obj->prop1 = 'Hello'; + $obj->prop2 = 'World'; + + $this->assertEquals( 'This is a string', util::maybe_serialize( 'This is a string' ) ); + $this->assertEquals( 5.81, util::maybe_serialize( 5.81 ) ); + $this->assertEquals( 'a:0:{}', util::maybe_serialize( array() ) ); + $this->assertEquals( 'O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}', util::maybe_serialize( $obj ) ); + $this->assertEquals( 'a:4:{i:0;s:4:"test";i:1;s:4:"blah";s:5:"hello";s:5:"world";s:5:"array";O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}}', util::maybe_serialize( array( 'test', 'blah', 'hello' => 'world', 'array' => $obj ) ) ); + } + + public function test_maybe_unserialize() + { + $obj = new stdClass(); + $obj->prop1 = 'Hello'; + $obj->prop2 = 'World'; + + $this->assertNull(util::maybe_unserialize(serialize(null))); + $this->assertFalse(util::maybe_unserialize(serialize(false))); + + $this->assertEquals( 'This is a string', util::maybe_unserialize( 'This is a string' ) ); + $this->assertEquals( 5.81, util::maybe_unserialize( 5.81 ) ); + $this->assertEquals( array(), util::maybe_unserialize( 'a:0:{}' ) ); + $this->assertEquals( $obj, util::maybe_unserialize( 'O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}' ) ); + $this->assertEquals( array( 'test', 'blah', 'hello' => 'world', 'array' => $obj ), util::maybe_unserialize( 'a:4:{i:0;s:4:"test";i:1;s:4:"blah";s:5:"hello";s:5:"world";s:5:"array";O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}}' ) ); + + // Test a broken serialization. + $expectedData = array( + 'Normal', + 'High-value Char: '.chr(231).'a-va?', // High-value Char: ça-va? [in ISO-8859-1] + ); + + $brokenSerialization = 'a:2:{i:0;s:6:"Normal";i:1;s:23:"High-value Char: ▒a-va?";}'; + + $unserializedData = util::maybe_unserialize($brokenSerialization); + $this->assertEquals($expectedData[0], $unserializedData[0], 'Did not properly fix the broken serialized data.'); + $this->assertEquals(substr($expectedData[1], 0, 10), substr($unserializedData[1], 0, 10), 'Did not properly fix the broken serialized data.'); + + // Test unfixable serialization. + $unfixableSerialization = 'a:2:{i:0;s:6:"Normal";}'; + $this->assertEquals($unfixableSerialization, util::maybe_unserialize($unfixableSerialization), 'Somehow the [previously?] impossible happened and utilphp thinks it has unserialized an unfixable serialization.'); + } + + public function test_is_serialized() + { + $this->assertFalse( util::is_serialized(1) ); + $this->assertFalse( util::is_serialized(null) ); + $this->assertFalse( util::is_serialized( 's:4:"test;' ) ); + $this->assertFalse( util::is_serialized( 'a:0:{}!' ) ); + $this->assertFalse( util::is_serialized( 'a:0' ) ); + $this->assertFalse( util::is_serialized( 'This is a string' ) ); + $this->assertFalse( util::is_serialized( 'a string' ) ); + $this->assertFalse( util::is_serialized( 'z:0;' ) ); + $this->assertTrue( util::is_serialized( 'N;' ) ); + $this->assertTrue( util::is_serialized( 'b:1;' ) ); + $this->assertTrue( util::is_serialized( 'a:0:{}' ) ); + $this->assertTrue( util::is_serialized( 'O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}' ) ); + } + + public function test_fix_broken_serialization() + { + $expectedData = array( + 'Normal', + 'High-value Char: '.chr(231).'a-va?', // High-value Char: ça-va? [in ISO-8859-1] + ); + + $brokenSerialization = 'a:2:{i:0;s:6:"Normal";i:1;s:23:"High-value Char: ▒a-va?";}'; + + // Temporarily override error handling to ensure that this is, in fact, [still] a broken serialization. + { + $expectedError = array( + 'errno' => 8, + 'errstr' => 'unserialize(): Error at offset 55 of 60 bytes' + ); + + $reportedError = array(); + set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) use (&$reportedError) { + $reportedError = compact('errno', 'errstr'); + }); + + unserialize($brokenSerialization); + + $this->assertEquals($expectedError['errno'], $reportedError['errno']); + // Because HHVM's unserialize() error message does not contain enough info to properly test. + if (!defined('HHVM_VERSION')) { + $this->assertEquals($expectedError['errstr'], $reportedError['errstr']); + } + restore_error_handler(); + } + + $fixedSerialization = util::fix_broken_serialization($brokenSerialization); + $unserializedData = unserialize($fixedSerialization); + $this->assertEquals($expectedData[0], $unserializedData[0], 'Did not properly fix the broken serialized data.'); + + $this->assertEquals(substr($expectedData[1], 0, 10), substr($unserializedData[1], 0, 10), 'Did not properly fix the broken serialized data.'); + } + + public function test_is_https() + { + $_SERVER['HTTPS'] = null; + + $this->assertFalse( util::is_https() ); + + $_SERVER['HTTPS'] = 'on'; + + $this->assertTrue( util::is_https() ); + } + + public function test_add_query_arg() + { + // Regular tests + $this->assertEquals( '/app/admin/users?user=5', util::add_query_arg( 'user', 5, '/app/admin/users' ) ); + $this->assertEquals( '/app/admin/users?user=5', util::add_query_arg( array( 'user' => 5 ), '/app/admin/users' ) ); + $this->assertEquals( '/app/admin/users?user=5', util::add_query_arg( array( 'user' => 5 ), null, '/app/admin/users' ) ); + $this->assertEquals( '/app/admin/users?action=edit&user=5', util::add_query_arg( 'user', 5, '/app/admin/users?action=edit' ) ); + $this->assertEquals( '/app/admin/users?action=edit&user=5', util::add_query_arg( array( 'user' => 5 ), '/app/admin/users?action=edit' ) ); + $this->assertEquals( '/app/admin/users?action=edit&tab=personal&user=5', util::add_query_arg( 'user', 5, '/app/admin/users?action=edit&tab=personal' ) ); + $this->assertEquals( '/app/admin/users?action=edit&tab=personal&user=5', util::add_query_arg( array( 'user' => 5 ), '/app/admin/users?action=edit&tab=personal' ) ); + + // Ensure strips false. + $this->assertEquals('/index.php', util::add_query_arg('debug', false, '/index.php')); + + // With a URL fragment + $this->assertEquals( '/app/admin/users?user=5#test', util::add_query_arg( 'user', 5, '/app/admin/users#test' ) ); + + // Full URL + $this->assertEquals( 'http://example.com/?a=b', util::add_query_arg( 'a', 'b', 'http://example.com' ) ); + + // Only the query string + $this->assertEquals( '?a=b&c=d', util::add_query_arg( 'c', 'd', '?a=b' ) ); + $this->assertEquals( 'a=b&c=d', util::add_query_arg( 'c', 'd', 'a=b' ) ); + + // Url encoding test + $this->assertEquals( '/app/admin/users?param=containsa%26sym', util::add_query_arg( 'param', 'containsa&sym', '/app/admin/users' ) ); + + // If not provided, grab the URI from the server. + $_SERVER['REQUEST_URI'] = '/app/admin/users'; + $this->assertEquals( '/app/admin/users?user=6', util::add_query_arg( array( 'user' => 6 ) ) ); + $this->assertEquals( '/app/admin/users?user=7', util::add_query_arg( 'user', 7 ) ); + } + + public function test_remove_query_arg() + { + $this->assertEquals( '/app/admin/users', util::remove_query_arg( 'user', '/app/admin/users?user=5' ) ); + $this->assertEquals( '/app/admin/users?action=edit', util::remove_query_arg( 'user', '/app/admin/users?action=edit&user=5' ) ); + $this->assertEquals( '/app/admin/users?user=5', util::remove_query_arg( array( 'tab', 'action' ), '/app/admin/users?action=edit&tab=personal&user=5' ) ); + } + + public function test_http_build_url() + { + $url = 'http://user:pass@example.com:8080/path/?query#fragment'; + + $expected = 'http://example.com/'; + $actual = util::http_build_url($url, array(), util::HTTP_URL_STRIP_ALL); + $this->assertEquals($expected, $actual); + + $expected = 'http://example.com:8080/path/?query#fragment'; + $actual = util::http_build_url($url, array(), util::HTTP_URL_STRIP_AUTH); + $this->assertEquals($expected, $actual); + + $this->assertEquals('https://dev.example.com/', util::http_build_url('http://example.com/', array('scheme' => 'https', 'host' => 'dev.example.com'))); + $this->assertEquals('http://example.com/#hi', util::http_build_url('http://example.com/', array('fragment' => 'hi'), util::HTTP_URL_REPLACE)); + $this->assertEquals('http://example.com/page', util::http_build_url('http://example.com/', array('path' => 'page'), util::HTTP_URL_JOIN_PATH)); + $this->assertEquals('http://example.com/page', util::http_build_url('http://example.com', array('path' => 'page'), util::HTTP_URL_JOIN_PATH)); + $this->assertEquals('http://example.com/?hi=Bro', util::http_build_url('http://example.com/', array('query' => 'hi=Bro'), util::HTTP_URL_JOIN_QUERY)); + $this->assertEquals('http://example.com/?show=1&hi=Bro', util::http_build_url('http://example.com/?show=1', array('query' => 'hi=Bro'), util::HTTP_URL_JOIN_QUERY)); + + $this->assertEquals('http://admin@example.com/', util::http_build_url('http://example.com/', array('user' => 'admin'))); + $this->assertEquals('http://admin:1@example.com/', util::http_build_url('http://example.com/', array('user' => 'admin', 'pass' => '1'))); + } + + public function test_str_to_bool() + { + $this->assertTrue( util::str_to_bool( 'true' ) ); + $this->assertTrue( util::str_to_bool( 'yes' ) ); + $this->assertTrue( util::str_to_bool( 'y' ) ); + $this->assertTrue( util::str_to_bool( 'oui' ) ); + $this->assertTrue( util::str_to_bool( 'vrai' ) ); + + $this->assertFalse( util::str_to_bool( 'false' ) ); + $this->assertFalse( util::str_to_bool( 'no' ) ); + $this->assertFalse( util::str_to_bool( 'n' ) ); + $this->assertFalse( util::str_to_bool( 'non' ) ); + $this->assertFalse( util::str_to_bool( 'faux' ) ); + + $this->assertFalse( util::str_to_bool( 'test' , false) ); + + } + + public function test_array_pluck() + { + $array = array( + array( + 'name' => 'Bob', + 'age' => 37 + ), + array( + 'name' => 'Fred', + 'age' => 37 + ), + array( + 'name' => 'Jane', + 'age' => 29 + ), + array( + 'name' => 'Brandon', + 'age' => 20 + ), + array( + 'age' => 41 + ) + ); + + $obj_array = array( + 'bob' => (object) array( + 'name' => 'Bob', + 'age' => 37 + ), + 'fred' => (object) array( + 'name' => 'Fred', + 'age' => 37 + ), + 'jane' => (object) array( + 'name' => 'Jane', + 'age' => 29 + ), + 'brandon' => (object) array( + 'name' => 'Brandon', + 'age' => 20 + ), + 'invalid' => (object) array( + 'age' => 41 + ) + ); + + $obj_array_expect = array( + 'bob' => 'Bob', + 'fred' => 'Fred', + 'jane' => 'Jane', + 'brandon' => 'Brandon' + ); + + $this->assertEquals( array( 'Bob', 'Fred', 'Jane', 'Brandon' ), util::array_pluck( $array, 'name' ) ); + $this->assertEquals( array( 'Bob', 'Fred', 'Jane', 'Brandon', array( 'age' => 41 ) ), util::array_pluck( $array, 'name', TRUE, FALSE ) ); + $this->assertEquals( $obj_array_expect, util::array_pluck( $obj_array, 'name' ) ); + $this->assertEquals( array( 'Bob', 'Fred', 'Jane', 'Brandon' ), util::array_pluck( $obj_array, 'name', FALSE ) ); + + $expected = array('Bob', 'Fred', 'Jane', 'Brandon', 'invalid' => (object)array('age' => 41)); + $this->assertEquals($expected, util::array_pluck($obj_array, 'name', FALSE, FALSE)); + $expected = array('Bob', 'Fred', 'Jane', 'Brandon', array('age' => 41)); + $this->assertEquals($expected, util::array_pluck($array, 'name', false, false)); + } + + public function test_htmlentities() + { + $this->assertEquals( 'One & Two', util::htmlentities( 'One & Two' ) ); + $this->assertEquals( 'One & Two', util::htmlentities( 'One & Two', TRUE ) ); + } + + public function test_htmlspecialchars() + { + $this->assertEquals( 'One & Two', util::htmlspecialchars( 'One & Two' ) ); + $this->assertEquals( 'One & Two', util::htmlspecialchars( 'One & Two', TRUE ) ); + } + + public function test_remove_accents() + { + $this->assertEquals( 'A', util::remove_accents( "\xC3\x81" ) ); + $this->assertEquals( 'e', util::remove_accents( "\xC4\x97" ) ); + $this->assertEquals( 'U', util::remove_accents( "\xC3\x9C" ) ); + $this->assertEquals( 'Ae', util::remove_accents( "Ä", 'de' ) ); + $this->assertEquals( 'OEoeAEDHTHssaedhth', util::remove_accents(chr(140) . chr(156) . chr(198) . chr(208) . chr(222) . chr(223) . chr(230) . chr(240) . chr(254))); + } + + public function test_zero_pad() + { + $this->assertEquals( '00000341', util::zero_pad( 341, 8 ) ); + $this->assertEquals( '341', util::zero_pad( 341, 1 ) ); + } + + public function test_human_time_diff() + { + $this->assertEquals( '1 second ago', util::human_time_diff( time() - 1 ) ); + $this->assertEquals( '30 seconds ago', util::human_time_diff( time() - 30 ) ); + $this->assertEquals( '1 minute ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MINUTE * 1.4 ) ) ); + $this->assertEquals( '5 minutes ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MINUTE * 5 ) ) ); + $this->assertEquals( '1 hour ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR ) ) ); + $this->assertEquals( '2 hours ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 2 ) ) ); + $this->assertEquals( '1 day ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 ) ) ); + $this->assertEquals( '5 days ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 * 5 ) ) ); + $this->assertEquals( '1 week ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 * 7 ) ) ); + $this->assertEquals( '2 weeks ago', util::human_time_diff( time() - ( util::SECONDS_IN_AN_HOUR * 24 * 14 ) ) ); + $this->assertEquals( '1 month ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_WEEK * 5 ) ) ); + $this->assertEquals( '2 months ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_WEEK * 10 ) ) ); + $this->assertEquals( '1 year ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MONTH * 15 ) ) ); + $this->assertEquals( '2 years ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MONTH * 36 ) ) ); + $this->assertEquals( '11 years ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MONTH * 140 ) ) ); + + $this->assertEquals( 'fifteen minutes ago', util::human_time_diff( time() - ( util::SECONDS_IN_A_MINUTE * 15 ), '', TRUE ) ); + } + + public function test_number_to_word() + { + try { + util::number_to_word('junk data'); + $this->fail('Accepted junk data'); + } catch(\LogicException $e) { + $this->assertEquals('Not a number', $e->getMessage()); + } + + // Partially numeric. + $this->assertEquals('', util::number_to_word('1a')); + + // Decimals + $this->assertEquals( 'five point zero five', util::number_to_word('5.05') ); + $this->assertEquals( 'zero point eight', util::number_to_word( 0.8 ) ); + + // Integers + $this->assertEquals( 'positive one', util::number_to_word( '+1' ) ); + $this->assertEquals( 'negative twelve', util::number_to_word( -12 ) ); + $this->assertEquals( 'one', util::number_to_word( 1 ) ); + $this->assertEquals( 'five', util::number_to_word( 5 ) ); + $this->assertEquals( 'fifteen', util::number_to_word( 15 ) ); + $this->assertEquals( 'twenty-one', util::number_to_word( 21 ) ); + $this->assertEquals( 'thirty-two', util::number_to_word( 32 ) ); + $this->assertEquals( 'forty-three', util::number_to_word( 43 ) ); + $this->assertEquals( 'fifty-four', util::number_to_word( 54 ) ); + $this->assertEquals( 'sixty-six', util::number_to_word( 66 ) ); + $this->assertEquals( 'seventy-seven', util::number_to_word( 77 ) ); + $this->assertEquals( 'eighty-eight', util::number_to_word( 88 ) ); + $this->assertEquals( 'ninety-nine', util::number_to_word( 99 ) ); + $this->assertEquals( 'one hundred and thirty-six', util::number_to_word( 136 ) ); + $this->assertEquals( 'ten', util::number_to_word( 10 ) ); + $this->assertEquals( 'twenty', util::number_to_word( 20 ) ); + $this->assertEquals( 'thirty', util::number_to_word( 30 ) ); + $this->assertEquals( 'forty', util::number_to_word( 40 ) ); + $this->assertEquals( 'fifty', util::number_to_word( 50 ) ); + $this->assertEquals( 'sixty', util::number_to_word( 60 ) ); + $this->assertEquals( 'seventy', util::number_to_word( 70 ) ); + $this->assertEquals( 'eighty', util::number_to_word( 80 ) ); + $this->assertEquals( 'ninety', util::number_to_word( 90 ) ); + $this->assertEquals( 'eleven', util::number_to_word( 11 ) ); + $this->assertEquals( 'thirteen', util::number_to_word( 13 ) ); + $this->assertEquals( 'fourteen', util::number_to_word( 14 ) ); + $this->assertEquals( 'fifteen', util::number_to_word( 15 ) ); + $this->assertEquals( 'sixteen', util::number_to_word( 16 ) ); + $this->assertEquals( 'seventeen', util::number_to_word( 17 ) ); + $this->assertEquals( 'eighteen', util::number_to_word( 18 ) ); + $this->assertEquals( 'nineteen', util::number_to_word( 19 ) ); + $this->assertEquals( 'one thousand', util::number_to_word( 1000 ) ); + $this->assertEquals( 'one million', util::number_to_word( 1000000 ) ); + $this->assertEquals( 'one billion', util::number_to_word( 1000000000 ) ); + $this->assertEquals( 'one trillion', util::number_to_word( 1000000000000 ) ); + $this->assertEquals( 'one quadrillion', util::number_to_word( '1000000000000000' ) ); + $this->assertEquals( 'one quintrillion', util::number_to_word( '1000000000000000000' ) ); + $this->assertEquals( 'one sextillion', util::number_to_word( '1000000000000000000000' ) ); + $this->assertEquals( 'one septillion', util::number_to_word( '1000000000000000000000000' ) ); + $this->assertEquals( 'one octillion', util::number_to_word( '1000000000000000000000000000' ) ); + $this->assertEquals( 'one nonillion', util::number_to_word( '1000000000000000000000000000000' ) ); + $this->assertEquals( 'one decillion', util::number_to_word( '1000000000000000000000000000000000' ) ); + $this->assertEquals( 'one', util::number_to_word( '1000000000000000000000000000000000000000000' ) ); + + } + + public function test_array_search_deep() + { + $users = array( + 1 => (object) array( 'username' => 'brandon', 'age' => 20 ), + 2 => (object) array( 'username' => 'matt', 'age' => 27 ), + 3 => (object) array( 'username' => 'jane', 'age' => 53 ), + 4 => (object) array( 'username' => 'john', 'age' => 41 ), + 5 => (object) array( 'username' => 'steve', 'age' => 11 ), + 6 => (object) array( 'username' => 'fred', 'age' => 42 ), + 7 => (object) array( 'username' => 'rasmus', 'age' => 21 ), + 8 => (object) array( 'username' => 'don', 'age' => 15 ), + 9 => array( 'username' => 'darcy', 'age' => 33 ), + ); + + $test = array( + 1 => 'brandon', + 2 => 'devon', + 3 => array( 'troy' ), + 4 => 'annie' + ); + + $this->assertFalse( util::array_search_deep( $test, 'bob' ) ); + $this->assertEquals( 3, util::array_search_deep( $test, 'troy' ) ); + $this->assertEquals( 4, util::array_search_deep( $test, 'annie' ) ); + $this->assertEquals( 2, util::array_search_deep( $test, 'devon', 'devon' ) ); + $this->assertEquals( 7, util::array_search_deep( $users, 'rasmus', 'username' ) ); + $this->assertEquals( 9, util::array_search_deep( $users, 'darcy', 'username' ) ); + $this->assertEquals( 1, util::array_search_deep( $users, 'brandon' ) ); + } + + public function test_array_map_deep() + { + $input = array( + '<', + 'abc', + '>', + 'def', + array( '&', 'test', '123' ), + (object) array( 'hey', '<>' ) + ); + + $expect = array( + '<', + 'abc', + '>', + 'def', + array( '&', 'test', '123' ), + (object) array( 'hey', '<>' ) + ); + + $this->assertEquals( $expect, util::array_map_deep( $input, 'htmlentities' ) ); + } + + public function test_random_string() + { + // Make sure the generated string contains only human friendly characters and is 30 characters long + $str = util::random_string( 30 ); + $this->assertTrue( (bool) preg_match( '/^([ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjkmnprstuvwxyz23456789]{30})$/', $str ) ); + + // Make sure the generated string is 30 characters long + $str = util::random_string( 30, false, true ); + $this->assertTrue( strlen( $str ) === 30, 'random_string produced an invalid length string' ); + + // Make sure the generated string is 120 characters long + $str = util::random_string( 120 ); + $this->assertTrue(strlen( $str ) === 120, 'random_string produced an invalid length string'); + + // Make sure the string doesn't contain duplicate letters + $str = util::random_string( 53, true, false, true ); + $this->assertTrue(strlen($str) === 53, 'random_string produced an invalid length string'); + $this->assertTrue(count(array_unique(str_split($str))) === strlen($str), 'random_string produced a string with duplicate characters'); + + // Longer length than characters available + try { + $str = util::random_string( 55, true, false, true ); + $this->assertTrue( false ); + } catch (Exception $e) { + $this->assertTrue( true ); + } + + // Test secure variant + $str = util::secure_random_string(16); + $this->assertTrue(strlen($str) === 16); + + // Longer length than characters available + try { + $str = util::secure_random_string(0); + $this->assertTrue(false); + } catch (Exception $e) { + $this->assertTrue(true); + } + } + + public function test_match_string() + { + $this->assertTrue( util::match_string('a', 'a') ); + $this->assertFalse( util::match_string('a', ' a') ); + $this->assertFalse( util::match_string('/', '/something') ); + $this->assertTrue( util::match_string('test/*', 'test/first/second') ); + $this->assertTrue( util::match_string('*/test', 'first/second/test') ); + $this->assertFalse( util::match_string('first/', 'first/second/test') ); + $this->assertFalse( util::match_string('test', 'TEST') ); + $this->assertTrue( util::match_string('test', 'TEST', false) ); + } + + public function test_validate_email() + { + $this->assertTrue( util::validate_email( 'john.smith@gmail.com' ) ); + $this->assertTrue( util::validate_email( 'john.smith+label@gmail.com' ) ); + $this->assertTrue( util::validate_email( 'john.smith@gmail.co.uk' ) ); + } + + public function test_safe_truncate() + { + $this->assertEquals( 'The quick brown fox...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 24 ) ); + $this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 55 ) ); + $this->assertEquals( 'Th...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 2 ) ); + $this->assertEquals( 'The...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 3 ) ); + $this->assertEquals( 'The...', util::safe_truncate( 'The quick brown fox jumps over the lazy dog', 7 ) ); + } + + public function test_limit_characters() + { + $this->assertEquals( 'The quick brown fox jump...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 24 ) ); + $this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 55 ) ); + $this->assertEquals( 'Th...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 2 ) ); + $this->assertEquals( 'The...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 3 ) ); + $this->assertEquals( 'The qui...', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 7 ) ); + $this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::limit_characters( 'The quick brown fox jumps over the lazy dog', 150 ) ); + } + + public function test_limit_words() + { + $this->assertEquals( 'The quick brown...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 3 ) ); + $this->assertEquals( 'The quick brown fox jumps...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 5 ) ); + $this->assertEquals( 'The...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 1 ) ); + $this->assertEquals( 'The quick brown fox jumps over the lazy dog', util::limit_words( 'The quick brown fox jumps over the lazy dog', 90 ) ); + $this->assertEquals( 'The quick brown fox jumps over the...', util::limit_words( 'The quick brown fox jumps over the lazy dog', 7 ) ); + } + + public function test_ordinal() + { + $this->assertEquals( '1st', util::ordinal( 1 ) ); + $this->assertEquals( '2nd', util::ordinal( 2 ) ); + $this->assertEquals( '3rd', util::ordinal( 3 ) ); + $this->assertEquals( '4th', util::ordinal( 4 ) ); + $this->assertEquals( '5th', util::ordinal( 5 ) ); + $this->assertEquals( '6th', util::ordinal( 6 ) ); + $this->assertEquals( '7th', util::ordinal( 7 ) ); + $this->assertEquals( '8th', util::ordinal( 8 ) ); + $this->assertEquals( '9th', util::ordinal( 9 ) ); + $this->assertEquals( '22nd', util::ordinal( 22 ) ); + $this->assertEquals( '23rd', util::ordinal( 23 ) ); + $this->assertEquals( '143rd', util::ordinal( 143 ) ); + } + + public function test_array_first() + { + $test = array( 'a' => array( 'a', 'b', 'c' ) ); + + $this->assertEquals( 'a', util::array_first( util::array_get( $test['a'] ) ) ); + } + + public function test_array_first_key() + { + $test = array( 'a' => array( 'a' => 'b', 'c' => 'd' ) ); + + $this->assertEquals( 'a', util::array_first_key( util::array_get( $test['a'] ) ) ); + } + + public function test_array_last() + { + $test = array( 'a' => array( 'a', 'b', 'c' ) ); + + $this->assertEquals( 'c', util::array_last( util::array_get( $test['a'] ) ) ); + } + + public function test_array_last_key() + { + $test = array( 'a' => array( 'a' => 'b', 'c' => 'd' ) ); + + $this->assertEquals( 'c', util::array_last_key( util::array_get( $test['a'] ) ) ); + } + + public function test_array_flatten() + { + $input = array( 'a', 'b', 'c', 'd', array( 'first' => 'e', 'f', 'second' => 'g', array( 'h', 'third' => 'i', array( array( array( array( 'j', 'k', 'l' ) ) ) ) ) ) ); + $expectNoKeys = range( 'a', 'l' ); + $expectWithKeys = array( + 'a', 'b', 'c', 'd', + 'first' => 'e', + 'f', + 'second' => 'g', + 'h', + 'third' => 'i', + 'j', 'k', 'l' + ); + + $this->assertEquals( $expectWithKeys, util::array_flatten( $input ) ); + $this->assertEquals( $expectNoKeys, util::array_flatten( $input, false ) ); + $this->assertEquals( $expectWithKeys, util::array_flatten( $input, true ) ); + } + + public function test_strip_space() + { + $input = ' The quick brown fox jumps over the lazy dog '; + $expect = 'Thequickbrownfoxjumpsoverthelazydog'; + + $this->assertEquals($expect, Util::strip_space($input)); + } + + public function test_sanitize_string() + { + $input = ' Benoit! à New-York? j’ai perçu 1 % : Qu’as-tu "gagné" chez M. V. Noël? Dix francs.'; + $expect = 'benoitanewyorkjaipercu1quastugagnechezmvnoeldixfrancs'; + + $this->assertEquals($expect, Util::sanitize_string($input)); + } + + public function test_get_gravatar() + { + $_SERVER['HTTPS'] = 'on'; + $this->assertEquals('https://secure.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=32', util::get_gravatar('john.doe@example.org')); + $this->assertEquals('https://secure.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=128', util::get_gravatar('john.doe@example.org', 128)); + + $_SERVER['HTTPS'] = 'off'; + $this->assertEquals('http://www.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=32', util::get_gravatar('john.doe@example.org')); + $this->assertEquals('http://www.gravatar.com/avatar/a4bf5bbb9feaa2713d99a3b52ab80024?s=128', util::get_gravatar('john.doe@example.org', 128)); + } + + public function test_get_client_ip() + { + $_SERVER['REMOTE_ADDR'] = '192.168.30.152'; + $_SERVER['HTTP_CLIENT_IP'] = '192.168.30.153'; + $_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.30.154'; + $this->assertEquals('192.168.30.152', util::get_client_ip()); + $this->assertEquals('192.168.30.153', util::get_client_ip(true)); + + unset($_SERVER['HTTP_CLIENT_IP']); + $this->assertEquals('192.168.30.154', util::get_client_ip(true)); + unset($_SERVER['HTTP_X_FORWARDED_FOR']); + $this->assertEquals('192.168.30.152', util::get_client_ip(true)); + } + + public function test_full_permissions() + { + // Text a non-existant file. + $this->assertFalse(util::full_permissions('faker-123.blah'), 'Gave a permission value for a non-existant file.'); + + // Test an existing file. + $expected = '-rw-rw-rw-'; + $tempFile = tempnam(sys_get_temp_dir(), 'foo'); + $this->assertTrue(chmod($tempFile, 0666), 'Oops. Could not change temp file\'s permissions to 0666.'); + $this->assertEquals($expected, util::full_permissions($tempFile), 'Could not properly obtain permissions of an existing file.'); + unlink($tempFile); + + $this->assertEquals('lr--r--r--', util::full_permissions('fake-file-222', octdec('120444'))); + $this->assertEquals('ur--r--r--', util::full_permissions('fake-file-222', octdec('000444'))); + $this->assertEquals('srwxr-xr-x', util::full_permissions('fake-file-222', octdec('140755'))); + $this->assertEquals('drwxr-xr-x', util::full_permissions('fake-file-222', octdec('40755'))); + $this->assertEquals('brw-rw----', util::full_permissions('fake-file-222', octdec('60660'))); + $this->assertEquals('crw-rw----', util::full_permissions('fake-file-222', octdec('20660'))); + $this->assertEquals('prw-rw----', util::full_permissions('fake-file-222', octdec('10660'))); + $this->assertEquals('---x------', util::full_permissions('fake-file-222', octdec('100100'))); + $this->assertEquals('--w-------', util::full_permissions('fake-file-222', octdec('100200'))); + $this->assertEquals('--wx------', util::full_permissions('fake-file-222', octdec('100300'))); + $this->assertEquals('-r--------', util::full_permissions('fake-file-222', octdec('100400'))); + $this->assertEquals('-r-x------', util::full_permissions('fake-file-222', octdec('100500'))); + $this->assertEquals('-rw-------', util::full_permissions('fake-file-222', octdec('100600'))); + $this->assertEquals('-rwx------', util::full_permissions('fake-file-222', octdec('100700'))); + + // Windows does not have the concept of /. + if (!defined('PHP_WINDOWS_VERSION_MAJOR')) { + $this->assertEquals('drwxr-xr-x', util::full_permissions('/')); + } + } + + public function test_array_clean() + { + $input = array( 'a', 'b', '', null, false, 0); + $expect = array('a', 'b'); + $this->assertEquals($expect, Util::array_clean($input)); + } + + public function test_var_dump_plain() + { + $input = 'var'; + $expect = 'string(3) "var"'; + $this->assertEquals($expect, Util::var_dump_plain($input, true)); + + $input = true; + $expect = 'bool(true)'; + $this->assertEquals($expect, Util::var_dump_plain($input, true)); + + $input = 1; + $expect = 'int(1)'; + $this->assertEquals($expect, Util::var_dump_plain($input, true)); + + $input = 1.5; + $expect = 'float(1.5)'; + $this->assertEquals($expect, Util::var_dump_plain($input, true)); + + $input = null; + $expect = 'NULL'; + $this->assertEquals($expect, Util::var_dump_plain($input, true)); + + $input = fopen('php://memory', 'r'); + $expect = 'resource("stream") "' . $input . '"'; + $this->assertEquals($expect, Util::var_dump_plain($input, -1)); + fclose($input); + + // Test complex arrays. + $input = array(1, 2, 4, 6, 10 => 20, 100 => 200); + $actual = util::var_dump_plain($input, true); + $this->assertContains(')', $actual); + + // Test complex objects. + $experiment = new VarDumpExperiment(); + $actual = util::var_dump_plain($experiment, true); + $this->assertContains('1 => string(1', $actual); + } + + public function test_var_dump() + { + $input = 'var'; + $expect = '
string(3) "var"
'; + + // Ensure the proper output is returned + $this->assertEquals($expect, Util::var_dump($input, true)); + + // Ensure the proper output is actually outputted + $this->expectOutputString($expect); + util::var_dump($input); + + // Ensure we avoid infinite recursion on recursive arrays + $a = array('a' => 'value a', 'b' => 'value b'); + $b = array('test' => &$a); + $c = array('a' => &$a, 'b' => &$b); + $a['c'] = &$c; + $b['c'] = &$c; + $this->assertContains('*RECURSION DETECTED*', Util::var_dump($c, true)); + + // Ensure we avoid infinite recursion on recursive objects + $a = (object) array('a' => 'value a', 'b' => 'value b'); + $b = (object) array('test' => &$a); + $c = (object) array('a' => &$a, 'b' => &$b); + $a->c = &$c; + $b->c = &$c; + $this->assertContains('*RECURSION DETECTED*', Util::var_dump($c, true)); + + // Test class scoping. + $experiment = new VarDumpExperiment(); + $actual = util::var_dump($experiment, true); + + $snippet = substr($actual, strrpos($actual, 'display:inline')); + $this->assertContains('"public"', $snippet); + $this->assertContains('"protected:protected"', $snippet); + $this->assertContains('"private:VarDumpExperiment:private"', $actual); + } + + public function test_linkify() + { + $input = 'great websites: http://www.google.com?param=test and http://yahoo.com/a/nested/folder'; + $expect = 'great websites: http://www.google.com?param=test and http://yahoo.com/a/nested/folder'; + $this->assertEquals($expect, Util::linkify($input)); + + $this->assertEquals($expect, util::linkify($expect), 'linkify() tried to double linkify an href.'); + } + + public function test_start_with() + { + $this->assertTrue(Util::starts_with('start a string', 'start a')); + $this->assertFalse(Util::starts_with('start a string', 'string')); + } + + public function test_end_with() + { + $this->assertTrue(Util::ends_with('start a string', 'a string')); + $this->assertFalse(Util::ends_with('start a string', 'start')); + } + + public function test_contains() + { + $this->assertTrue(Util::str_contains('start a string', 'a string')); + $this->assertFalse(Util::str_contains('start a string', 'Start')); + } + + public function test_iContains() + { + $this->assertTrue(Util::str_icontains('start a string', 'a string')); + $this->assertTrue(Util::str_icontains('start a string', 'Start')); + } + + public function test_get_file_ext() + { + $input = 'a_pdf_fil.pdf'; + $expect = 'pdf'; + $this->assertEquals($expect, Util::get_file_ext($input)); + } + + public function test_rmdir() + { + $dirname = dirname(__FILE__); + + // Test deleting a non-existant directory + $this->assertFalse(file_exists($dirname . '/test1')); + $this->assertTrue(util::rmdir($dirname . '/test1')); + + // Test deleting an empty directory + $dir = $dirname . '/test2'; + mkdir($dir); + + $this->assertTrue(is_dir($dir)); + + if (is_dir($dir)) { + util::rmdir($dir); + $this->assertFalse(is_dir($dir)); + } + + // Test deleting a non-empty directory + $dir = $dirname . '/test3'; + $file = $dirname . '/test3/test.txt'; + mkdir($dir); + touch($file); + + $this->assertTrue(is_dir($dir)); + $this->assertTrue(is_file($file)); + + if (is_dir($dir)) { + util::rmdir($dir); + $this->assertFalse(is_dir($dir)); + $this->assertFalse(is_file($file)); + } + + // Test deleting a non-directory path + $file = $dirname . '/test4.txt'; + touch($file); + + try { + $str = util::rmdir($file); + $this->assertTrue(false); + } catch (\Exception $e) { + $this->assertTrue(true); + } + + unlink($file); + + // Test deleting a nested directory + $dir1 = $dirname . '/test5'; + $dir2 = $dirname . '/test5/nested_dir'; + $file1 = $dir1 . '/file1.txt'; + $file2 = $dir2 . '/file2.txt'; + mkdir($dir1); + mkdir($dir2); + touch($file1); + touch($file2); + + $this->assertTrue(is_dir($dir1)); + $this->assertTrue(is_dir($dir2)); + $this->assertTrue(is_file($file1)); + $this->assertTrue(is_file($file2)); + + if (is_dir($dir1)) { + util::rmdir($dir1); + $this->assertFalse(is_dir($dir1)); + $this->assertFalse(is_dir($dir2)); + $this->assertFalse(is_file($file1)); + $this->assertFalse(is_file($file2)); + } + + // Test symlink traversal. + $dir = $dirname . '/test6'; + $nestedDir = "$dir/nested"; + $symlink = "$dir/nested-symlink"; + + mkdir($dir); + mkdir($nestedDir); + + $symlinkStatus = symlink($nestedDir, $symlink); + $this->assertTrue($symlinkStatus, 'The test system does not support making symlinks.'); + + if (!$symlink) { + return; + } + + $this->assertTrue(util::rmdir($symlink, true), 'Could not delete a symlinked directory.'); + $this->assertFalse(file_exists($symlink), 'Could not delete a symlinked directory.'); + util::rmdir($dir, true); + $this->assertFalse(is_dir($dir), 'Could not delete a directory with a symlinked directory inside of it.'); + } + + public function test_get_current_url() + { + $expected = 'http://test.dev/test.php?foo=bar'; + $expectedAuth = 'http://admin:123@test.dev/test.php?foo=bar'; + $expectedPort = 'http://test.dev:443/test.php?foo=bar'; + $expectedPort2 = 'https://test.dev:80/test.php?foo=bar'; + $expectedSSL = 'https://test.dev/test.php?foo=bar'; + + $_SERVER['HTTP_HOST'] = 'test.dev'; + $_SERVER['SERVER_PORT'] = 80; + $_SERVER['REQUEST_URI'] = '/test.php?foo=bar'; + $_SERVER['QUERY_STRING'] = 'foo=bar'; + $_SERVER['PHP_SELF'] = '/test.php'; + + // Test regular. + $this->assertEquals($expected, util::get_current_url()); + + // Test server auth. + $_SERVER['PHP_AUTH_USER'] = 'admin'; + $_SERVER['PHP_AUTH_PW'] = '123'; + $this->assertEquals($expectedAuth, util::get_current_url()); + unset($_SERVER['PHP_AUTH_USER']); + unset($_SERVER['PHP_AUTH_PW']); + + // Test port. + $_SERVER['SERVER_PORT'] = 443; + $this->assertEquals($expectedPort, util::get_current_url()); + + // Test SSL. + $_SERVER['HTTPS'] = 'on'; + $this->assertEquals($expectedSSL, util::get_current_url()); + $_SERVER['SERVER_PORT'] = 80; + $this->assertEquals($expectedPort2, util::get_current_url()); + unset($_SERVER['HTTPS']); + + // Test no $_SERVER['REQUEST_URI'] (e.g., MS IIS). + unset($_SERVER['REQUEST_URI']); + $this->assertEquals($expected, util::get_current_url()); + } + + public function test_set_writable() + { + if (strncasecmp(PHP_OS, 'WIN', 3) === 0) { + $this->markTestSkipped('This functionality is not working on Windows.'); + } + + if (posix_geteuid() === 0) { + $this->markTestSkipped('These tests don\'t work when run as root'); + } + + $this->assertFalse(util::set_writable('/no/such/file')); + + // Create a file to test with + $dirname = dirname(__FILE__); + $file = $dirname . '/test7'; + touch($file); + chmod($file, 0644); + + // The file is owned by us so it should be writable + $this->assertTrue(is_writable($file)); + $this->assertEquals('-rw-r--r--', util::full_permissions($file)); + + // Toggle writable bit off for us + util::set_writable($file, false); + clearstatcache(); + $this->assertFalse(is_writable($file)); + $this->assertEquals('-r--r--r--', util::full_permissions($file)); + + // Toggle writable bit back on for us + util::set_writable($file, true); + clearstatcache(); + $this->assertTrue(is_writable($file)); + $this->assertEquals('-rw-r--r--', util::full_permissions($file)); + + unlink($file); + } + + public function test_set_readable() + { + if (strncasecmp(PHP_OS, 'WIN', 3) === 0) { + $this->markTestSkipped('This functionality is not working on Windows.'); + } + + if (posix_geteuid() === 0) { + $this->markTestSkipped('These tests don\'t work when run as root'); + } + + $this->assertFalse(util::set_readable('/no/such/file')); + + $dirname = dirname(__FILE__); + $file = $dirname . '/test8'; + touch($file); + + $this->assertTrue(is_readable($file)); + + util::set_readable($file, false); + clearstatcache(); + $this->assertFalse(is_readable($file)); + + util::set_readable($file, true); + clearstatcache(); + $this->assertTrue(is_readable($file)); + + unlink($file); + } + + public function test_set_executable() + { + if (strncasecmp(PHP_OS, 'WIN', 3) === 0) { + $this->markTestSkipped('This functionality is not working on Windows.'); + } + + if (posix_geteuid() === 0) { + $this->markTestSkipped('These tests don\'t work when run as root'); + } + + $this->assertFalse(util::set_executable('/no/such/file')); + + $dirname = dirname(__FILE__); + $file = $dirname . '/test9'; + touch($file); + + $this->assertFalse(is_executable($file)); + + util::set_executable($file, true); + clearstatcache(); + $this->assertTrue(is_executable($file)); + + util::set_executable($file, false); + clearstatcache(); + $this->assertFalse(is_executable($file)); + + unlink($file); + } + + public function test_directory_size() { + $dirname = dirname(__FILE__); + $dir = $dirname .'/dir1'; + mkdir($dir); + $file1 = $dir .'/file1'; + file_put_contents($file1, '1234567890'); + $file2 = $dir .'/file2'; + file_put_contents($file2, range('a', 'z')); + $this->assertEquals(10 + 26, util::directory_size($dir)); + util::rmdir($dir); + } + + public function test_get_user_directory() { + // Test for OS Default. + $this->assertTrue(is_writable(util::get_user_directory())); + + $oldServer = $_SERVER; + unset($_SERVER); + // Test for UNIX. + $_SERVER['HOME'] = '/home/unknown'; + $this->assertEquals($_SERVER['HOME'], util::get_user_directory(), 'Could not get the user\'s home directory in UNIX.'); + unset($_SERVER); + + // Test for Windows. + $expected = 'X:\Users\ThisUser'; + $_SERVER['HOMEDRIVE'] = 'X:'; + $_SERVER['HOMEPATH'] = '\Users\ThisUser'; + $this->assertEquals($expected, util::get_user_directory(), 'Could not get the user\'s home directory in Windows.'); + + // In case the tests are not being run in isolation. + $_SERVER = $oldServer; + } + + public function test_directory_contents() { + $dirname = dirname(__FILE__); + $dir = $dirname . DIRECTORY_SEPARATOR .'dir1'; + mkdir($dir); + $file1 = $dir . DIRECTORY_SEPARATOR .'file1'; + touch($file1); + $this->assertEquals(array($file1), util::directory_contents($dir)); + util::rmdir($dir); + } +} diff --git a/vendor/brandonwamboldt/utilphp/util.php b/vendor/brandonwamboldt/utilphp/util.php new file mode 100644 index 00000000..1b209796 --- /dev/null +++ b/vendor/brandonwamboldt/utilphp/util.php @@ -0,0 +1,10 @@ + + */ +class util extends \utilphp\util { } diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php new file mode 100644 index 00000000..dc02dfb1 --- /dev/null +++ b/vendor/composer/ClassLoader.php @@ -0,0 +1,445 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see http://www.php-fig.org/psr/psr-0/ + * @see http://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + // PSR-4 + private $prefixLengthsPsr4 = array(); + private $prefixDirsPsr4 = array(); + private $fallbackDirsPsr4 = array(); + + // PSR-0 + private $prefixesPsr0 = array(); + private $fallbackDirsPsr0 = array(); + + private $useIncludePath = false; + private $classMap = array(); + private $classMapAuthoritative = false; + private $missingClasses = array(); + private $apcuPrefix; + + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', $this->prefixesPsr0); + } + + return array(); + } + + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 base directories + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + } + + /** + * Unregisters this instance as an autoloader. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return bool|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath.'\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + */ +function includeFile($file) +{ + include $file; +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 00000000..f27399a0 --- /dev/null +++ b/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 00000000..af2fd3b1 --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,16 @@ + $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', + 'DBHelper' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', + 'DBTransaction' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', + 'MeekroDB' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', + 'MeekroDBEval' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', + 'MeekroDBException' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', + 'WhereClause' => $vendorDir . '/sergeytsalkov/meekrodb/db.class.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 00000000..bf34e7c9 --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,10 @@ + array($vendorDir . '/brandonwamboldt/utilphp/src'), +); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php new file mode 100644 index 00000000..f44fc383 --- /dev/null +++ b/vendor/composer/autoload_psr4.php @@ -0,0 +1,10 @@ + array($vendorDir . '/league/plates/src'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 00000000..afca66f6 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,52 @@ += 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + } + + $loader->register(true); + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 00000000..ac3cfb2c --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,53 @@ + + array ( + 'League\\Plates\\' => 14, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'League\\Plates\\' => + array ( + 0 => __DIR__ . '/..' . '/league/plates/src', + ), + ); + + public static $prefixesPsr0 = array ( + 'u' => + array ( + 'utilphp\\' => + array ( + 0 => __DIR__ . '/..' . '/brandonwamboldt/utilphp/src', + ), + ), + ); + + public static $classMap = array ( + 'DB' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + 'DBHelper' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + 'DBTransaction' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + 'MeekroDB' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + 'MeekroDBEval' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + 'MeekroDBException' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + 'WhereClause' => __DIR__ . '/..' . '/sergeytsalkov/meekrodb/db.class.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$prefixDirsPsr4; + $loader->prefixesPsr0 = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$prefixesPsr0; + $loader->classMap = ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 00000000..b52416a5 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,152 @@ +[ + { + "name": "brandonwamboldt/utilphp", + "version": "1.1.0", + "version_normalized": "1.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/brandonwamboldt/utilphp.git", + "reference": "36c32efc4f0679c05163464a550f45c8d83fe683" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brandonwamboldt/utilphp/zipball/36c32efc4f0679c05163464a550f45c8d83fe683", + "reference": "36c32efc4f0679c05163464a550f45c8d83fe683", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "satooshi/php-coveralls": "dev-master" + }, + "time": "2015-02-02T17:56:14+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "utilphp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brandon Wamboldt", + "email": "brandon.wamboldt@gmail.com" + } + ], + "description": "util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects", + "homepage": "https://github.com/brandonwamboldt/utilphp", + "keywords": [ + "collection", + "helpers", + "php", + "utility" + ] + }, + { + "name": "league/plates", + "version": "3.3.0", + "version_normalized": "3.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/plates.git", + "reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/plates/zipball/b1684b6f127714497a0ef927ce42c0b44b45a8af", + "reference": "b1684b6f127714497a0ef927ce42c0b44b45a8af", + "shasum": "" + }, + "require": { + "php": "^5.3 | ^7.0" + }, + "require-dev": { + "mikey179/vfsstream": "^1.4", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~1.5" + }, + "time": "2016-12-28T00:14:17+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\Plates\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jonathan Reinink", + "email": "jonathan@reinink.ca", + "role": "Developer" + } + ], + "description": "Plates, the native PHP template system that's fast, easy to use and easy to extend.", + "homepage": "http://platesphp.com", + "keywords": [ + "league", + "package", + "templates", + "templating", + "views" + ] + }, + { + "name": "sergeytsalkov/meekrodb", + "version": "v2.3", + "version_normalized": "2.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/SergeyTsalkov/meekrodb.git", + "reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/SergeyTsalkov/meekrodb/zipball/eb36858f1aff94ae1665900e681a1cfb78563ee1", + "reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1", + "shasum": "" + }, + "require": { + "php": ">=5.2.0" + }, + "time": "2014-06-16T22:40:22+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "classmap": [ + "db.class.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0" + ], + "authors": [ + { + "name": "Sergey Tsalkov", + "email": "stsalkov@gmail.com" + } + ], + "description": "The Simple PHP/MySQL Library", + "homepage": "http://www.meekro.com", + "keywords": [ + "database", + "mysql", + "mysqli", + "pdo" + ] + } +] diff --git a/vendor/league/plates/CONTRIBUTING.md b/vendor/league/plates/CONTRIBUTING.md new file mode 100644 index 00000000..9eebab6e --- /dev/null +++ b/vendor/league/plates/CONTRIBUTING.md @@ -0,0 +1,22 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/plates). + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. +- **Consider our release cycle** - We try to follow semver. Randomly breaking public APIs is not an option. +- **Create topic branches** - Don't ask us to pull from your master branch. +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +## Running Tests + +``` bash +$ phpunit +``` +**Happy coding**! \ No newline at end of file diff --git a/vendor/league/plates/LICENSE b/vendor/league/plates/LICENSE new file mode 100644 index 00000000..26357d46 --- /dev/null +++ b/vendor/league/plates/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 The League of Extraordinary Packages + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/vendor/league/plates/README.md b/vendor/league/plates/README.md new file mode 100644 index 00000000..56679e19 --- /dev/null +++ b/vendor/league/plates/README.md @@ -0,0 +1,63 @@ +Plates +====== + +[![Author](http://img.shields.io/badge/author-@reinink-blue.svg?style=flat-square)](https://twitter.com/reinink) +[![Source Code](http://img.shields.io/badge/source-league/plates-blue.svg?style=flat-square)](https://github.com/thephpleague/plates) +[![Latest Version](https://img.shields.io/github/release/thephpleague/plates.svg?style=flat-square)](https://github.com/thephpleague/plates/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) +[![Build Status](https://img.shields.io/travis/thephpleague/plates/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/plates) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates) +[![Total Downloads](https://img.shields.io/packagist/dt/league/plates.svg?style=flat-square)](https://packagist.org/packages/league/plates) + +Plates is a native PHP template system that's fast, easy to use and easy to extend. It's inspired by the excellent [Twig](http://twig.sensiolabs.org/) template engine and strives to bring modern template language functionality to native PHP templates. Plates is designed for developers who prefer to use native PHP templates over compiled template languages, such as Twig or Smarty. + +### Highlights + +- Native PHP templates, no new [syntax](http://platesphp.com/templates/syntax/) to learn +- Plates is a template system, not a template language +- Plates encourages the use of existing PHP functions +- Increase code reuse with template [layouts](http://platesphp.com/templates/layouts/) and [inheritance](http://platesphp.com/templates/inheritance/) +- Template [folders](http://platesphp.com/engine/folders/) for grouping templates into namespaces +- [Data](http://platesphp.com/templates/data/#preassigned-and-shared-data) sharing across templates +- Preassign [data](http://platesphp.com/templates/data/#preassigned-and-shared-data) to specific templates +- Built-in [escaping](http://platesphp.com/templates/escaping/) helpers +- Easy to extend using [functions](http://platesphp.com/engine/functions/) and [extensions](http://platesphp.com/engine/extensions/) +- Framework-agnostic, will work with any project +- Decoupled design makes templates easy to test +- Composer ready and PSR-2 compliant + +## Installation + +Plates is available via Composer: + +``` +composer require league/plates +``` + +## Documentation + +Full documentation can be found at [platesphp.com](http://platesphp.com/). + +## Testing + +```bash +phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/thephpleague/plates/blob/master/CONTRIBUTING.md) for details. + +## Security + +If you discover any security related issues, please email jonathan@reinink.ca instead of using the issue tracker. + +## Credits + +- [Jonathan Reinink](https://github.com/reinink) +- [All Contributors](https://github.com/thephpleague/plates/contributors) + +## License + +The MIT License (MIT). Please see [License File](https://github.com/thephpleague/plates/blob/master/LICENSE) for more information. diff --git a/vendor/league/plates/composer.json b/vendor/league/plates/composer.json new file mode 100644 index 00000000..8971a983 --- /dev/null +++ b/vendor/league/plates/composer.json @@ -0,0 +1,41 @@ +{ + "name": "league/plates", + "description": "Plates, the native PHP template system that's fast, easy to use and easy to extend.", + "keywords": [ + "league", + "package", + "templating", + "templates", + "views" + ], + "homepage": "http://platesphp.com", + "license": "MIT", + "authors" : [ + { + "name": "Jonathan Reinink", + "email": "jonathan@reinink.ca", + "role": "Developer" + } + ], + "require" : { + "php": "^5.3 | ^7.0" + }, + "require-dev": { + "mikey179/vfsStream": "^1.4", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~1.5" + }, + "autoload": { + "psr-4": { + "League\\Plates\\": "src" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "scripts": { + "test": "phpunit" + } +} diff --git a/vendor/league/plates/docs/CNAME b/vendor/league/plates/docs/CNAME new file mode 100644 index 00000000..1e00c34f --- /dev/null +++ b/vendor/league/plates/docs/CNAME @@ -0,0 +1 @@ +platesphp.com \ No newline at end of file diff --git a/vendor/league/plates/docs/_data/images.yml b/vendor/league/plates/docs/_data/images.yml new file mode 100644 index 00000000..56d11839 --- /dev/null +++ b/vendor/league/plates/docs/_data/images.yml @@ -0,0 +1,8 @@ +# Path to project specific favicon.ico, leave blank to use default +favicon: /favicon.ico + +# Path to project specific apple-touch-icon-precomposed.png, leave blank to use default +apple_touch: /apple-touch-icon-precomposed.png + +# Path to project logo +logo: /logo.png \ No newline at end of file diff --git a/vendor/league/plates/docs/_data/menu.yml b/vendor/league/plates/docs/_data/menu.yml new file mode 100644 index 00000000..317a0e4f --- /dev/null +++ b/vendor/league/plates/docs/_data/menu.yml @@ -0,0 +1,24 @@ +Getting Started: + Introduction: '/' + Simple example: '/simple-example/' + Installation: '/installation/' + Changelog: '/changelog/' +The Engine: + Overview: '/engine/' + File extensions: '/engine/file-extensions/' + Folders: '/engine/folders/' + Functions: '/engine/functions/' + Extensions: '/engine/extensions/' +Templates: + Overview: '/templates/' + Data: '/templates/data/' + Functions: '/templates/functions/' + Nesting: '/templates/nesting/' + Layouts: '/templates/layouts/' + Sections: '/templates/sections/' + Inheritance: '/templates/inheritance/' + Escaping: '/templates/escaping/' + Syntax: '/templates/syntax/' +Extensions: + Asset: '/extensions/asset/' + URI: '/extensions/uri/' \ No newline at end of file diff --git a/vendor/league/plates/docs/_data/project.yml b/vendor/league/plates/docs/_data/project.yml new file mode 100644 index 00000000..4ff76f30 --- /dev/null +++ b/vendor/league/plates/docs/_data/project.yml @@ -0,0 +1,4 @@ +title: Plates +tagline: Native PHP Templates +description: 'Plates is a Twig inspired, native PHP template system that brings modern template language functionality to native PHP templates.' +google_analytics_tracking_id: UA-46050814-2 \ No newline at end of file diff --git a/vendor/league/plates/docs/_layouts/default.html b/vendor/league/plates/docs/_layouts/default.html new file mode 100644 index 00000000..72042e30 --- /dev/null +++ b/vendor/league/plates/docs/_layouts/default.html @@ -0,0 +1,107 @@ + + + + + + + {% if page.url == '/' %} + {{ site.data.project.title }} - {{ site.data.project.tagline }} + {% else %} + {{ page.title }} - {{ site.data.project.title }} + {% endif %} + {% if site.data.project.description %} + + {% endif %} + {% if site.github.url %} + + {% endif %} + {% if site.data.images.favicon %} + + {% else %} + + {% endif %} + {% if site.data.images.apple_touch %} + + {% else %} + + {% endif %} + + + + + + + Fork me on GitHub + + +
+ + The League of Extraordinary Packages + +

Our Packages:

+
    + +
+
+ +
+ + + Presented by The League of Extraordinary Packages + +
+ + + + +
+ + {% for section in site.data.menu %} +

{{ section[0] }}

+
    + {% for link in section[1] %} +
  • + {{ link[0] }} +
  • + {% endfor %} +
+ {% endfor %} +
+
+ {{ content }} +
+
+ + + + + + + +{% if site.data.project.google_analytics_tracking_id %} + +{% endif %} + + + \ No newline at end of file diff --git a/vendor/league/plates/docs/apple-touch-icon-precomposed.png b/vendor/league/plates/docs/apple-touch-icon-precomposed.png new file mode 100644 index 00000000..460a2ba1 Binary files /dev/null and b/vendor/league/plates/docs/apple-touch-icon-precomposed.png differ diff --git a/vendor/league/plates/docs/changelog.md b/vendor/league/plates/docs/changelog.md new file mode 100644 index 00000000..a471991d --- /dev/null +++ b/vendor/league/plates/docs/changelog.md @@ -0,0 +1,15 @@ +--- +layout: default +permalink: changelog/ +title: Changelog +--- + +Changelog +========= + +All notable changes to this project will be documented in this file. + +{% for release in site.github.releases %} +## [{{ release.name }}]({{ release.html_url }}) - {{ release.published_at | date: "%Y-%m-%d" }} +{{ release.body | markdownify }} +{% endfor %} \ No newline at end of file diff --git a/vendor/league/plates/docs/css/custom.scss b/vendor/league/plates/docs/css/custom.scss new file mode 100644 index 00000000..6bef9794 --- /dev/null +++ b/vendor/league/plates/docs/css/custom.scss @@ -0,0 +1,16 @@ +--- +--- + +.github { + position: absolute; + top: 0; + right: 0; + border: 0; + z-index: 1000; +} + +@media screen and (max-width: 1065px) { + .github { + display: none; + } +} \ No newline at end of file diff --git a/vendor/league/plates/docs/engine/extensions.md b/vendor/league/plates/docs/engine/extensions.md new file mode 100644 index 00000000..c40868a5 --- /dev/null +++ b/vendor/league/plates/docs/engine/extensions.md @@ -0,0 +1,120 @@ +--- +layout: default +permalink: engine/extensions/ +title: Extensions +--- + +Extensions +========== + +Creating extensions couldn't be easier, and can really make Plates sing for your specific project. Start by creating a class that implements `\League\Plates\Extension\ExtensionInterface`. Next, register your template [functions](/engine/functions/) within a `register()` method. + +## Simple extensions example + +~~~ php +use League\Plates\Engine; +use League\Plates\Extension\ExtensionInterface; + +class ChangeCase implements ExtensionInterface +{ + public function register(Engine $engine) + { + $engine->registerFunction('uppercase', [$this, 'uppercaseString']); + $engine->registerFunction('lowercase', [$this, 'lowercaseString']); + } + + public function uppercaseString($var) + { + return strtoupper($var); + } + + public function lowercaseString($var) + { + return strtolower($var); + } +} +~~~ + +To use this extension in your template, simply call your new functions: + +~~~ php +

Hello, e($this->uppercase($name))?>

+~~~ + +They can also be used in a [batch](/templates/functions/#batch-function-calls) compatible function: + +~~~ php +

Hello e($name, 'uppercase')

+~~~ + +## Single method extensions + +Alternatively, you may choose to expose the entire extension object to the template using a single function. This can make your templates more legible and also reduce the chance of conflicts with other extensions. + +~~~ php +use League\Plates\Engine; +use League\Plates\Extension\ExtensionInterface; + +class ChangeCase implements ExtensionInterface +{ + public function register(Engine $engine) + { + $engine->registerFunction('case', [$this, 'getObject']); + } + + public function getObject() + { + return $this; + } + + public function upper($var) + { + return strtoupper($var); + } + + public function lower($var) + { + return strtolower($var); + } +} +~~~ + +To use this extension in your template, first call the primary function, then the secondary functions: + +~~~ php +

Hello, e($this->case()->upper($name))?>

+~~~ + +## Loading extensions + +To enable an extension, load it into the [engine](/engine/) object using the `loadExtension()` method. + +~~~ php +$engine->loadExtension(new ChangeCase()); +~~~ + +## Accessing the engine and template + +It may be desirable to access the `engine` or `template` objects from within your extension. Plates makes both of these objects available to you. The engine is automatically passed to the `register()` method, and the template is assigned as a parameter on each function call. + +~~~ php +use League\Plates\Engine; +use League\Plates\Extension\ExtensionInterface; + +class MyExtension implements ExtensionInterface +{ + protected $engine; + public $template; // must be public + + public function register(Engine $engine) + { + $this->engine = $engine; + + // Access template data: + $data = $this->template->data(); + + // Register functions + // ... + } +} +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/engine/file-extensions.md b/vendor/league/plates/docs/engine/file-extensions.md new file mode 100644 index 00000000..613bccf4 --- /dev/null +++ b/vendor/league/plates/docs/engine/file-extensions.md @@ -0,0 +1,36 @@ +--- +layout: default +permalink: engine/file-extensions/ +title: File extensions +--- + +File extensions +=============== + +Plates does not enforce a specific template file extension. By default it assumes `.php`. This file extension is automatically appended to your template names when rendered. You are welcome to change the default extension using one of the following methods. + +## Constructor method + +~~~ php +// Create new engine and set the default file extension to ".tpl" +$template = new League\Plates\Engine('/path/to/templates', 'tpl'); +~~~ + +## Setter method + +~~~ php +// Sets the default file extension to ".tpl" after engine instantiation +$template->setFileExtension('tpl'); +~~~ + +## Manually assign + +If you prefer to manually set the file extension, simply set the default file extension to `null`. + +~~~ php +// Disable automatic file extensions +$template->setFileExtension(null); + +// Render template +echo $templates->render('home.php'); +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/engine/folders.md b/vendor/league/plates/docs/engine/folders.md new file mode 100644 index 00000000..7991bfcd --- /dev/null +++ b/vendor/league/plates/docs/engine/folders.md @@ -0,0 +1,50 @@ +--- +layout: default +permalink: engine/folders/ +title: Folders +--- + +Folders +======= + +Folders make it really easy to organize and access your templates. Folders allow you to group your templates under different namespaces, each of which having their own file system path. + +## Creating folders + +To create folders, use the `addFolder()` method: + +~~~ php +// Create new Plates instance +$templates = new League\Plates\Engine(); + +// Add folders +$templates->addFolder('admin', '/path/to/admin/templates'); +$templates->addFolder('emails', '/path/to/email/templates'); +~~~ + +## Using folders + +To use the folders you created within your project simply append the folder name with two colons before the template name. For example, to render a welcome email: + +~~~ php +$email = $templates->render('emails::welcome'); +~~~ + +This works with template functions as well, such as layouts or nested templates. For example: + +~~~ php +layout('shared::template') ?> +~~~ + +## Folder fallbacks + +When enabled, if a folder template is missing, Plates will automatically fallback and look for a template with the **same** name in the default folder. This can be helpful when using folders to manage themes. To enable fallbacks, simply pass `true` as the third parameter in the `addFolders()` method. + +~~~ php +// Create new Plates engine +$templates = new \League\Plates\Engine('/path/to/default/theme'); + +// Add themes +$templates->addFolder('theme1', '/path/to/theme/1', true); +$templates->addFolder('theme2', '/path/to/theme/2', true); +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/engine/functions.md b/vendor/league/plates/docs/engine/functions.md new file mode 100644 index 00000000..b677ec57 --- /dev/null +++ b/vendor/league/plates/docs/engine/functions.md @@ -0,0 +1,34 @@ +--- +layout: default +permalink: engine/functions/ +title: Functions +--- + +Functions +========= + +While [extensions](/engine/extensions/) are awesome for adding additional reusable functionality to Plates, sometimes it's easier to just create a one-off function for a specific use case. Plates makes this easy to do. + +## Registering functions + +~~~ php +// Create new Plates engine +$templates = new \League\Plates\Engine('/path/to/templates'); + +// Register a one-off function +$templates->registerFunction('uppercase', function ($string) { + return strtoupper($string); +}); +~~~ + +To use this function in a template, simply call it like any other function: + +~~~ php +

Hello e($this->uppercase($name))

+~~~ + +It can also be used in a [batch](/templates/functions/#batch-function-calls) compatible function: + +~~~ php +

Hello e($name, 'uppercase')

+~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/engine/index.md b/vendor/league/plates/docs/engine/index.md new file mode 100644 index 00000000..6d428796 --- /dev/null +++ b/vendor/league/plates/docs/engine/index.md @@ -0,0 +1,56 @@ +--- +layout: default +permalink: engine/ +title: The Engine +--- + +The Engine +========== + +Plates uses a central object called the `Engine`, which is used to store the environment configuration, functions and extensions. It helps decouple your templates from the file system and other dependencies. For example, if you want to change the folder where your templates are stored, you can do so by simply changing the path in one location. + +## Basic usage + +~~~ php +// Create new Plates engine +$templates = new League\Plates\Engine('/path/to/templates'); + +// Add any any additional folders +$templates->addFolder('emails', '/path/to/emails'); + +// Load any additional extensions +$templates->loadExtension(new League\Plates\Extension\Asset('/path/to/public')); + +// Create a new template +$template = $templates->make('emails::welcome'); +~~~ + +## Dependency Injection + +Plates is designed to be easily passed around your application and easily injected in your controllers or other application objects. Simply pass an instance of the `Engine` to any consuming objects, and then use either the `make()` method to create a new template, or the `render()` method to render it immediately. For example: + +~~~ php +class Controller +{ + private $templates; + + public function __construct(League\Plates\Engine $templates) + { + $this->templates = $templates; + } + + // Create a template object + public function getIndex() + { + $template = $this->templates->make('home'); + + return $template->render(); + } + + // Render a template directly + public function getIndex() + { + return $this->templates->render('home'); + } +} +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/extensions/asset.md b/vendor/league/plates/docs/extensions/asset.md new file mode 100644 index 00000000..6a1d40e6 --- /dev/null +++ b/vendor/league/plates/docs/extensions/asset.md @@ -0,0 +1,59 @@ +--- +layout: default +permalink: extensions/asset/ +title: Asset extension +--- + +Asset +===== + +The asset extension can be used to quickly create "cache busted" asset URLs in your templates. This is particularly helpful for aggressively cached files that can potentially change in the future, such as CSS files, JavaScript files and images. It works by appending the timestamp of the file's last update to its URL. For example, `/css/all.css` becomes `/css/all.1373577602.css`. As long as the file does not change, the timestamp remains the same and caching occurs. However, if the file is changed, a new URL is automatically generated with a new timestamp, and visitors receive the new file. + +## Installing the asset extension + +The asset extension comes packaged with Plates but is not enabled by default, as it requires extra parameters passed to it at instantiation. + +~~~ php +// Load asset extension +$engine->loadExtension(new League\Plates\Extension\Asset('/path/to/public/assets/', true)); +~~~ + +The first constructor parameter is the file system path of the assets directory. The second is an optional `boolean` parameter that if set to true uses the filename caching method (ie. `file.1373577602.css`) instead of the default query string method (ie. `file.css?v=1373577602`). + +## Filename caching + +To make filename caching work, some URL rewriting is required: + +### Apache example +~~~ php + + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L] + +~~~ + +### Nginx example + +~~~ php +location ~* (.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$ { + try_files $uri $1.$2; +} +~~~ + +## Using the asset extension + +~~~ php + + + Asset Extension Example + + + + + + + + + +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/extensions/uri.md b/vendor/league/plates/docs/extensions/uri.md new file mode 100644 index 00000000..e18c2060 --- /dev/null +++ b/vendor/league/plates/docs/extensions/uri.md @@ -0,0 +1,83 @@ +--- +layout: default +permalink: extensions/uri/ +title: URI extension +--- + +URI +=== + +The URI extension is designed to make URI checks within templates easier. The most common use is marking the current page in a menu as "selected". It only has one function, `uri()`, but can do a number of helpful tasks depending on the parameters passed to it. + +## Installing the URI extension + +The URI extension comes packaged with Plates but is not enabled by default, as it requires an extra parameter passed to it at instantiation. + +~~~ php +// Load URI extension using global variable +$engine->loadExtension(new League\Plates\Extension\URI($_SERVER['PATH_INFO'])); + +// Load URI extension using a HttpFoundation's request object +$engine->loadExtension(new League\Plates\Extension\URI($request->getPathInfo())); +~~~ + +## URI example + +~~~ php +
    +
  • uri('/', 'class="selected"')?>>Home
  • +
  • uri('/about', 'class="selected"')?>>About
  • +
  • uri('/products', 'class="selected"')?>>Products
  • +
  • uri('/contact', 'class="selected"')?>>Contact
  • +
+~~~ + +## Using the URI extension + +Get the whole URI. + +~~~ php +uri()?> +~~~ + +Get a specified segment of the URI. + +~~~ php +uri(1)?> +~~~ + +Check if a specific segment of the URI (first parameter) equals a given string (second parameter). Returns `true` on success or `false` on failure. + +~~~ php +uri(1, 'home')): ?> +~~~ + +Check if a specific segment of the URI (first parameter) equals a given string (second parameter). Returns string (third parameter) on success or `false` on failure. + +~~~ php +uri(1, 'home', 'success')?> +~~~ + +Check if a specific segment of the URI (first parameter) equals a given string (second parameter). Returns string (third parameter) on success or string (fourth parameter) on failure. + +~~~ php +uri(1, 'home', 'success', 'fail')?> +~~~ + +Check if a regular expression string matches the current URI. Returns `true` on success or `false` on failure. + +~~~ php +uri('/home')): ?> +~~~ + +Check if a regular expression string (first parameter) matches the current URI. Returns string (second parameter) on success or `false` on failure. + +~~~ php +uri('/home', 'success')?> +~~~ + +Check if a regular expression string (first parameter) matches the current URI. Returns string (second parameter) on success or string (third parameter) on failure. + +~~~ php +uri('/home', 'success', 'fail')?> +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/favicon.ico b/vendor/league/plates/docs/favicon.ico new file mode 100644 index 00000000..44d7f3ff Binary files /dev/null and b/vendor/league/plates/docs/favicon.ico differ diff --git a/vendor/league/plates/docs/index.md b/vendor/league/plates/docs/index.md new file mode 100644 index 00000000..3c342719 --- /dev/null +++ b/vendor/league/plates/docs/index.md @@ -0,0 +1,40 @@ +--- +layout: default +permalink: / +title: Introduction +--- + +Introduction +============ + +[![Author](http://img.shields.io/badge/author-@reinink-blue.svg?style=flat-square)](https://twitter.com/reinink) +[![Source Code](http://img.shields.io/badge/source-league/plates-blue.svg?style=flat-square)](https://github.com/thephpleague/plates) +[![Latest Version](https://img.shields.io/github/release/thephpleague/plates.svg?style=flat-square)](https://github.com/thephpleague/plates/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/thephpleague/plates/blob/master/LICENSE)
+[![Build Status](https://img.shields.io/travis/thephpleague/plates/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/plates) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/plates.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/plates) +[![Total Downloads](https://img.shields.io/packagist/dt/league/plates.svg?style=flat-square)](https://packagist.org/packages/league/plates) + +## About + +Plates is a native PHP template system that's fast, easy to use and easy to extend. It's inspired by the excellent [Twig](http://twig.sensiolabs.org/) template engine and strives to bring modern template language functionality to native PHP templates. Plates is designed for developers who prefer to use native PHP templates over compiled template languages, such as Twig or Smarty. + +## Highlights + +- Native PHP templates, no new [syntax](/templates/syntax/) to learn +- Plates is a template system, not a template language +- Plates encourages the use of existing PHP functions +- Increase code reuse with template [layouts](/templates/layouts/) and [inheritance](/templates/inheritance/) +- Template [folders](/engine/folders/) for grouping templates into namespaces +- [Data](/templates/data/#preassigned-and-shared-data) sharing across templates +- Preassign [data](/templates/data/#preassigned-and-shared-data) to specific templates +- Built-in [escaping](/templates/escaping/) helpers +- Easy to extend using [functions](/engine/functions/) and [extensions](/engine/extensions/) +- Framework-agnostic, will work with any project +- Decoupled design makes templates easy to test +- Composer ready and PSR-2 compliant + +## Questions? + +Plates was created by [Jonathan Reinink](https://twitter.com/reinink). Submit issues to [Github](https://github.com/thephpleague/plates/issues). diff --git a/vendor/league/plates/docs/installation.md b/vendor/league/plates/docs/installation.md new file mode 100644 index 00000000..ba7a2b63 --- /dev/null +++ b/vendor/league/plates/docs/installation.md @@ -0,0 +1,35 @@ +--- +layout: default +permalink: installation/ +title: Installation +--- + +Installation +============ + +## Using Composer + +Plates is available on [Packagist](https://packagist.org/packages/league/plates) and can be installed using [Composer](https://getcomposer.org/). This can be done by running the following command or by updating your `composer.json` file. + +~~~ bash +composer require league/plates +~~~ + +
composer.json
+~~~ javascript +{ + "require": { + "league/plates": "3.*" + } +} +~~~ + +Be sure to also include your Composer autoload file in your project: + +~~~ php +require 'vendor/autoload.php'; +~~~ + +## Downloading .zip file + +This project is also available for download as a `.zip` file on GitHub. Visit the [releases page](https://github.com/thephpleague/plates/releases), select the version you want, and click the "Source code (zip)" download button. \ No newline at end of file diff --git a/vendor/league/plates/docs/logo.png b/vendor/league/plates/docs/logo.png new file mode 100644 index 00000000..19cf68a7 Binary files /dev/null and b/vendor/league/plates/docs/logo.png differ diff --git a/vendor/league/plates/docs/simple-example.md b/vendor/league/plates/docs/simple-example.md new file mode 100644 index 00000000..35f9b71d --- /dev/null +++ b/vendor/league/plates/docs/simple-example.md @@ -0,0 +1,54 @@ +--- +layout: default +permalink: simple-example/ +title: Simple example +--- + +Simple example +============== + +Here is a simple example of how to use Plates. We will assume the following directory stucture: + +~~~ +`-- path + `-- to + `-- templates + |-- template.php + |-- profile.php +~~~ + +## Within your controller + +~~~ php +// Create new Plates instance +$templates = new League\Plates\Engine('/path/to/templates'); + +// Render a template +echo $templates->render('profile', ['name' => 'Jonathan']); +~~~ + +## The page template + +
profile.php
+~~~ php +layout('template', ['title' => 'User Profile']) ?> + +

User Profile

+

Hello, e($name)?>

+~~~ + +## The layout template + +
template.php
+~~~ php + + + <?=$this->e($title)?> + + + +section('content')?> + + + +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/data.md b/vendor/league/plates/docs/templates/data.md new file mode 100644 index 00000000..33bfb2aa --- /dev/null +++ b/vendor/league/plates/docs/templates/data.md @@ -0,0 +1,61 @@ +--- +layout: default +permalink: templates/data/ +title: Data +--- + +Data +==== + +It's very common to share application data (variables) with a template. Data can be whatever you want: strings, arrays, objects, etc. Plates allows you set both template specific data as well as shared template data. + +## Assign data + +Assigning data is done from within your application code, such as a controller. There are a number of ways to assign the data, depending on how you structure your objects. + +~~~ php +// Create new Plates instance +$templates = new League\Plates\Engine('/path/to/templates'); + +// Assign via the engine's render method +echo $templates->render('profile', ['name' => 'Jonathan']); + +// Assign via the engine's make method +$template = $templates->make('profile', ['name' => 'Jonathan']); + +// Assign directly to a template object +$template = $templates->make('profile'); +$template->data(['name' => 'Jonathan']); +~~~ + +## Accessing data + +Template data is available as locally scoped variables at the time of rendering. Continuing with the example above, here is how you would [escape](/templates/escaping/) and output the "name" value in a template: + +~~~ php +

Hello e($name)?>

+~~~ + +

Prior to Plates 3.0, variables were accessed using the $this pseudo-variable. This is no longer possible. Use the locally scoped variables instead.

+ +## Preassigned and shared data + +If you have data that you want assigned to a specific template each time that template is rendered throughout your application, the `addData()` function can help organize that code in one place. + +~~~ php +$templates->addData(['name' => 'Jonathan'], 'emails::welcome'); +~~~ + +You can pressaign data to more than one template by passing an array of templates: + +~~~ php +$templates->addData(['name' => 'Jonathan'], ['login', 'template']); +~~~ + +To assign data to ALL templates, simply omit the second parameter: + +~~~ php +$templates->addData(['name' => 'Jonathan']); +~~~ + +Keep in mind that shared data is assigned to a template when it's first created, meaning any conflicting data assigned that's afterwards to a specific template will overwrite the shared data. This is generally desired behavior. \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/escaping.md b/vendor/league/plates/docs/templates/escaping.md new file mode 100644 index 00000000..4dcd2f62 --- /dev/null +++ b/vendor/league/plates/docs/templates/escaping.md @@ -0,0 +1,50 @@ +--- +layout: default +permalink: templates/escaping/ +title: Escaping +--- + +Escaping +======== + +Escaping is a form of [data filtering](http://www.phptherightway.com/#data_filtering) which sanitizes unsafe, user supplied input prior to outputting it as HTML. Plates provides two shortcuts to the `htmlspecialchars()` function. + +## Escaping example + +~~~ php +

Hello, escape($name)?>

+ + +

Hello, e($name)?>

+~~~ + +## Batch function calls + +The escape functions also support [batch](/templates/functions/#batch-function-calls) function calls, which allow you to apply multiple functions, including native PHP functions, to a variable at one time. + +~~~ php +

Welcome e($name, 'strip_tags|strtoupper')?>

+~~~ + +## Escaping HTML attributes + +

It's VERY important to always double quote HTML attributes that contain escaped variables, otherwise your template will still be open to injection attacks.

+ +Some [libraries](http://framework.zend.com/manual/2.1/en/modules/zend.escaper.escaping-html-attributes.html) go as far as having a special function for escaping HTML attributes. However, this is somewhat redundant considering that if a developer forgets to properly quote an HTML attribute, they will likely also forget to use this special function. Here is how you properly escape HTML attributes: + +~~~ php + +<?=$this->e($name)?> + + +<?=$this->e($name)?> + + +<?=$this-e($name)?>> +~~~ + +## Automatic escaping + +Probably the biggest drawbacks to native PHP templates is the inability to auto-escape variables properly. Template languages like Twig and Smarty can identify "echoed" variables during a parsing stage and automatically escape them. This cannot be done in native PHP as the language does not offer overloading functionality for it's output functions (ie. `print` and `echo`). + +Don't worry, escaping can still be done safely, it just means you are responsible for manually escaping each variable on output. Consider creating a snippet for one of the above, built-in escaping functions to make this process easier. \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/functions.md b/vendor/league/plates/docs/templates/functions.md new file mode 100644 index 00000000..234d9cf1 --- /dev/null +++ b/vendor/league/plates/docs/templates/functions.md @@ -0,0 +1,47 @@ +--- +layout: default +permalink: templates/functions/ +title: Functions +--- + +Functions +========= + +Template functions in Plates are accessed using the `$this` pseudo-variable. + +~~~ php +

Hello, escape($name)?>

+~~~ + + +## Custom fuctions + +In addition to the functions included with Plates, it's also possible to add [one-off functions](/engine/functions/), or even groups of functions, known as [extensions](/engine/extensions/). + +## Batch function calls + +Sometimes you need to apply more than function to a variable in your templates. This can become somewhat illegible. The `batch()` function helps by allowing you to apply multiple functions, including native PHP functions, to a variable at one time. + +~~~ php + +

Welcome escape(strtoupper(strip_tags($name)))?>

+ + +

Welcome batch($name, 'strip_tags|strtoupper|escape')?>

+~~~ + +The [escape](/templates/escaping/) functions also support batch function calls. + +~~~ php +

Welcome e($name, 'strip_tags|strtoupper')?>

+~~~ + +The batch functions works well for "piped" functions that accept one parameter, modify it, and then return it. It's important to note that they execute functions left to right and will favour extension functions over native PHP functions if there are conflicts. + +~~~ php + +batch('Jonathan', 'escape|strtolower|strtoupper')?> + + +batch('Jonathan', 'escape|strtoupper|strtolower')?> +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/index.md b/vendor/league/plates/docs/templates/index.md new file mode 100644 index 00000000..f08f1469 --- /dev/null +++ b/vendor/league/plates/docs/templates/index.md @@ -0,0 +1,73 @@ +--- +layout: default +permalink: templates/ +title: Templates +--- + +Templates +========= + +Plates templates are very simple PHP objects. Generally you'll want to create these using the two factory methods, `make()` and `render()`, in the [engine](/engine/). For example: + +~~~ php +// Create new Plates instance +$templates = new League\Plates\Engine('/path/to/templates'); + +// Render a template in a subdirectory +echo $templates->render('partials/header'); + +// Render a template +echo $templates->render('profile', ['name' => 'Jonathan']); +~~~ + +For more information about how Plates is designed to be easily added to your application, see the section on [dependency injection](/engine/#dependency-injection). + +## Manually creating templates + +It's also possible to create templates manually. The only dependency they require is an instance of the [engine](/engine/) object. For example: + +~~~ php +// Create new Plates instance +$templates = new League\Plates\Engine('/path/to/templates'); + +// Create a new template +$template = new League\Plates\Template\Template($templates, 'profile'); + +// Render the template +echo $template->render(['name' => 'Jonathan']); + +// You can also render the template using the toString() magic method +echo $template; +~~~ + +## Check if a template exists + +When dynamically loading templates, you may need to check if they exist. This can be done using the engine's `exists()` method: + +~~~ php +if ($templates->exists('articles::beginners_guide')) { + // It exists! +} +~~~ + +You can also run this check on an existing template: + +~~~ php +if ($template->exists()) { + // It exists! +} +~~~ + +## Get a template path + +To get a template path from its name, use the engine's `path()` method: + +~~~ php +$path = $templates->path('articles::beginners_guide'); +~~~ + +You can also get the path from an existing template: + +~~~ php +$path = $template->path(); +~~~ diff --git a/vendor/league/plates/docs/templates/inheritance.md b/vendor/league/plates/docs/templates/inheritance.md new file mode 100644 index 00000000..9b0f211a --- /dev/null +++ b/vendor/league/plates/docs/templates/inheritance.md @@ -0,0 +1,63 @@ +--- +layout: default +permalink: templates/inheritance/ +title: Inheritance +--- + +Inheritance +=========== + +By combining [layouts](/templates/layouts/) and [sections](/templates/sections/), Plates allows you to "build up" your pages using predefined sections. This is best understand using an example: + + +## Inheritance example + +The following example illustrates a pretty standard website. Start by creating a site template, which includes your header and footer as well as any predefined content [sections](/templates/sections/). Notice how Plates makes it possible to even set default section content, in the event that a page doesn't define it. + +
template.php
+~~~ php + + + <?=$this->e($title)?> + + + + + +
+ section('page')?> +
+ + + + + +~~~ + +With the template defined, any page can now "implement" this [layout](/templates/layouts/). Notice how each section of content is defined between the `start()` and `end()` functions. + +
profile.php
+~~~ php +layout('template', ['title' => 'User Profile']) ?> + +start('page') ?> +

Welcome!

+

Hello e($name)?>

+stop() ?> + +start('sidebar') ?> + +stop() ?> +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/layouts.md b/vendor/league/plates/docs/templates/layouts.md new file mode 100644 index 00000000..63c871df --- /dev/null +++ b/vendor/league/plates/docs/templates/layouts.md @@ -0,0 +1,102 @@ +--- +layout: default +permalink: templates/layouts/ +title: Layouts +--- + +Layouts +======= + +The `layout()` function allows you to define a layout template that a template will implement. It's like having separate header and footer templates in one file. + +## Define a layout + +The `layout()` function can be called anywhere in a template, since the layout template is actually rendered second. Typically it's placed at the top of the file. + +~~~ php +layout('template') ?> + +

User Profile

+

Hello, e($name)?>

+~~~ + +This function also works with [folders](/engine/folders/): + +~~~ php +layout('shared::template') ?> +~~~ + +## Assign data + +To assign data (variables) to a layout template, pass them as an array to the `layout()` function. This data will then be available as locally scoped variables within the layout template. + +~~~ php +layout('template', ['title' => 'User Profile']) ?> +~~~ + +## Accessing the content + +To access the rendered template content within the layout, use the `section()` function, passing `'content'` as the section name. This will return all outputted content from the template that hasn't been defined in a [section](/templates/sections/). + +~~~ php + + + <?=$this->e($title)?> + + + +section('content')?> + + + +~~~ + +## Stacked layouts + +Plates allows stacking of layouts, allowing even further simplification and organization of templates. Instead of just using one main layout, it's possible to break templates into more specific layouts, which themselves implement a main layout. Consider this example: + +### The main site layout + +
template.php
+~~~ php + + + <?=$this->e($title)?> + + + +section('content')?> + + + +~~~ + +### The blog layout + +
blog.php
+~~~ php +layout('template') ?> + +

The Blog

+ +
+
+ section('content')?> +
+ +
+~~~ + +### A blog article + +
blog-article.php
+~~~ php +layout('blog', ['title' => $article->title]) ?> + +

e($article->title)?>

+
+ e($article->content)?> +
+~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/nesting.md b/vendor/league/plates/docs/templates/nesting.md new file mode 100644 index 00000000..bc60aeb9 --- /dev/null +++ b/vendor/league/plates/docs/templates/nesting.md @@ -0,0 +1,44 @@ +--- +layout: default +permalink: templates/nesting/ +title: Nesting +--- + +Nesting +======= + +Including another template into the current template is done using the `insert()` function: + +~~~ php +insert('partials/header') ?> + +

Your content.

+ +insert('partials/footer') ?> +~~~ + +The `insert()` function also works with [folders](/engine/folders/): + +~~~ php +insert('partials::header') ?> +~~~ + +## Alternative syntax + +The `insert()` function automatically outputs the rendered template. If you prefer to manually output the response, use the `fetch()` function instead: + +~~~ php +fetch('partials/header')?> +~~~ + +## Assign data + +To assign data (variables) to a nested template, pass them as an array to the `insert()` or `fetch()` functions. This data will then be available as locally scoped variables within the nested template. + +~~~ php +insert('partials/header', ['name' => 'Jonathan']) ?> + +

Your content.

+ +insert('partials/footer') ?> +~~~ \ No newline at end of file diff --git a/vendor/league/plates/docs/templates/sections.md b/vendor/league/plates/docs/templates/sections.md new file mode 100644 index 00000000..a5cadcd3 --- /dev/null +++ b/vendor/league/plates/docs/templates/sections.md @@ -0,0 +1,80 @@ +--- +layout: default +permalink: templates/sections/ +title: Sections +--- + +Sections +======== + +The `start()` and `stop` functions allow you to build sections (or blocks) of content within your template, and instead of them being rendered directly, they are saved for use elsewhere. For example, in your [layout](/templates/layouts/) template. + +## Creating sections + +You define the name of the section with the `start()` function. To end a section call the `stop()` function. + +~~~ php +start('welcome') ?> + +

Welcome!

+

Hello e($name)?>

+ +stop() ?> +~~~ + +## Stacking section content + +By default, when you render a section its content will overwrite any existing content for that section. However, it's possible to append (or stack) the content instead using the `push()` method. This can be useful for specifying any JavaScript libraries required by your child views. + +~~~ php +push('scripts') ?> + +end() ?> +~~~ + +

The end() function is simply an alias of stop(). These functions can be used interchangeably.

+ +## Accessing section content + +Access rendered section content using the name you assigned in the `start()` method. This variable can be accessed from the current template and layout templates using the `section()` function. + +~~~ php +section('welcome')?> +~~~ + +

Prior to Plates 3.0, accessing template content was done using either the content() or child() functions. For consistency with sections, this is no longer possible.

+ +## Default section content + +In situations where a page doesn't implement a particular section, it's helpful to assign default content. There are a couple ways to do this: + +### Defining it inline + +If the default content can be defined in a single line of code, it's best to simply pass it as the second parameter of the `content()` function. + +~~~ php + +~~~ + +### Use an if statement + +If the default content requires more than a single line of code, it's best to use a simple if statement to check if a section exists, and otherwise display the default. + +~~~ php + +~~~ + diff --git a/vendor/league/plates/docs/templates/syntax.md b/vendor/league/plates/docs/templates/syntax.md new file mode 100644 index 00000000..c2a78e9c --- /dev/null +++ b/vendor/league/plates/docs/templates/syntax.md @@ -0,0 +1,50 @@ +--- +layout: default +permalink: templates/syntax/ +title: Syntax +--- + +Syntax +====== + +While the actual syntax you use in your templates is entirely your choice (it's just PHP after all), we suggest the following syntax guidelines to help keep templates clean and legible. + +## Guidelines + +- Always use HTML with inline PHP. Never use blocks of PHP. +- Always escape potentially dangerous variables prior to outputting using the built-in escape functions. More on escaping [here](/templates/escaping/). +- Always use the short echo syntax (`layout('template', ['title' => 'User Profile']) ?> + +

Welcome!

+

Hello e($name)?>

+ +

Friends

+ + + +

Invitations

+

You have some friend invites!

+ +~~~ diff --git a/vendor/league/plates/example/example.php b/vendor/league/plates/example/example.php new file mode 100644 index 00000000..aaffe052 --- /dev/null +++ b/vendor/league/plates/example/example.php @@ -0,0 +1,12 @@ +addData(['company' => 'The Company Name'], 'layout'); + +// Render a template +echo $templates->render('profile', ['name' => 'Jonathan']); diff --git a/vendor/league/plates/example/templates/layout.php b/vendor/league/plates/example/templates/layout.php new file mode 100644 index 00000000..5b5847cf --- /dev/null +++ b/vendor/league/plates/example/templates/layout.php @@ -0,0 +1,12 @@ + + + <?=$this->e($title)?> | <?=$this->e($company)?> + + + +section('content')?> + +section('scripts')?> + + + \ No newline at end of file diff --git a/vendor/league/plates/example/templates/profile.php b/vendor/league/plates/example/templates/profile.php new file mode 100644 index 00000000..0797e463 --- /dev/null +++ b/vendor/league/plates/example/templates/profile.php @@ -0,0 +1,12 @@ +layout('layout', ['title' => 'User Profile']) ?> + +

User Profile

+

Hello, e($name)?>!

+ +insert('sidebar') ?> + +push('scripts') ?> + +end() ?> \ No newline at end of file diff --git a/vendor/league/plates/example/templates/sidebar.php b/vendor/league/plates/example/templates/sidebar.php new file mode 100644 index 00000000..13d9ea83 --- /dev/null +++ b/vendor/league/plates/example/templates/sidebar.php @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/vendor/league/plates/phpunit.xml.dist b/vendor/league/plates/phpunit.xml.dist new file mode 100644 index 00000000..aae18548 --- /dev/null +++ b/vendor/league/plates/phpunit.xml.dist @@ -0,0 +1,20 @@ + + + + + tests/ + + + + + src/ + + + + + + + + + + diff --git a/vendor/league/plates/src/Engine.php b/vendor/league/plates/src/Engine.php new file mode 100644 index 00000000..6c89642b --- /dev/null +++ b/vendor/league/plates/src/Engine.php @@ -0,0 +1,279 @@ +directory = new Directory($directory); + $this->fileExtension = new FileExtension($fileExtension); + $this->folders = new Folders(); + $this->functions = new Functions(); + $this->data = new Data(); + } + + /** + * Set path to templates directory. + * @param string|null $directory Pass null to disable the default directory. + * @return Engine + */ + public function setDirectory($directory) + { + $this->directory->set($directory); + + return $this; + } + + /** + * Get path to templates directory. + * @return string + */ + public function getDirectory() + { + return $this->directory->get(); + } + + /** + * Set the template file extension. + * @param string|null $fileExtension Pass null to manually set it. + * @return Engine + */ + public function setFileExtension($fileExtension) + { + $this->fileExtension->set($fileExtension); + + return $this; + } + + /** + * Get the template file extension. + * @return string + */ + public function getFileExtension() + { + return $this->fileExtension->get(); + } + + /** + * Add a new template folder for grouping templates under different namespaces. + * @param string $name + * @param string $directory + * @param boolean $fallback + * @return Engine + */ + public function addFolder($name, $directory, $fallback = false) + { + $this->folders->add($name, $directory, $fallback); + + return $this; + } + + /** + * Remove a template folder. + * @param string $name + * @return Engine + */ + public function removeFolder($name) + { + $this->folders->remove($name); + + return $this; + } + + /** + * Get collection of all template folders. + * @return Folders + */ + public function getFolders() + { + return $this->folders; + } + + /** + * Add preassigned template data. + * @param array $data; + * @param null|string|array $templates; + * @return Engine + */ + public function addData(array $data, $templates = null) + { + $this->data->add($data, $templates); + + return $this; + } + + /** + * Get all preassigned template data. + * @param null|string $template; + * @return array + */ + public function getData($template = null) + { + return $this->data->get($template); + } + + /** + * Register a new template function. + * @param string $name; + * @param callback $callback; + * @return Engine + */ + public function registerFunction($name, $callback) + { + $this->functions->add($name, $callback); + + return $this; + } + + /** + * Remove a template function. + * @param string $name; + * @return Engine + */ + public function dropFunction($name) + { + $this->functions->remove($name); + + return $this; + } + + /** + * Get a template function. + * @param string $name + * @return Func + */ + public function getFunction($name) + { + return $this->functions->get($name); + } + + /** + * Check if a template function exists. + * @param string $name + * @return boolean + */ + public function doesFunctionExist($name) + { + return $this->functions->exists($name); + } + + /** + * Load an extension. + * @param ExtensionInterface $extension + * @return Engine + */ + public function loadExtension(ExtensionInterface $extension) + { + $extension->register($this); + + return $this; + } + + /** + * Load multiple extensions. + * @param array $extensions + * @return Engine + */ + public function loadExtensions(array $extensions = array()) + { + foreach ($extensions as $extension) { + $this->loadExtension($extension); + } + + return $this; + } + + /** + * Get a template path. + * @param string $name + * @return string + */ + public function path($name) + { + $name = new Name($this, $name); + + return $name->getPath(); + } + + /** + * Check if a template exists. + * @param string $name + * @return boolean + */ + public function exists($name) + { + $name = new Name($this, $name); + + return $name->doesPathExist(); + } + + /** + * Create a new template. + * @param string $name + * @return Template + */ + public function make($name) + { + return new Template($this, $name); + } + + /** + * Create a new template and render it. + * @param string $name + * @param array $data + * @return string + */ + public function render($name, array $data = array()) + { + return $this->make($name)->render($data); + } +} diff --git a/vendor/league/plates/src/Extension/Asset.php b/vendor/league/plates/src/Extension/Asset.php new file mode 100644 index 00000000..91d39f66 --- /dev/null +++ b/vendor/league/plates/src/Extension/Asset.php @@ -0,0 +1,85 @@ +path = rtrim($path, '/'); + $this->filenameMethod = $filenameMethod; + } + + /** + * Register extension function. + * @param Engine $engine + * @return null + */ + public function register(Engine $engine) + { + $engine->registerFunction('asset', array($this, 'cachedAssetUrl')); + } + + /** + * Create "cache busted" asset URL. + * @param string $url + * @return string + */ + public function cachedAssetUrl($url) + { + $filePath = $this->path . '/' . ltrim($url, '/'); + + if (!file_exists($filePath)) { + throw new LogicException( + 'Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.' + ); + } + + $lastUpdated = filemtime($filePath); + $pathInfo = pathinfo($url); + + if ($pathInfo['dirname'] === '.') { + $directory = ''; + } elseif ($pathInfo['dirname'] === '/') { + $directory = '/'; + } else { + $directory = $pathInfo['dirname'] . '/'; + } + + if ($this->filenameMethod) { + return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension']; + } + + return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated; + } +} diff --git a/vendor/league/plates/src/Extension/ExtensionInterface.php b/vendor/league/plates/src/Extension/ExtensionInterface.php new file mode 100644 index 00000000..0164d1ea --- /dev/null +++ b/vendor/league/plates/src/Extension/ExtensionInterface.php @@ -0,0 +1,13 @@ +uri = $uri; + $this->parts = explode('/', $this->uri); + } + + /** + * Register extension functions. + * @param Engine $engine + * @return null + */ + public function register(Engine $engine) + { + $engine->registerFunction('uri', array($this, 'runUri')); + } + + /** + * Perform URI check. + * @param null|integer|string $var1 + * @param mixed $var2 + * @param mixed $var3 + * @param mixed $var4 + * @return mixed + */ + public function runUri($var1 = null, $var2 = null, $var3 = null, $var4 = null) + { + if (is_null($var1)) { + return $this->uri; + } + + if (is_numeric($var1) and is_null($var2)) { + return array_key_exists($var1, $this->parts) ? $this->parts[$var1] : null; + } + + if (is_numeric($var1) and is_string($var2)) { + return $this->checkUriSegmentMatch($var1, $var2, $var3, $var4); + } + + if (is_string($var1)) { + return $this->checkUriRegexMatch($var1, $var2, $var3); + } + + throw new LogicException('Invalid use of the uri function.'); + } + + /** + * Perform a URI segment match. + * @param integer $key + * @param string $string + * @param mixed $returnOnTrue + * @param mixed $returnOnFalse + * @return mixed + */ + protected function checkUriSegmentMatch($key, $string, $returnOnTrue = null, $returnOnFalse = null) + { + if (array_key_exists($key, $this->parts) && $this->parts[$key] === $string) { + return is_null($returnOnTrue) ? true : $returnOnTrue; + } + + return is_null($returnOnFalse) ? false : $returnOnFalse; + } + + /** + * Perform a regular express match. + * @param string $regex + * @param mixed $returnOnTrue + * @param mixed $returnOnFalse + * @return mixed + */ + protected function checkUriRegexMatch($regex, $returnOnTrue = null, $returnOnFalse = null) + { + if (preg_match('#^' . $regex . '$#', $this->uri) === 1) { + return is_null($returnOnTrue) ? true : $returnOnTrue; + } + + return is_null($returnOnFalse) ? false : $returnOnFalse; + } +} diff --git a/vendor/league/plates/src/Template/Data.php b/vendor/league/plates/src/Template/Data.php new file mode 100644 index 00000000..aa4d1e1e --- /dev/null +++ b/vendor/league/plates/src/Template/Data.php @@ -0,0 +1,93 @@ +shareWithAll($data); + } + + if (is_array($templates)) { + return $this->shareWithSome($data, $templates); + } + + if (is_string($templates)) { + return $this->shareWithSome($data, array($templates)); + } + + throw new LogicException( + 'The templates variable must be null, an array or a string, ' . gettype($templates) . ' given.' + ); + } + + /** + * Add data shared with all templates. + * @param array $data; + * @return Data + */ + public function shareWithAll($data) + { + $this->sharedVariables = array_merge($this->sharedVariables, $data); + + return $this; + } + + /** + * Add data shared with some templates. + * @param array $data; + * @param array $templates; + * @return Data + */ + public function shareWithSome($data, array $templates) + { + foreach ($templates as $template) { + if (isset($this->templateVariables[$template])) { + $this->templateVariables[$template] = array_merge($this->templateVariables[$template], $data); + } else { + $this->templateVariables[$template] = $data; + } + } + + return $this; + } + + /** + * Get template data. + * @param null|string $template; + * @return array + */ + public function get($template = null) + { + if (isset($template, $this->templateVariables[$template])) { + return array_merge($this->sharedVariables, $this->templateVariables[$template]); + } + + return $this->sharedVariables; + } +} diff --git a/vendor/league/plates/src/Template/Directory.php b/vendor/league/plates/src/Template/Directory.php new file mode 100644 index 00000000..f5de5374 --- /dev/null +++ b/vendor/league/plates/src/Template/Directory.php @@ -0,0 +1,53 @@ +set($path); + } + + /** + * Set path to templates directory. + * @param string|null $path Pass null to disable the default directory. + * @return Directory + */ + public function set($path) + { + if (!is_null($path) and !is_dir($path)) { + throw new LogicException( + 'The specified path "' . $path . '" does not exist.' + ); + } + + $this->path = $path; + + return $this; + } + + /** + * Get path to templates directory. + * @return string + */ + public function get() + { + return $this->path; + } +} diff --git a/vendor/league/plates/src/Template/FileExtension.php b/vendor/league/plates/src/Template/FileExtension.php new file mode 100644 index 00000000..57646bdd --- /dev/null +++ b/vendor/league/plates/src/Template/FileExtension.php @@ -0,0 +1,45 @@ +set($fileExtension); + } + + /** + * Set the template file extension. + * @param null|string $fileExtension + * @return FileExtension + */ + public function set($fileExtension) + { + $this->fileExtension = $fileExtension; + + return $this; + } + + /** + * Get the template file extension. + * @return string + */ + public function get() + { + return $this->fileExtension; + } +} diff --git a/vendor/league/plates/src/Template/Folder.php b/vendor/league/plates/src/Template/Folder.php new file mode 100644 index 00000000..01fcbdd2 --- /dev/null +++ b/vendor/league/plates/src/Template/Folder.php @@ -0,0 +1,109 @@ +setName($name); + $this->setPath($path); + $this->setFallback($fallback); + } + + /** + * Set the folder name. + * @param string $name + * @return Folder + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Get the folder name. + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set the folder path. + * @param string $path + * @return Folder + */ + public function setPath($path) + { + if (!is_dir($path)) { + throw new LogicException('The specified directory path "' . $path . '" does not exist.'); + } + + $this->path = $path; + + return $this; + } + + /** + * Get the folder path. + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Set the folder fallback status. + * @param boolean $fallback + * @return Folder + */ + public function setFallback($fallback) + { + $this->fallback = $fallback; + + return $this; + } + + /** + * Get the folder fallback status. + * @return boolean + */ + public function getFallback() + { + return $this->fallback; + } +} diff --git a/vendor/league/plates/src/Template/Folders.php b/vendor/league/plates/src/Template/Folders.php new file mode 100644 index 00000000..9bf266a7 --- /dev/null +++ b/vendor/league/plates/src/Template/Folders.php @@ -0,0 +1,75 @@ +exists($name)) { + throw new LogicException('The template folder "' . $name . '" is already being used.'); + } + + $this->folders[$name] = new Folder($name, $path, $fallback); + + return $this; + } + + /** + * Remove a template folder. + * @param string $name + * @return Folders + */ + public function remove($name) + { + if (!$this->exists($name)) { + throw new LogicException('The template folder "' . $name . '" was not found.'); + } + + unset($this->folders[$name]); + + return $this; + } + + /** + * Get a template folder. + * @param string $name + * @return Folder + */ + public function get($name) + { + if (!$this->exists($name)) { + throw new LogicException('The template folder "' . $name . '" was not found.'); + } + + return $this->folders[$name]; + } + + /** + * Check if a template folder exists. + * @param string $name + * @return boolean + */ + public function exists($name) + { + return isset($this->folders[$name]); + } +} diff --git a/vendor/league/plates/src/Template/Func.php b/vendor/league/plates/src/Template/Func.php new file mode 100644 index 00000000..79141f46 --- /dev/null +++ b/vendor/league/plates/src/Template/Func.php @@ -0,0 +1,107 @@ +setName($name); + $this->setCallback($callback); + } + + /** + * Set the function name. + * @param string $name + * @return Func + */ + public function setName($name) + { + if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name) !== 1) { + throw new LogicException( + 'Not a valid function name.' + ); + } + + $this->name = $name; + + return $this; + } + + /** + * Get the function name. + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set the function callback + * @param callable $callback + * @return Func + */ + public function setCallback($callback) + { + if (!is_callable($callback, true)) { + throw new LogicException( + 'Not a valid function callback.' + ); + } + + $this->callback = $callback; + + return $this; + } + + /** + * Get the function callback. + * @return callable + */ + public function getCallback() + { + return $this->callback; + } + + /** + * Call the function. + * @param Template $template + * @param array $arguments + * @return mixed + */ + public function call(Template $template = null, $arguments = array()) + { + if (is_array($this->callback) and + isset($this->callback[0]) and + $this->callback[0] instanceof ExtensionInterface + ) { + $this->callback[0]->template = $template; + } + + return call_user_func_array($this->callback, $arguments); + } +} diff --git a/vendor/league/plates/src/Template/Functions.php b/vendor/league/plates/src/Template/Functions.php new file mode 100644 index 00000000..e0e4c2c1 --- /dev/null +++ b/vendor/league/plates/src/Template/Functions.php @@ -0,0 +1,78 @@ +exists($name)) { + throw new LogicException( + 'The template function name "' . $name . '" is already registered.' + ); + } + + $this->functions[$name] = new Func($name, $callback); + + return $this; + } + + /** + * Remove a template function. + * @param string $name; + * @return Functions + */ + public function remove($name) + { + if (!$this->exists($name)) { + throw new LogicException( + 'The template function "' . $name . '" was not found.' + ); + } + + unset($this->functions[$name]); + + return $this; + } + + /** + * Get a template function. + * @param string $name + * @return Func + */ + public function get($name) + { + if (!$this->exists($name)) { + throw new LogicException('The template function "' . $name . '" was not found.'); + } + + return $this->functions[$name]; + } + + /** + * Check if a template function exists. + * @param string $name + * @return boolean + */ + public function exists($name) + { + return isset($this->functions[$name]); + } +} diff --git a/vendor/league/plates/src/Template/Name.php b/vendor/league/plates/src/Template/Name.php new file mode 100644 index 00000000..a999d74d --- /dev/null +++ b/vendor/league/plates/src/Template/Name.php @@ -0,0 +1,202 @@ +setEngine($engine); + $this->setName($name); + } + + /** + * Set the engine. + * @param Engine $engine + * @return Name + */ + public function setEngine(Engine $engine) + { + $this->engine = $engine; + + return $this; + } + + /** + * Get the engine. + * @return Engine + */ + public function getEngine() + { + return $this->engine; + } + + /** + * Set the original name and parse it. + * @param string $name + * @return Name + */ + public function setName($name) + { + $this->name = $name; + + $parts = explode('::', $this->name); + + if (count($parts) === 1) { + $this->setFile($parts[0]); + } elseif (count($parts) === 2) { + $this->setFolder($parts[0]); + $this->setFile($parts[1]); + } else { + throw new LogicException( + 'The template name "' . $this->name . '" is not valid. ' . + 'Do not use the folder namespace separator "::" more than once.' + ); + } + + return $this; + } + + /** + * Get the original name. + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set the parsed template folder. + * @param string $folder + * @return Name + */ + public function setFolder($folder) + { + $this->folder = $this->engine->getFolders()->get($folder); + + return $this; + } + + /** + * Get the parsed template folder. + * @return string + */ + public function getFolder() + { + return $this->folder; + } + + /** + * Set the parsed template file. + * @param string $file + * @return Name + */ + public function setFile($file) + { + if ($file === '') { + throw new LogicException( + 'The template name "' . $this->name . '" is not valid. ' . + 'The template name cannot be empty.' + ); + } + + $this->file = $file; + + if (!is_null($this->engine->getFileExtension())) { + $this->file .= '.' . $this->engine->getFileExtension(); + } + + return $this; + } + + /** + * Get the parsed template file. + * @return string + */ + public function getFile() + { + return $this->file; + } + + /** + * Resolve template path. + * @return string + */ + public function getPath() + { + if (is_null($this->folder)) { + return $this->getDefaultDirectory() . DIRECTORY_SEPARATOR . $this->file; + } + + $path = $this->folder->getPath() . DIRECTORY_SEPARATOR . $this->file; + + if (!is_file($path) and $this->folder->getFallback() and is_file($this->getDefaultDirectory() . DIRECTORY_SEPARATOR . $this->file)) { + $path = $this->getDefaultDirectory() . DIRECTORY_SEPARATOR . $this->file; + } + + return $path; + } + + /** + * Check if template path exists. + * @return boolean + */ + public function doesPathExist() + { + return is_file($this->getPath()); + } + + /** + * Get the default templates directory. + * @return string + */ + protected function getDefaultDirectory() + { + $directory = $this->engine->getDirectory(); + + if (is_null($directory)) { + throw new LogicException( + 'The template name "' . $this->name . '" is not valid. '. + 'The default directory has not been defined.' + ); + } + + return $directory; + } +} diff --git a/vendor/league/plates/src/Template/Template.php b/vendor/league/plates/src/Template/Template.php new file mode 100644 index 00000000..0a88c8cf --- /dev/null +++ b/vendor/league/plates/src/Template/Template.php @@ -0,0 +1,346 @@ +engine = $engine; + $this->name = new Name($engine, $name); + + $this->data($this->engine->getData($name)); + } + + /** + * Magic method used to call extension functions. + * @param string $name + * @param array $arguments + * @return mixed + */ + public function __call($name, $arguments) + { + return $this->engine->getFunction($name)->call($this, $arguments); + } + + /** + * Alias for render() method. + * @throws \Throwable + * @throws \Exception + * @return string + */ + public function __toString() + { + return $this->render(); + } + + /** + * Assign or get template data. + * @param array $data + * @return mixed + */ + public function data(array $data = null) + { + if (is_null($data)) { + return $this->data; + } + + $this->data = array_merge($this->data, $data); + } + + /** + * Check if the template exists. + * @return boolean + */ + public function exists() + { + return $this->name->doesPathExist(); + } + + /** + * Get the template path. + * @return string + */ + public function path() + { + return $this->name->getPath(); + } + + /** + * Render the template and layout. + * @param array $data + * @throws \Throwable + * @throws \Exception + * @return string + */ + public function render(array $data = array()) + { + $this->data($data); + unset($data); + extract($this->data); + + if (!$this->exists()) { + throw new LogicException( + 'The template "' . $this->name->getName() . '" could not be found at "' . $this->path() . '".' + ); + } + + try { + $level = ob_get_level(); + ob_start(); + + include $this->path(); + + $content = ob_get_clean(); + + if (isset($this->layoutName)) { + $layout = $this->engine->make($this->layoutName); + $layout->sections = array_merge($this->sections, array('content' => $content)); + $content = $layout->render($this->layoutData); + } + + return $content; + } catch (Throwable $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } catch (Exception $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } + } + + /** + * Set the template's layout. + * @param string $name + * @param array $data + * @return null + */ + public function layout($name, array $data = array()) + { + $this->layoutName = $name; + $this->layoutData = $data; + } + + /** + * Start a new section block. + * @param string $name + * @return null + */ + public function start($name) + { + if ($name === 'content') { + throw new LogicException( + 'The section name "content" is reserved.' + ); + } + + if ($this->sectionName) { + throw new LogicException('You cannot nest sections within other sections.'); + } + + $this->sectionName = $name; + + ob_start(); + } + + /** + * Start a new append section block. + * @param string $name + * @return null + */ + public function push($name) + { + $this->appendSection = true; + + $this->start($name); + } + + /** + * Stop the current section block. + * @return null + */ + public function stop() + { + if (is_null($this->sectionName)) { + throw new LogicException( + 'You must start a section before you can stop it.' + ); + } + + if (!isset($this->sections[$this->sectionName])) { + $this->sections[$this->sectionName] = ''; + } + + $this->sections[$this->sectionName] = $this->appendSection ? $this->sections[$this->sectionName] . ob_get_clean() : ob_get_clean(); + $this->sectionName = null; + $this->appendSection = false; + } + + /** + * Alias of stop(). + * @return null + */ + public function end() + { + $this->stop(); + } + + /** + * Returns the content for a section block. + * @param string $name Section name + * @param string $default Default section content + * @return string|null + */ + public function section($name, $default = null) + { + if (!isset($this->sections[$name])) { + return $default; + } + + return $this->sections[$name]; + } + + /** + * Fetch a rendered template. + * @param string $name + * @param array $data + * @return string + */ + public function fetch($name, array $data = array()) + { + return $this->engine->render($name, $data); + } + + /** + * Output a rendered template. + * @param string $name + * @param array $data + * @return null + */ + public function insert($name, array $data = array()) + { + echo $this->engine->render($name, $data); + } + + /** + * Apply multiple functions to variable. + * @param mixed $var + * @param string $functions + * @return mixed + */ + public function batch($var, $functions) + { + foreach (explode('|', $functions) as $function) { + if ($this->engine->doesFunctionExist($function)) { + $var = call_user_func(array($this, $function), $var); + } elseif (is_callable($function)) { + $var = call_user_func($function, $var); + } else { + throw new LogicException( + 'The batch function could not find the "' . $function . '" function.' + ); + } + } + + return $var; + } + + /** + * Escape string. + * @param string $string + * @param null|string $functions + * @return string + */ + public function escape($string, $functions = null) + { + static $flags; + + if (!isset($flags)) { + $flags = ENT_QUOTES | (defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0); + } + + if ($functions) { + $string = $this->batch($string, $functions); + } + + return htmlspecialchars($string, $flags, 'UTF-8'); + } + + /** + * Alias to escape function. + * @param string $string + * @param null|string $functions + * @return string + */ + public function e($string, $functions = null) + { + return $this->escape($string, $functions); + } +} diff --git a/vendor/sergeytsalkov/meekrodb/.gitignore b/vendor/sergeytsalkov/meekrodb/.gitignore new file mode 100644 index 00000000..55317fd6 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/.gitignore @@ -0,0 +1 @@ +simpletest/test_setup.php diff --git a/vendor/sergeytsalkov/meekrodb/COPYING b/vendor/sergeytsalkov/meekrodb/COPYING new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/vendor/sergeytsalkov/meekrodb/COPYING.LESSER b/vendor/sergeytsalkov/meekrodb/COPYING.LESSER new file mode 100644 index 00000000..65c5ca88 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/vendor/sergeytsalkov/meekrodb/README.md b/vendor/sergeytsalkov/meekrodb/README.md new file mode 100644 index 00000000..a564246b --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/README.md @@ -0,0 +1,139 @@ +MeekroDB -- The Simple PHP MySQL Library +======== +Learn more: http://www.meekro.com + +MeekroDB is: + +* A PHP MySQL library that lets you **get more done with fewer lines of code**, and **makes SQL injection 100% impossible**. +* Google's #1 search result for "php mysql library" for over 2 years, with **thousands of deployments worldwide**. +* A library with a **perfect security track record**. No bugs relating to security or SQL injection have ever been discovered. + +Installation +======== +When you're ready to get started, see the [Quick Start Guide](http://www.meekro.com/quickstart.php) on our website. + +### Manual Setup +Include the `db.class.php` file into your project and set it up like this: + + require_once 'db.class.php'; + DB::$user = 'my_database_user'; + DB::$password = 'my_database_password'; + DB::$dbName = 'my_database_name'; + +### Composer +Add this to your `composer.json` + + { + "require": { + "sergeytsalkov/meekrodb": "*" + } + } + +Code Examples +======== +### Grab some rows from the database and print out a field from each row. + + $accounts = DB::query("SELECT * FROM accounts WHERE type = %s AND age > %i", $type, 15); + foreach ($accounts as $account) { + echo $account['username'] . "\n"; + } + +### Insert a new row. + + DB::insert('mytable', array( + 'name' => $name, + 'rank' => $rank, + 'location' => $location, + 'age' => $age, + 'intelligence' => $intelligence + )); + +### Grab one row or field + + $account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe'); + $number_accounts = DB::queryFirstField("SELECT COUNT(*) FROM accounts"); + +### Use a list in a query + DB::query("SELECT * FROM tbl WHERE name IN %ls AND age NOT IN %li", array('John', 'Bob'), array(12, 15)); + +### Nested Transactions + + DB::$nested_transactions = true; + DB::startTransaction(); // outer transaction + // .. some queries.. + $depth = DB::startTransaction(); // inner transaction + echo $depth . 'transactions are currently active'; // 2 + + // .. some queries.. + DB::commit(); // commit inner transaction + // .. some queries.. + DB::commit(); // commit outer transaction + +### Lots More - See: http://www.meekro.com/docs.php + + +How is MeekroDB better than PDO? +======== +### Optional Static Class Mode +Most web apps will only ever talk to one database. This means that +passing $db objects to every function of your code just adds unnecessary clutter. +The simplest approach is to use static methods such as DB::query(), and that's how +MeekroDB works. Still, if you need database objects, MeekroDB can do that too. + +### Do more with fewer lines of code +The code below escapes your parameters for safety, runs the query, and grabs +the first row of results. Try doing that in one line with PDO. + + $account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe'); + +### Work with list parameters easily +Using MySQL's IN keyword should not be hard. MeekroDB smooths out the syntax for you, +PDO does not. + + $accounts = DB::query("SELECT * FROM accounts WHERE username IN %ls", array('Joe', 'Frank')); + + +### Simple inserts +Using MySQL's INSERT should not be more complicated than passing in an +associative array. MeekroDB also simplifies many related commands, including +the useful and bizarre INSERT .. ON DUPLICATE UPDATE command. PDO does none of this. + + DB::insert('accounts', array('username' => 'John', 'password' => 'whatever')); + +### Focus on the goal, not the task +Want to do INSERT yourself rather than relying on DB::insert()? +It's dead simple. I don't even want to think about how many lines +you'd need to pull this off in PDO. + + // Insert 2 rows at once + DB::query("INSERT INTO %b %lb VALUES %?", 'accounts', + array('username', 'password', 'last_login_timestamp'), + array( + array('Joe', 'joes_password', new DateTime('yesterday')), + array('Frank', 'franks_password', new DateTime('last Monday')) + ) + ); + +### Nested transactions +MySQL's SAVEPOINT commands lets you create nested transactions, but only +if you keep track of SAVEPOINT ids yourself. MeekroDB does this for you, +so you can have nested transactions with no complexity or learning curve. + + DB::$nested_transactions = true; + DB::startTransaction(); // outer transaction + // .. some queries.. + $depth = DB::startTransaction(); // inner transaction + echo $depth . 'transactions are currently active'; // 2 + + // .. some queries.. + DB::commit(); // commit inner transaction + // .. some queries.. + DB::commit(); // commit outer transaction + +### Flexible error and success handlers +Set your own custom function run on errors, or on every query that succeeds. +You can easily have separate error handling behavior for the dev and live +versions of your application. Want to count up all your queries and their +runtime? Just add a new success handler. + +### More about MeekroDB's design philosophy: http://www.meekro.com/beliefs.php diff --git a/vendor/sergeytsalkov/meekrodb/composer.json b/vendor/sergeytsalkov/meekrodb/composer.json new file mode 100644 index 00000000..f4940634 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/composer.json @@ -0,0 +1,29 @@ +{ + "name": "SergeyTsalkov/meekrodb", + "description": "The Simple PHP/MySQL Library", + "homepage": "http://www.meekro.com", + "support": { + "email": "support@meekro.com" + }, + "keywords": [ + "mysql", + "database", + "mysqli", + "pdo" + ], + "license": "LGPL-3.0", + "authors": [ + { + "name": "Sergey Tsalkov", + "email": "stsalkov@gmail.com" + } + ], + "require": { + "php": ">=5.2.0" + }, + "autoload": { + "classmap": [ + "db.class.php" + ] + } +} diff --git a/vendor/sergeytsalkov/meekrodb/db.class.php b/vendor/sergeytsalkov/meekrodb/db.class.php new file mode 100644 index 00000000..e63d9669 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/db.class.php @@ -0,0 +1,956 @@ +. +*/ + + +class DB { + // initial connection + public static $dbName = ''; + public static $user = ''; + public static $password = ''; + public static $host = 'localhost'; + public static $port = null; + public static $encoding = 'latin1'; + + // configure workings + public static $param_char = '%'; + public static $named_param_seperator = '_'; + public static $success_handler = false; + public static $error_handler = true; + public static $throw_exception_on_error = false; + public static $nonsql_error_handler = null; + public static $throw_exception_on_nonsql_error = false; + public static $nested_transactions = false; + public static $usenull = true; + public static $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => ''); + public static $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30); + + // internal + protected static $mdb = null; + + public static function getMDB() { + $mdb = DB::$mdb; + + if ($mdb === null) { + $mdb = DB::$mdb = new MeekroDB(); + } + + static $variables_to_sync = array('param_char', 'named_param_seperator', 'success_handler', 'error_handler', 'throw_exception_on_error', + 'nonsql_error_handler', 'throw_exception_on_nonsql_error', 'nested_transactions', 'usenull', 'ssl', 'connect_options'); + + $db_class_vars = get_class_vars('DB'); // the DB::$$var syntax only works in 5.3+ + + foreach ($variables_to_sync as $variable) { + if ($mdb->$variable !== $db_class_vars[$variable]) { + $mdb->$variable = $db_class_vars[$variable]; + } + } + + return $mdb; + } + + // yes, this is ugly. __callStatic() only works in 5.3+ + public static function get() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'get'), $args); } + public static function disconnect() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'disconnect'), $args); } + public static function query() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'query'), $args); } + public static function queryFirstRow() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstRow'), $args); } + public static function queryOneRow() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneRow'), $args); } + public static function queryAllLists() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryAllLists'), $args); } + public static function queryFullColumns() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFullColumns'), $args); } + public static function queryFirstList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstList'), $args); } + public static function queryOneList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneList'), $args); } + public static function queryFirstColumn() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstColumn'), $args); } + public static function queryOneColumn() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneColumn'), $args); } + public static function queryFirstField() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstField'), $args); } + public static function queryOneField() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneField'), $args); } + public static function queryRaw() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryRaw'), $args); } + public static function queryRawUnbuf() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryRawUnbuf'), $args); } + + public static function insert() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insert'), $args); } + public static function insertIgnore() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertIgnore'), $args); } + public static function insertUpdate() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertUpdate'), $args); } + public static function replace() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'replace'), $args); } + public static function update() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'update'), $args); } + public static function delete() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'delete'), $args); } + + public static function insertId() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertId'), $args); } + public static function count() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'count'), $args); } + public static function affectedRows() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'affectedRows'), $args); } + + public static function useDB() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'useDB'), $args); } + public static function startTransaction() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'startTransaction'), $args); } + public static function commit() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'commit'), $args); } + public static function rollback() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'rollback'), $args); } + public static function tableList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'tableList'), $args); } + public static function columnList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'columnList'), $args); } + + public static function sqlEval() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'sqlEval'), $args); } + public static function nonSQLError() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'nonSQLError'), $args); } + + public static function serverVersion() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'serverVersion'), $args); } + public static function transactionDepth() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'transactionDepth'), $args); } + + + public static function debugMode($handler = true) { + DB::$success_handler = $handler; + } + +} + + +class MeekroDB { + // initial connection + public $dbName = ''; + public $user = ''; + public $password = ''; + public $host = 'localhost'; + public $port = null; + public $encoding = 'latin1'; + + // configure workings + public $param_char = '%'; + public $named_param_seperator = '_'; + public $success_handler = false; + public $error_handler = true; + public $throw_exception_on_error = false; + public $nonsql_error_handler = null; + public $throw_exception_on_nonsql_error = false; + public $nested_transactions = false; + public $usenull = true; + public $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => ''); + public $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30); + + // internal + public $internal_mysql = null; + public $server_info = null; + public $insert_id = 0; + public $num_rows = 0; + public $affected_rows = 0; + public $current_db = null; + public $nested_transactions_count = 0; + + + public function __construct($host=null, $user=null, $password=null, $dbName=null, $port=null, $encoding=null) { + if ($host === null) $host = DB::$host; + if ($user === null) $user = DB::$user; + if ($password === null) $password = DB::$password; + if ($dbName === null) $dbName = DB::$dbName; + if ($port === null) $port = DB::$port; + if ($encoding === null) $encoding = DB::$encoding; + + $this->host = $host; + $this->user = $user; + $this->password = $password; + $this->dbName = $dbName; + $this->port = $port; + $this->encoding = $encoding; + } + + public function get() { + $mysql = $this->internal_mysql; + + if (!($mysql instanceof MySQLi)) { + if (! $this->port) $this->port = ini_get('mysqli.default_port'); + $this->current_db = $this->dbName; + $mysql = new mysqli(); + + $connect_flags = 0; + if ($this->ssl['key']) { + $mysql->ssl_set($this->ssl['key'], $this->ssl['cert'], $this->ssl['ca_cert'], $this->ssl['ca_path'], $this->ssl['cipher']); + $connect_flags |= MYSQLI_CLIENT_SSL; + } + foreach ($this->connect_options as $key => $value) { + $mysql->options($key, $value); + } + + // suppress warnings, since we will check connect_error anyway + @$mysql->real_connect($this->host, $this->user, $this->password, $this->dbName, $this->port, null, $connect_flags); + + if ($mysql->connect_error) { + $this->nonSQLError('Unable to connect to MySQL server! Error: ' . $mysql->connect_error); + } + + $mysql->set_charset($this->encoding); + $this->internal_mysql = $mysql; + $this->server_info = $mysql->server_info; + } + + return $mysql; + } + + public function disconnect() { + $mysqli = $this->internal_mysql; + if ($mysqli instanceof MySQLi) { + if ($thread_id = $mysqli->thread_id) $mysqli->kill($thread_id); + $mysqli->close(); + } + $this->internal_mysql = null; + } + + public function nonSQLError($message) { + if ($this->throw_exception_on_nonsql_error) { + $e = new MeekroDBException($message); + throw $e; + } + + $error_handler = is_callable($this->nonsql_error_handler) ? $this->nonsql_error_handler : 'meekrodb_error_handler'; + + call_user_func($error_handler, array( + 'type' => 'nonsql', + 'error' => $message + )); + } + + public function debugMode($handler = true) { + $this->success_handler = $handler; + } + + public function serverVersion() { $this->get(); return $this->server_info; } + public function transactionDepth() { return $this->nested_transactions_count; } + public function insertId() { return $this->insert_id; } + public function affectedRows() { return $this->affected_rows; } + public function count() { $args = func_get_args(); return call_user_func_array(array($this, 'numRows'), $args); } + public function numRows() { return $this->num_rows; } + + public function useDB() { $args = func_get_args(); return call_user_func_array(array($this, 'setDB'), $args); } + public function setDB($dbName) { + $db = $this->get(); + if (! $db->select_db($dbName)) $this->nonSQLError("Unable to set database to $dbName"); + $this->current_db = $dbName; + } + + + public function startTransaction() { + if ($this->nested_transactions && $this->serverVersion() < '5.5') { + return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion()); + } + + if (!$this->nested_transactions || $this->nested_transactions_count == 0) { + $this->query('START TRANSACTION'); + $this->nested_transactions_count = 1; + } else { + $this->query("SAVEPOINT LEVEL{$this->nested_transactions_count}"); + $this->nested_transactions_count++; + } + + return $this->nested_transactions_count; + } + + public function commit($all=false) { + if ($this->nested_transactions && $this->serverVersion() < '5.5') { + return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion()); + } + + if ($this->nested_transactions && $this->nested_transactions_count > 0) + $this->nested_transactions_count--; + + if (!$this->nested_transactions || $all || $this->nested_transactions_count == 0) { + $this->nested_transactions_count = 0; + $this->query('COMMIT'); + } else { + $this->query("RELEASE SAVEPOINT LEVEL{$this->nested_transactions_count}"); + } + + return $this->nested_transactions_count; + } + + public function rollback($all=false) { + if ($this->nested_transactions && $this->serverVersion() < '5.5') { + return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion()); + } + + if ($this->nested_transactions && $this->nested_transactions_count > 0) + $this->nested_transactions_count--; + + if (!$this->nested_transactions || $all || $this->nested_transactions_count == 0) { + $this->nested_transactions_count = 0; + $this->query('ROLLBACK'); + } else { + $this->query("ROLLBACK TO SAVEPOINT LEVEL{$this->nested_transactions_count}"); + } + + return $this->nested_transactions_count; + } + + protected function formatTableName($table) { + $table = trim($table, '`'); + + if (strpos($table, '.')) return implode('.', array_map(array($this, 'formatTableName'), explode('.', $table))); + else return '`' . str_replace('`', '``', $table) . '`'; + } + + public function update() { + $args = func_get_args(); + $table = array_shift($args); + $params = array_shift($args); + $where = array_shift($args); + + $query = str_replace('%', $this->param_char, "UPDATE %b SET %? WHERE ") . $where; + + array_unshift($args, $params); + array_unshift($args, $table); + array_unshift($args, $query); + return call_user_func_array(array($this, 'query'), $args); + } + + public function insertOrReplace($which, $table, $datas, $options=array()) { + $datas = unserialize(serialize($datas)); // break references within array + $keys = $values = array(); + + if (isset($datas[0]) && is_array($datas[0])) { + foreach ($datas as $datum) { + ksort($datum); + if (! $keys) $keys = array_keys($datum); + $values[] = array_values($datum); + } + + } else { + $keys = array_keys($datas); + $values = array_values($datas); + } + + if (isset($options['ignore']) && $options['ignore']) $which = 'INSERT IGNORE'; + + if (isset($options['update']) && is_array($options['update']) && $options['update'] && strtolower($which) == 'insert') { + if (array_values($options['update']) !== $options['update']) { + return $this->query( + str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE %?"), + $table, $keys, $values, $options['update']); + } else { + $update_str = array_shift($options['update']); + $query_param = array( + str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE ") . $update_str, + $table, $keys, $values); + $query_param = array_merge($query_param, $options['update']); + return call_user_func_array(array($this, 'query'), $query_param); + } + + } + + return $this->query( + str_replace('%', $this->param_char, "%l INTO %b %lb VALUES %?"), + $which, $table, $keys, $values); + } + + public function insert($table, $data) { return $this->insertOrReplace('INSERT', $table, $data); } + public function insertIgnore($table, $data) { return $this->insertOrReplace('INSERT', $table, $data, array('ignore' => true)); } + public function replace($table, $data) { return $this->insertOrReplace('REPLACE', $table, $data); } + + public function insertUpdate() { + $args = func_get_args(); + $table = array_shift($args); + $data = array_shift($args); + + if (! isset($args[0])) { // update will have all the data of the insert + if (isset($data[0]) && is_array($data[0])) { //multiple insert rows specified -- failing! + $this->nonSQLError("Badly formatted insertUpdate() query -- you didn't specify the update component!"); + } + + $args[0] = $data; + } + + if (is_array($args[0])) $update = $args[0]; + else $update = $args; + + return $this->insertOrReplace('INSERT', $table, $data, array('update' => $update)); + } + + public function delete() { + $args = func_get_args(); + $table = $this->formatTableName(array_shift($args)); + $where = array_shift($args); + $buildquery = "DELETE FROM $table WHERE $where"; + array_unshift($args, $buildquery); + return call_user_func_array(array($this, 'query'), $args); + } + + public function sqleval() { + $args = func_get_args(); + $text = call_user_func_array(array($this, 'parseQueryParams'), $args); + return new MeekroDBEval($text); + } + + public function columnList($table) { + return $this->queryOneColumn('Field', "SHOW COLUMNS FROM %b", $table); + } + + public function tableList($db = null) { + if ($db) { + $olddb = $this->current_db; + $this->useDB($db); + } + + $result = $this->queryFirstColumn('SHOW TABLES'); + if (isset($olddb)) $this->useDB($olddb); + return $result; + } + + protected function preparseQueryParams() { + $args = func_get_args(); + $sql = trim(strval(array_shift($args))); + $args_all = $args; + + if (count($args_all) == 0) return array($sql); + + $param_char_length = strlen($this->param_char); + $named_seperator_length = strlen($this->named_param_seperator); + + $types = array( + $this->param_char . 'll', // list of literals + $this->param_char . 'ls', // list of strings + $this->param_char . 'l', // literal + $this->param_char . 'li', // list of integers + $this->param_char . 'ld', // list of decimals + $this->param_char . 'lb', // list of backticks + $this->param_char . 'lt', // list of timestamps + $this->param_char . 's', // string + $this->param_char . 'i', // integer + $this->param_char . 'd', // double / decimal + $this->param_char . 'b', // backtick + $this->param_char . 't', // timestamp + $this->param_char . '?', // infer type + $this->param_char . 'ss' // search string (like string, surrounded with %'s) + ); + + // generate list of all MeekroDB variables in our query, and their position + // in the form "offset => variable", sorted by offsets + $posList = array(); + foreach ($types as $type) { + $lastPos = 0; + while (($pos = strpos($sql, $type, $lastPos)) !== false) { + $lastPos = $pos + 1; + if (isset($posList[$pos]) && strlen($posList[$pos]) > strlen($type)) continue; + $posList[$pos] = $type; + } + } + + ksort($posList); + + // for each MeekroDB variable, substitute it with array(type: i, value: 53) or whatever + $chunkyQuery = array(); // preparsed query + $pos_adj = 0; // how much we've added or removed from the original sql string + foreach ($posList as $pos => $type) { + $type = substr($type, $param_char_length); // variable, without % in front of it + $length_type = strlen($type) + $param_char_length; // length of variable w/o % + + $new_pos = $pos + $pos_adj; // position of start of variable + $new_pos_back = $new_pos + $length_type; // position of end of variable + $arg_number_length = 0; // length of any named or numbered parameter addition + + // handle numbered parameters + if ($arg_number_length = strspn($sql, '0123456789', $new_pos_back)) { + $arg_number = substr($sql, $new_pos_back, $arg_number_length); + if (! array_key_exists($arg_number, $args_all)) $this->nonSQLError("Non existent argument reference (arg $arg_number): $sql"); + + $arg = $args_all[$arg_number]; + + // handle named parameters + } else if (substr($sql, $new_pos_back, $named_seperator_length) == $this->named_param_seperator) { + $arg_number_length = strspn($sql, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_', + $new_pos_back + $named_seperator_length) + $named_seperator_length; + + $arg_number = substr($sql, $new_pos_back + $named_seperator_length, $arg_number_length - $named_seperator_length); + if (count($args_all) != 1 || !is_array($args_all[0])) $this->nonSQLError("If you use named parameters, the second argument must be an array of parameters"); + if (! array_key_exists($arg_number, $args_all[0])) $this->nonSQLError("Non existent argument reference (arg $arg_number): $sql"); + + $arg = $args_all[0][$arg_number]; + + } else { + $arg_number = 0; + $arg = array_shift($args); + } + + if ($new_pos > 0) $chunkyQuery[] = substr($sql, 0, $new_pos); + + if (is_object($arg) && ($arg instanceof WhereClause)) { + list($clause_sql, $clause_args) = $arg->textAndArgs(); + array_unshift($clause_args, $clause_sql); + $preparsed_sql = call_user_func_array(array($this, 'preparseQueryParams'), $clause_args); + $chunkyQuery = array_merge($chunkyQuery, $preparsed_sql); + } else { + $chunkyQuery[] = array('type' => $type, 'value' => $arg); + } + + $sql = substr($sql, $new_pos_back + $arg_number_length); + $pos_adj -= $new_pos_back + $arg_number_length; + } + + if (strlen($sql) > 0) $chunkyQuery[] = $sql; + + return $chunkyQuery; + } + + protected function escape($str) { return "'" . $this->get()->real_escape_string(strval($str)) . "'"; } + + protected function sanitize($value) { + if (is_object($value)) { + if ($value instanceof MeekroDBEval) return $value->text; + else if ($value instanceof DateTime) return $this->escape($value->format('Y-m-d H:i:s')); + else return ''; + } + + if (is_null($value)) return $this->usenull ? 'NULL' : "''"; + else if (is_bool($value)) return ($value ? 1 : 0); + else if (is_int($value)) return $value; + else if (is_float($value)) return $value; + + else if (is_array($value)) { + // non-assoc array? + if (array_values($value) === $value) { + if (is_array($value[0])) return implode(', ', array_map(array($this, 'sanitize'), $value)); + else return '(' . implode(', ', array_map(array($this, 'sanitize'), $value)) . ')'; + } + + $pairs = array(); + foreach ($value as $k => $v) { + $pairs[] = $this->formatTableName($k) . '=' . $this->sanitize($v); + } + + return implode(', ', $pairs); + } + else return $this->escape($value); + } + + protected function parseTS($ts) { + if (is_string($ts)) return date('Y-m-d H:i:s', strtotime($ts)); + else if (is_object($ts) && ($ts instanceof DateTime)) return $ts->format('Y-m-d H:i:s'); + } + + protected function intval($var) { + if (PHP_INT_SIZE == 8) return intval($var); + return floor(doubleval($var)); + } + + protected function parseQueryParams() { + $args = func_get_args(); + $chunkyQuery = call_user_func_array(array($this, 'preparseQueryParams'), $args); + + $query = ''; + $array_types = array('ls', 'li', 'ld', 'lb', 'll', 'lt'); + + foreach ($chunkyQuery as $chunk) { + if (is_string($chunk)) { + $query .= $chunk; + continue; + } + + $type = $chunk['type']; + $arg = $chunk['value']; + $result = ''; + + if ($type != '?') { + $is_array_type = in_array($type, $array_types, true); + if ($is_array_type && !is_array($arg)) $this->nonSQLError("Badly formatted SQL query: Expected array, got scalar instead!"); + else if (!$is_array_type && is_array($arg)) $this->nonSQLError("Badly formatted SQL query: Expected scalar, got array instead!"); + } + + if ($type == 's') $result = $this->escape($arg); + else if ($type == 'i') $result = $this->intval($arg); + else if ($type == 'd') $result = doubleval($arg); + else if ($type == 'b') $result = $this->formatTableName($arg); + else if ($type == 'l') $result = $arg; + else if ($type == 'ss') $result = $this->escape("%" . str_replace(array('%', '_'), array('\%', '\_'), $arg) . "%"); + else if ($type == 't') $result = $this->escape($this->parseTS($arg)); + + else if ($type == 'ls') $result = array_map(array($this, 'escape'), $arg); + else if ($type == 'li') $result = array_map(array($this, 'intval'), $arg); + else if ($type == 'ld') $result = array_map('doubleval', $arg); + else if ($type == 'lb') $result = array_map(array($this, 'formatTableName'), $arg); + else if ($type == 'll') $result = $arg; + else if ($type == 'lt') $result = array_map(array($this, 'escape'), array_map(array($this, 'parseTS'), $arg)); + + else if ($type == '?') $result = $this->sanitize($arg); + + else $this->nonSQLError("Badly formatted SQL query: Invalid MeekroDB param $type"); + + if (is_array($result)) $result = '(' . implode(',', $result) . ')'; + + $query .= $result; + } + + return $query; + } + + protected function prependCall($function, $args, $prepend) { array_unshift($args, $prepend); return call_user_func_array($function, $args); } + public function query() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'assoc'); } + public function queryAllLists() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'list'); } + public function queryFullColumns() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'full'); } + + public function queryRaw() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'raw_buf'); } + public function queryRawUnbuf() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'raw_unbuf'); } + + protected function queryHelper() { + $args = func_get_args(); + $type = array_shift($args); + $db = $this->get(); + + $is_buffered = true; + $row_type = 'assoc'; // assoc, list, raw + $full_names = false; + + switch ($type) { + case 'assoc': + break; + case 'list': + $row_type = 'list'; + break; + case 'full': + $row_type = 'list'; + $full_names = true; + break; + case 'raw_buf': + $row_type = 'raw'; + break; + case 'raw_unbuf': + $is_buffered = false; + $row_type = 'raw'; + break; + default: + $this->nonSQLError('Error -- invalid argument to queryHelper!'); + } + + $sql = call_user_func_array(array($this, 'parseQueryParams'), $args); + + if ($this->success_handler) $starttime = microtime(true); + $result = $db->query($sql, $is_buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); + if ($this->success_handler) $runtime = microtime(true) - $starttime; + else $runtime = 0; + + // ----- BEGIN ERROR HANDLING + if (!$sql || $db->error) { + if ($this->error_handler) { + $error_handler = is_callable($this->error_handler) ? $this->error_handler : 'meekrodb_error_handler'; + + call_user_func($error_handler, array( + 'type' => 'sql', + 'query' => $sql, + 'error' => $db->error, + 'code' => $db->errno + )); + } + + if ($this->throw_exception_on_error) { + $e = new MeekroDBException($db->error, $sql, $db->errno); + throw $e; + } + } else if ($this->success_handler) { + $runtime = sprintf('%f', $runtime * 1000); + $success_handler = is_callable($this->success_handler) ? $this->success_handler : 'meekrodb_debugmode_handler'; + + call_user_func($success_handler, array( + 'query' => $sql, + 'runtime' => $runtime, + 'affected' => $db->affected_rows + )); + } + + // ----- END ERROR HANDLING + + $this->insert_id = $db->insert_id; + $this->affected_rows = $db->affected_rows; + + // mysqli_result->num_rows won't initially show correct results for unbuffered data + if ($is_buffered && ($result instanceof MySQLi_Result)) $this->num_rows = $result->num_rows; + else $this->num_rows = null; + + if ($row_type == 'raw' || !($result instanceof MySQLi_Result)) return $result; + + $return = array(); + + if ($full_names) { + $infos = array(); + foreach ($result->fetch_fields() as $info) { + if (strlen($info->table)) $infos[] = $info->table . '.' . $info->name; + else $infos[] = $info->name; + } + } + + while ($row = ($row_type == 'assoc' ? $result->fetch_assoc() : $result->fetch_row())) { + if ($full_names) $row = array_combine($infos, $row); + $return[] = $row; + } + + // free results + $result->free(); + while ($db->more_results()) { + $db->next_result(); + if ($result = $db->use_result()) $result->free(); + } + + return $return; + } + + public function queryOneRow() { $args = func_get_args(); return call_user_func_array(array($this, 'queryFirstRow'), $args); } + public function queryFirstRow() { + $args = func_get_args(); + $result = call_user_func_array(array($this, 'query'), $args); + if (!$result || !is_array($result)) return null; + return reset($result); + } + + public function queryOneList() { $args = func_get_args(); return call_user_func_array(array($this, 'queryFirstList'), $args); } + public function queryFirstList() { + $args = func_get_args(); + $result = call_user_func_array(array($this, 'queryAllLists'), $args); + if (!$result || !is_array($result)) return null; + return reset($result); + } + + public function queryFirstColumn() { + $args = func_get_args(); + $results = call_user_func_array(array($this, 'queryAllLists'), $args); + $ret = array(); + + if (!count($results) || !count($results[0])) return $ret; + + foreach ($results as $row) { + $ret[] = $row[0]; + } + + return $ret; + } + + public function queryOneColumn() { + $args = func_get_args(); + $column = array_shift($args); + $results = call_user_func_array(array($this, 'query'), $args); + $ret = array(); + + if (!count($results) || !count($results[0])) return $ret; + if ($column === null) { + $keys = array_keys($results[0]); + $column = $keys[0]; + } + + foreach ($results as $row) { + $ret[] = $row[$column]; + } + + return $ret; + } + + public function queryFirstField() { + $args = func_get_args(); + $row = call_user_func_array(array($this, 'queryFirstList'), $args); + if ($row == null) return null; + return $row[0]; + } + + public function queryOneField() { + $args = func_get_args(); + $column = array_shift($args); + + $row = call_user_func_array(array($this, 'queryOneRow'), $args); + if ($row == null) { + return null; + } else if ($column === null) { + $keys = array_keys($row); + $column = $keys[0]; + } + + return $row[$column]; + } +} + +class WhereClause { + public $type = 'and'; //AND or OR + public $negate = false; + public $clauses = array(); + + function __construct($type) { + $type = strtolower($type); + if ($type !== 'or' && $type !== 'and') DB::nonSQLError('you must use either WhereClause(and) or WhereClause(or)'); + $this->type = $type; + } + + function add() { + $args = func_get_args(); + $sql = array_shift($args); + + if ($sql instanceof WhereClause) { + $this->clauses[] = $sql; + } else { + $this->clauses[] = array('sql' => $sql, 'args' => $args); + } + } + + function negateLast() { + $i = count($this->clauses) - 1; + if (!isset($this->clauses[$i])) return; + + if ($this->clauses[$i] instanceof WhereClause) { + $this->clauses[$i]->negate(); + } else { + $this->clauses[$i]['sql'] = 'NOT (' . $this->clauses[$i]['sql'] . ')'; + } + } + + function negate() { + $this->negate = ! $this->negate; + } + + function addClause($type) { + $r = new WhereClause($type); + $this->add($r); + return $r; + } + + function count() { + return count($this->clauses); + } + + function textAndArgs() { + $sql = array(); + $args = array(); + + if (count($this->clauses) == 0) return array('(1)', $args); + + foreach ($this->clauses as $clause) { + if ($clause instanceof WhereClause) { + list($clause_sql, $clause_args) = $clause->textAndArgs(); + } else { + $clause_sql = $clause['sql']; + $clause_args = $clause['args']; + } + + $sql[] = "($clause_sql)"; + $args = array_merge($args, $clause_args); + } + + if ($this->type == 'and') $sql = implode(' AND ', $sql); + else $sql = implode(' OR ', $sql); + + if ($this->negate) $sql = '(NOT ' . $sql . ')'; + return array($sql, $args); + } + + // backwards compatability + // we now return full WhereClause object here and evaluate it in preparseQueryParams + function text() { return $this; } +} + +class DBTransaction { + private $committed = false; + + function __construct() { + DB::startTransaction(); + } + function __destruct() { + if (! $this->committed) DB::rollback(); + } + function commit() { + DB::commit(); + $this->committed = true; + } + + +} + +class MeekroDBException extends Exception { + protected $query = ''; + + function __construct($message='', $query='', $code = 0) { + parent::__construct($message); + $this->query = $query; + $this->code = $code; + } + + public function getQuery() { return $this->query; } +} + +class DBHelper { + /* + verticalSlice + 1. For an array of assoc rays, return an array of values for a particular key + 2. if $keyfield is given, same as above but use that hash key as the key in new array + */ + + public static function verticalSlice($array, $field, $keyfield = null) { + $array = (array) $array; + + $R = array(); + foreach ($array as $obj) { + if (! array_key_exists($field, $obj)) die("verticalSlice: array doesn't have requested field\n"); + + if ($keyfield) { + if (! array_key_exists($keyfield, $obj)) die("verticalSlice: array doesn't have requested field\n"); + $R[$obj[$keyfield]] = $obj[$field]; + } else { + $R[] = $obj[$field]; + } + } + return $R; + } + + /* + reIndex + For an array of assoc rays, return a new array of assoc rays using a certain field for keys + */ + + public static function reIndex() { + $fields = func_get_args(); + $array = array_shift($fields); + $array = (array) $array; + + $R = array(); + foreach ($array as $obj) { + $target =& $R; + + foreach ($fields as $field) { + if (! array_key_exists($field, $obj)) die("reIndex: array doesn't have requested field\n"); + + $nextkey = $obj[$field]; + $target =& $target[$nextkey]; + } + $target = $obj; + } + return $R; + } +} + +function meekrodb_error_handler($params) { + if (isset($params['query'])) $out[] = "QUERY: " . $params['query']; + if (isset($params['error'])) $out[] = "ERROR: " . $params['error']; + $out[] = ""; + + if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) { + echo implode("\n", $out); + } else { + echo implode("
\n", $out); + } + + die; +} + +function meekrodb_debugmode_handler($params) { + echo "QUERY: " . $params['query'] . " [" . $params['runtime'] . " ms]"; + if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) { + echo "\n"; + } else { + echo "
\n"; + } +} + +class MeekroDBEval { + public $text = ''; + + function __construct($text) { + $this->text = $text; + } +} + +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/BasicTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/BasicTest.php new file mode 100644 index 00000000..f924c90a --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/BasicTest.php @@ -0,0 +1,420 @@ +assert($mysqli->server_info === null); + } + + function test_1_5_empty_table() { + $counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts"); + $this->assert($counter === strval(0)); + + $row = DB::queryFirstRow("SELECT * FROM accounts"); + $this->assert($row === null); + + $field = DB::queryFirstField("SELECT * FROM accounts"); + $this->assert($field === null); + + $field = DB::queryOneField('nothere', "SELECT * FROM accounts"); + $this->assert($field === null); + + $column = DB::queryFirstColumn("SELECT * FROM accounts"); + $this->assert(is_array($column) && count($column) === 0); + + $column = DB::queryOneColumn('nothere', "SELECT * FROM accounts"); //TODO: is this what we want? + $this->assert(is_array($column) && count($column) === 0); + } + + function test_2_insert_row() { + $true = DB::insert('accounts', array( + 'username' => 'Abe', + 'password' => 'hello' + )); + + $this->assert($true === true); + $this->assert(DB::affectedRows() === 1); + + $counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts"); + $this->assert($counter === strval(1)); + } + + function test_3_more_inserts() { + DB::insert('`accounts`', array( + 'username' => 'Bart', + 'password' => 'hello', + 'age' => 15, + 'height' => 10.371 + )); + $dbname = DB::$dbName; + DB::insert("`$dbname`.`accounts`", array( + 'username' => 'Charlie\'s Friend', + 'password' => 'goodbye', + 'age' => 30, + 'height' => 155.23, + 'favorite_word' => null, + )); + + $this->assert(DB::insertId() === 3); + $counter = DB::queryFirstField("SELECT COUNT(*) FROM accounts"); + $this->assert($counter === strval(3)); + + DB::insert('`accounts`', array( + 'username' => 'Deer', + 'password' => '', + 'age' => 15, + 'height' => 10.371 + )); + + $username = DB::queryFirstField("SELECT username FROM accounts WHERE password=%s0", null); + $this->assert($username === 'Deer'); + + $password = DB::queryFirstField("SELECT password FROM accounts WHERE favorite_word IS NULL"); + $this->assert($password === 'goodbye'); + + DB::$usenull = false; + DB::insertUpdate('accounts', array( + 'id' => 3, + 'favorite_word' => null, + )); + + $password = DB::queryFirstField("SELECT password FROM accounts WHERE favorite_word=%s AND favorite_word=%s", null, ''); + $this->assert($password === 'goodbye'); + + DB::$usenull = true; + DB::insertUpdate('accounts', array( + 'id' => 3, + 'favorite_word' => null, + )); + + DB::$param_char = '###'; + $bart = DB::queryFirstRow("SELECT * FROM accounts WHERE age IN ###li AND height IN ###ld AND username IN ###ls", + array(15, 25), array(10.371, 150.123), array('Bart', 'Barts')); + $this->assert($bart['username'] === 'Bart'); + DB::insert('accounts', array('username' => 'f_u')); + DB::query("DELETE FROM accounts WHERE username=###s", 'f_u'); + DB::$param_char = '%'; + + $charlie_password = DB::queryFirstField("SELECT password FROM accounts WHERE username IN %ls AND username = %s", + array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend'); + $this->assert($charlie_password === 'goodbye'); + + $charlie_password = DB::queryOneField('password', "SELECT * FROM accounts WHERE username IN %ls AND username = %s", + array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend'); + $this->assert($charlie_password === 'goodbye'); + + $passwords = DB::queryFirstColumn("SELECT password FROM accounts WHERE username=%s", 'Bart'); + $this->assert(count($passwords) === 1); + $this->assert($passwords[0] === 'hello'); + + $username = $password = $age = null; + list($age, $username, $password) = DB::queryOneList("SELECT age,username,password FROM accounts WHERE username=%s", 'Bart'); + $this->assert($username === 'Bart'); + $this->assert($password === 'hello'); + $this->assert($age == 15); + + $mysqli_result = DB::queryRaw("SELECT * FROM accounts WHERE favorite_word IS NULL"); + $this->assert($mysqli_result instanceof MySQLi_Result); + $row = $mysqli_result->fetch_assoc(); + $this->assert($row['password'] === 'goodbye'); + $this->assert($mysqli_result->fetch_assoc() === null); + } + + function test_4_query() { + DB::update('accounts', array( + 'birthday' => new DateTime('10 September 2000 13:13:13') + ), 'username=%s', 'Charlie\'s Friend'); + + $results = DB::query("SELECT * FROM accounts WHERE username=%s AND birthday IN %lt", 'Charlie\'s Friend', array('September 10 2000 13:13:13')); + $this->assert(count($results) === 1); + $this->assert($results[0]['age'] === '30' && $results[0]['password'] === 'goodbye'); + $this->assert($results[0]['birthday'] == '2000-09-10 13:13:13'); + + $results = DB::query("SELECT * FROM accounts WHERE username!=%s", "Charlie's Friend"); + $this->assert(count($results) === 3); + + $columnlist = DB::columnList('accounts'); + $this->assert(count($columnlist) === 8); + $this->assert($columnlist[0] === 'id'); + $this->assert($columnlist[5] === 'height'); + + $tablelist = DB::tableList(); + $this->assert(count($tablelist) === 2); + $this->assert($tablelist[0] === 'accounts'); + + $tablelist = null; + $tablelist = DB::tableList(DB::$dbName); + $this->assert(count($tablelist) === 2); + $this->assert($tablelist[0] === 'accounts'); + } + + function test_4_1_query() { + DB::insert('accounts', array( + 'username' => 'newguy', + 'password' => DB::sqleval("REPEAT('blah', %i)", '3'), + 'age' => DB::sqleval('171+1'), + 'height' => 111.15 + )); + + $row = DB::queryOneRow("SELECT * FROM accounts WHERE password=%s", 'blahblahblah'); + $this->assert($row['username'] === 'newguy'); + $this->assert($row['age'] === '172'); + + $true = DB::update('accounts', array( + 'password' => DB::sqleval("REPEAT('blah', %i)", 4), + 'favorite_word' => null, + ), 'username=%s', 'newguy'); + + $row = null; + $row = DB::queryOneRow("SELECT * FROM accounts WHERE username=%s", 'newguy'); + $this->assert($true === true); + $this->assert($row['password'] === 'blahblahblahblah'); + $this->assert($row['favorite_word'] === null); + + $row = DB::query("SELECT * FROM accounts WHERE password=%s_mypass AND (password=%s_mypass) AND username=%s_myuser", + array('myuser' => 'newguy', 'mypass' => 'blahblahblahblah') + ); + $this->assert(count($row) === 1); + $this->assert($row[0]['username'] === 'newguy'); + $this->assert($row[0]['age'] === '172'); + + $true = DB::query("DELETE FROM accounts WHERE password=%s", 'blahblahblahblah'); + $this->assert($true === true); + $this->assert(DB::affectedRows() === 1); + } + + function test_4_2_delete() { + DB::insert('accounts', array( + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + )); + + $ct = DB::queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', 199.194); + $this->assert(intval($ct) === 1); + + $ct = DB::queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s1 AND height=%d0 AND height=%d", 199.194, 'gonesoon'); + $this->assert(intval($ct) === 1); + + DB::delete('accounts', 'username=%s AND age=%i AND height=%d', 'gonesoon', '61', '199.194'); + $this->assert(DB::affectedRows() === 1); + + $ct = DB::queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', '199.194'); + $this->assert(intval($ct) === 0); + } + + function test_4_3_insertmany() { + $ins[] = array( + 'username' => '1ofmany', + 'password' => 'something', + 'age' => 23, + 'height' => 190.194 + ); + $ins[] = array( + 'password' => 'somethingelse', + 'username' => '2ofmany', + 'age' => 25, + 'height' => 190.194 + ); + $ins[] = array( + 'password' => NULL, + 'username' => '3ofmany', + 'age' => 15, + 'height' => 111.951 + ); + + DB::insert('accounts', $ins); + $this->assert(DB::affectedRows() === 3); + + $rows = DB::query("SELECT * FROM accounts WHERE height=%d ORDER BY age ASC", 190.194); + $this->assert(count($rows) === 2); + $this->assert($rows[0]['username'] === '1ofmany'); + $this->assert($rows[0]['age'] === '23'); + $this->assert($rows[1]['age'] === '25'); + $this->assert($rows[1]['password'] === 'somethingelse'); + $this->assert($rows[1]['username'] === '2ofmany'); + + $nullrow = DB::queryOneRow("SELECT * FROM accounts WHERE username LIKE %ss", '3ofman'); + $this->assert($nullrow['password'] === NULL); + $this->assert($nullrow['age'] === '15'); + } + + + + function test_5_insert_blobs() { + DB::query("CREATE TABLE `store data` ( + `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , + `picture` BLOB + ) ENGINE = InnoDB"); + + $columns = DB::columnList('store data'); + $this->assert(count($columns) === 2); + $this->assert($columns[1] === 'picture'); + + + $smile = file_get_contents('smile1.jpg'); + DB::insert('store data', array( + 'picture' => $smile, + )); + DB::queryOneRow("INSERT INTO %b (picture) VALUES (%s)", 'store data', $smile); + + $getsmile = DB::queryFirstField("SELECT picture FROM %b WHERE id=1", 'store data'); + $getsmile2 = DB::queryFirstField("SELECT picture FROM %b WHERE id=2", 'store data'); + $this->assert($smile === $getsmile); + $this->assert($smile === $getsmile2); + } + + function test_6_insert_ignore() { + DB::insertIgnore('accounts', array( + 'id' => 1, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + )); + } + + function test_7_insert_update() { + $true = DB::insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ), 'age = age + %i', 1); + + $this->assert($true === true); + $this->assert(DB::affectedRows() === 2); // a quirk of MySQL, even though only 1 row was updated + + $result = DB::query("SELECT * FROM accounts WHERE age = %i", 16); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '10.371'); + + DB::insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'blahblahdude', + 'age' => 233, + 'height' => 199.194 + )); + + $result = DB::query("SELECT * FROM accounts WHERE age = %i", 233); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '199.194'); + $this->assert($result[0]['username'] === 'blahblahdude'); + + DB::insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ), array( + 'age' => 74, + )); + + $result = DB::query("SELECT * FROM accounts WHERE age = %i", 74); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '199.194'); + $this->assert($result[0]['username'] === 'blahblahdude'); + + $multiples[] = array( + 'id' => 3, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ); + $multiples[] = array( + 'id' => 1, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ); + + DB::insertUpdate('accounts', $multiples, array('age' => 914)); + $this->assert(DB::affectedRows() === 4); + + $result = DB::query("SELECT * FROM accounts WHERE age=914 ORDER BY id ASC"); + $this->assert(count($result) === 2); + $this->assert($result[0]['username'] === 'Abe'); + $this->assert($result[1]['username'] === 'Charlie\'s Friend'); + + $true = DB::query("UPDATE accounts SET age=15, username='Bart' WHERE age=%i", 74); + $this->assert($true === true); + $this->assert(DB::affectedRows() === 1); + } + + function test_8_lb() { + $data = array( + 'username' => 'vookoo', + 'password' => 'dookoo', + ); + + $true = DB::query("INSERT into accounts %lb VALUES %ls", array_keys($data), array_values($data)); + $result = DB::query("SELECT * FROM accounts WHERE username=%s", 'vookoo'); + $this->assert($true === true); + $this->assert(count($result) === 1); + $this->assert($result[0]['password'] === 'dookoo'); + } + + function test_9_fullcolumns() { + $true = DB::insert('profile', array( + 'id' => 1, + 'signature' => 'u_suck' + )); + DB::query("UPDATE accounts SET profile_id=1 WHERE id=2"); + + $r = DB::queryFullColumns("SELECT accounts.*, profile.*, 1+1 FROM accounts + INNER JOIN profile ON accounts.profile_id=profile.id"); + + $this->assert($true === true); + $this->assert(count($r) === 1); + $this->assert($r[0]['accounts.id'] === '2'); + $this->assert($r[0]['profile.id'] === '1'); + $this->assert($r[0]['profile.signature'] === 'u_suck'); + $this->assert($r[0]['1+1'] === '2'); + } + + function test_901_updatewithspecialchar() { + $data = 'www.mysite.com/product?s=t-%s-%%3d%%3d%i&RCAID=24322'; + DB::update('profile', array('signature' => $data), 'id=%i', 1); + $signature = DB::queryFirstField("SELECT signature FROM profile WHERE id=%i", 1); + $this->assert($signature === $data); + + DB::update('profile',array('signature'=> "%li "),"id = %d",1); + $signature = DB::queryFirstField("SELECT signature FROM profile WHERE id=%i", 1); + $this->assert($signature === "%li "); + + } + + + +} + + +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/CallTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/CallTest.php new file mode 100644 index 00000000..cd82e6fa --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/CallTest.php @@ -0,0 +1,17 @@ +assert($r[0]['username'] === 'Abe'); + $this->assert($r[2]['age'] === '914'); + } + +} \ No newline at end of file diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/ErrorTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/ErrorTest.php new file mode 100644 index 00000000..b2309808 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/ErrorTest.php @@ -0,0 +1,83 @@ +assert($error_callback_worked === 1); + + DB::$error_handler = array('ErrorTest', 'static_error_callback'); + DB::query("SELET * FROM accounts"); + $this->assert($static_error_callback_worked === 1); + + DB::$error_handler = array($this, 'nonstatic_error_callback'); + DB::query("SELET * FROM accounts"); + $this->assert($nonstatic_error_callback_worked === 1); + + } + + public static function static_error_callback($params) { + global $static_error_callback_worked; + if (substr_count($params['error'], 'You have an error in your SQL syntax')) $static_error_callback_worked = 1; + } + + public function nonstatic_error_callback($params) { + global $nonstatic_error_callback_worked; + if (substr_count($params['error'], 'You have an error in your SQL syntax')) $nonstatic_error_callback_worked = 1; + } + + function test_2_exception_catch() { + $dbname = DB::$dbName; + DB::$error_handler = ''; + DB::$throw_exception_on_error = true; + try { + DB::query("SELET * FROM accounts"); + } catch(MeekroDBException $e) { + $this->assert(substr_count($e->getMessage(), 'You have an error in your SQL syntax')); + $this->assert($e->getQuery() === 'SELET * FROM accounts'); + $exception_was_caught = 1; + } + $this->assert($exception_was_caught === 1); + + try { + DB::insert("`$dbname`.`accounts`", array( + 'id' => 2, + 'username' => 'Another Dude\'s \'Mom"', + 'password' => 'asdfsdse', + 'age' => 35, + 'height' => 555.23 + )); + } catch(MeekroDBException $e) { + $this->assert(substr_count($e->getMessage(), 'Duplicate entry')); + $exception_was_caught = 2; + } + $this->assert($exception_was_caught === 2); + } + + function test_3_debugmode_handler() { + global $debug_callback_worked; + + DB::debugMode('my_debug_handler'); + DB::query("SELECT * FROM accounts WHERE username!=%s", "Charlie's Friend"); + + $this->assert($debug_callback_worked === 1); + + DB::debugMode(false); + } + +} + +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/ErrorTest_53.php b/vendor/sergeytsalkov/meekrodb/simpletest/ErrorTest_53.php new file mode 100644 index 00000000..8aafe093 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/ErrorTest_53.php @@ -0,0 +1,19 @@ +assert($anonymous_error_callback_worked === 1); + + } + + +} + +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/HelperTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/HelperTest.php new file mode 100644 index 00000000..496c4062 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/HelperTest.php @@ -0,0 +1,51 @@ +assert(count($names) === 5); + $this->assert($names[0] === 'Abe'); + + $ages = DBHelper::verticalSlice($all, 'age', 'username'); + $this->assert(count($ages) === 5); + $this->assert($ages['Abe'] === '700'); + } + + function test_2_reindex() { + $all = DB::query("SELECT * FROM accounts ORDER BY id ASC"); + $names = DBHelper::reIndex($all, 'username'); + $this->assert(count($names) === 5); + $this->assert($names['Bart']['username'] === 'Bart'); + $this->assert($names['Bart']['age'] === '15'); + + $names = DBHelper::reIndex($all, 'username', 'age'); + $this->assert($names['Bart']['15']['username'] === 'Bart'); + $this->assert($names['Bart']['15']['age'] === '15'); + } + + function test_3_empty() { + $none = DB::query("SELECT * FROM accounts WHERE username=%s", 'doesnotexist'); + $this->assert(is_array($none) && count($none) === 0); + $names = DBHelper::verticalSlice($none, 'username', 'age'); + $this->assert(is_array($names) && count($names) === 0); + + $names_other = DBHelper::reIndex($none, 'username', 'age'); + $this->assert(is_array($names_other) && count($names_other) === 0); + } + + function test_4_null() { + DB::query("UPDATE accounts SET password = NULL WHERE username=%s", 'Bart'); + + $all = DB::query("SELECT * FROM accounts ORDER BY id ASC"); + $ages = DBHelper::verticalSlice($all, 'age', 'password'); + $this->assert(count($ages) === 5); + $this->assert($ages[''] === '15'); + + $passwords = DBHelper::reIndex($all, 'password'); + $this->assert(count($passwords) === 5); + $this->assert($passwords['']['username'] === 'Bart'); + $this->assert($passwords['']['password'] === NULL); + } + +} +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/ObjectTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/ObjectTest.php new file mode 100644 index 00000000..87c82bb7 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/ObjectTest.php @@ -0,0 +1,312 @@ +mdb = new MeekroDB(); + + foreach ($this->mdb->tableList() as $table) { + $this->mdb->query("DROP TABLE %b", $table); + } + } + + + function test_1_create_table() { + $this->mdb->query("CREATE TABLE `accounts` ( + `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , + `username` VARCHAR( 255 ) NOT NULL , + `password` VARCHAR( 255 ) NULL , + `age` INT NOT NULL DEFAULT '10', + `height` DOUBLE NOT NULL DEFAULT '10.0', + `favorite_word` VARCHAR( 255 ) NULL DEFAULT 'hi' + ) ENGINE = InnoDB"); + } + + function test_1_5_empty_table() { + $counter = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts"); + $this->assert($counter === strval(0)); + + $row = $this->mdb->queryFirstRow("SELECT * FROM accounts"); + $this->assert($row === null); + + $field = $this->mdb->queryFirstField("SELECT * FROM accounts"); + $this->assert($field === null); + + $field = $this->mdb->queryOneField('nothere', "SELECT * FROM accounts"); + $this->assert($field === null); + + $column = $this->mdb->queryFirstColumn("SELECT * FROM accounts"); + $this->assert(is_array($column) && count($column) === 0); + + $column = $this->mdb->queryOneColumn('nothere', "SELECT * FROM accounts"); //TODO: is this what we want? + $this->assert(is_array($column) && count($column) === 0); + } + + function test_2_insert_row() { + $this->mdb->insert('accounts', array( + 'username' => 'Abe', + 'password' => 'hello' + )); + + $this->assert($this->mdb->affectedRows() === 1); + + $counter = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts"); + $this->assert($counter === strval(1)); + } + + function test_3_more_inserts() { + $this->mdb->insert('`accounts`', array( + 'username' => 'Bart', + 'password' => 'hello', + 'age' => 15, + 'height' => 10.371 + )); + $dbname = $this->mdb->dbName; + $this->mdb->insert("`$dbname`.`accounts`", array( + 'username' => 'Charlie\'s Friend', + 'password' => 'goodbye', + 'age' => 30, + 'height' => 155.23, + 'favorite_word' => null, + )); + + $this->assert($this->mdb->insertId() === 3); + + $counter = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts"); + $this->assert($counter === strval(3)); + + $password = $this->mdb->queryFirstField("SELECT password FROM accounts WHERE favorite_word IS NULL"); + $this->assert($password === 'goodbye'); + + $this->mdb->param_char = '###'; + $bart = $this->mdb->queryFirstRow("SELECT * FROM accounts WHERE age IN ###li AND height IN ###ld AND username IN ###ls", + array(15, 25), array(10.371, 150.123), array('Bart', 'Barts')); + $this->assert($bart['username'] === 'Bart'); + $this->mdb->param_char = '%'; + + $charlie_password = $this->mdb->queryFirstField("SELECT password FROM accounts WHERE username IN %ls AND username = %s", + array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend'); + $this->assert($charlie_password === 'goodbye'); + + $charlie_password = $this->mdb->queryOneField('password', "SELECT * FROM accounts WHERE username IN %ls AND username = %s", + array('Charlie', 'Charlie\'s Friend'), 'Charlie\'s Friend'); + $this->assert($charlie_password === 'goodbye'); + + $passwords = $this->mdb->queryFirstColumn("SELECT password FROM accounts WHERE username=%s", 'Bart'); + $this->assert(count($passwords) === 1); + $this->assert($passwords[0] === 'hello'); + + $username = $password = $age = null; + list($age, $username, $password) = $this->mdb->queryOneList("SELECT age,username,password FROM accounts WHERE username=%s", 'Bart'); + $this->assert($username === 'Bart'); + $this->assert($password === 'hello'); + $this->assert($age == 15); + + $mysqli_result = $this->mdb->queryRaw("SELECT * FROM accounts WHERE favorite_word IS NULL"); + $this->assert($mysqli_result instanceof MySQLi_Result); + $row = $mysqli_result->fetch_assoc(); + $this->assert($row['password'] === 'goodbye'); + $this->assert($mysqli_result->fetch_assoc() === null); + } + + function test_4_query() { + $results = $this->mdb->query("SELECT * FROM accounts WHERE username=%s", 'Charlie\'s Friend'); + $this->assert(count($results) === 1); + $this->assert($results[0]['age'] == 30 && $results[0]['password'] == 'goodbye'); + + $results = $this->mdb->query("SELECT * FROM accounts WHERE username!=%s", "Charlie's Friend"); + $this->assert(count($results) === 2); + + $columnlist = $this->mdb->columnList('accounts'); + $this->assert(count($columnlist) === 6); + $this->assert($columnlist[0] === 'id'); + $this->assert($columnlist[4] === 'height'); + + $tablelist = $this->mdb->tableList(); + $this->assert(count($tablelist) === 1); + $this->assert($tablelist[0] === 'accounts'); + + $tablelist = null; + $tablelist = $this->mdb->tableList($this->mdb->dbName); + $this->assert(count($tablelist) === 1); + $this->assert($tablelist[0] === 'accounts'); + } + + function test_4_1_query() { + $this->mdb->insert('accounts', array( + 'username' => 'newguy', + 'password' => $this->mdb->sqleval("REPEAT('blah', %i)", '3'), + 'age' => $this->mdb->sqleval('171+1'), + 'height' => 111.15 + )); + + $row = $this->mdb->queryOneRow("SELECT * FROM accounts WHERE password=%s", 'blahblahblah'); + $this->assert($row['username'] === 'newguy'); + $this->assert($row['age'] === '172'); + + $this->mdb->update('accounts', array( + 'password' => $this->mdb->sqleval("REPEAT('blah', %i)", 4), + 'favorite_word' => null, + ), 'username=%s', 'newguy'); + + $row = null; + $row = $this->mdb->queryOneRow("SELECT * FROM accounts WHERE username=%s", 'newguy'); + $this->assert($row['password'] === 'blahblahblahblah'); + $this->assert($row['favorite_word'] === null); + + $this->mdb->query("DELETE FROM accounts WHERE password=%s", 'blahblahblahblah'); + $this->assert($this->mdb->affectedRows() === 1); + } + + function test_4_2_delete() { + $this->mdb->insert('accounts', array( + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + )); + + $ct = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', 199.194); + $this->assert(intval($ct) === 1); + + $ct = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s1 AND height=%d0 AND height=%d", 199.194, 'gonesoon'); + $this->assert(intval($ct) === 1); + + $this->mdb->delete('accounts', 'username=%s AND age=%i AND height=%d', 'gonesoon', '61', '199.194'); + $this->assert($this->mdb->affectedRows() === 1); + + $ct = $this->mdb->queryFirstField("SELECT COUNT(*) FROM accounts WHERE username=%s AND height=%d", 'gonesoon', '199.194'); + $this->assert(intval($ct) === 0); + } + + function test_4_3_insertmany() { + $ins[] = array( + 'username' => '1ofmany', + 'password' => 'something', + 'age' => 23, + 'height' => 190.194 + ); + $ins[] = array( + 'password' => 'somethingelse', + 'username' => '2ofmany', + 'age' => 25, + 'height' => 190.194 + ); + + $this->mdb->insert('accounts', $ins); + $this->assert($this->mdb->affectedRows() === 2); + + $rows = $this->mdb->query("SELECT * FROM accounts WHERE height=%d ORDER BY age ASC", 190.194); + $this->assert(count($rows) === 2); + $this->assert($rows[0]['username'] === '1ofmany'); + $this->assert($rows[0]['age'] === '23'); + $this->assert($rows[1]['age'] === '25'); + $this->assert($rows[1]['password'] === 'somethingelse'); + $this->assert($rows[1]['username'] === '2ofmany'); + + } + + + + function test_5_insert_blobs() { + $this->mdb->query("CREATE TABLE `storedata` ( + `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , + `picture` BLOB + ) ENGINE = InnoDB"); + + + $smile = file_get_contents('smile1.jpg'); + $this->mdb->insert('storedata', array( + 'picture' => $smile, + )); + $this->mdb->query("INSERT INTO storedata (picture) VALUES (%s)", $smile); + + $getsmile = $this->mdb->queryFirstField("SELECT picture FROM storedata WHERE id=1"); + $getsmile2 = $this->mdb->queryFirstField("SELECT picture FROM storedata WHERE id=2"); + $this->assert($smile === $getsmile); + $this->assert($smile === $getsmile2); + } + + function test_6_insert_ignore() { + $this->mdb->insertIgnore('accounts', array( + 'id' => 1, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + )); + } + + function test_7_insert_update() { + $this->mdb->insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ), 'age = age + %i', 1); + + $this->assert($this->mdb->affectedRows() === 2); // a quirk of MySQL, even though only 1 row was updated + + $result = $this->mdb->query("SELECT * FROM accounts WHERE age = %i", 16); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '10.371'); + + $this->mdb->insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'blahblahdude', + 'age' => 233, + 'height' => 199.194 + )); + + $result = $this->mdb->query("SELECT * FROM accounts WHERE age = %i", 233); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '199.194'); + $this->assert($result[0]['username'] === 'blahblahdude'); + + $this->mdb->insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ), array( + 'age' => 74, + )); + + $result = $this->mdb->query("SELECT * FROM accounts WHERE age = %i", 74); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '199.194'); + $this->assert($result[0]['username'] === 'blahblahdude'); + + $multiples[] = array( + 'id' => 3, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ); + $multiples[] = array( + 'id' => 1, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ); + + $this->mdb->insertUpdate('accounts', $multiples, array('age' => 914)); + $this->assert($this->mdb->affectedRows() === 4); + + $result = $this->mdb->query("SELECT * FROM accounts WHERE age=914 ORDER BY id ASC"); + $this->assert(count($result) === 2); + $this->assert($result[0]['username'] === 'Abe'); + $this->assert($result[1]['username'] === 'Charlie\'s Friend'); + + $this->mdb->query("UPDATE accounts SET age=15, username='Bart' WHERE age=%i", 74); + $this->assert($this->mdb->affectedRows() === 1); + } + +} + + +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/TransactionTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/TransactionTest.php new file mode 100644 index 00000000..76f1f231 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/TransactionTest.php @@ -0,0 +1,30 @@ +assert($depth === 1); + + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 700, 'Abe'); + $depth = DB::startTransaction(); + $this->assert($depth === 1); + + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 800, 'Abe'); + $depth = DB::rollback(); + $this->assert($depth === 0); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 700); + + $depth = DB::rollback(); + $this->assert($depth === 0); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 700); + } + +} +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/TransactionTest_55.php b/vendor/sergeytsalkov/meekrodb/simpletest/TransactionTest_55.php new file mode 100644 index 00000000..a4090984 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/TransactionTest_55.php @@ -0,0 +1,85 @@ +assert($depth === 1); + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 700, 'Abe'); + + $depth = DB::startTransaction(); + $this->assert($depth === 2); + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 800, 'Abe'); + + $depth = DB::startTransaction(); + $this->assert($depth === 3); + $this->assert(DB::transactionDepth() === 3); + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 500, 'Abe'); + $depth = DB::commit(); + + $this->assert($depth === 2); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 500); + + $depth = DB::rollback(); + $this->assert($depth === 1); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 700); + + $depth = DB::commit(); + $this->assert($depth === 0); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 700); + + + DB::$nested_transactions = false; + } + + function test_2_transactions() { + DB::$nested_transactions = true; + + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 600, 'Abe'); + + DB::startTransaction(); + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 700, 'Abe'); + DB::startTransaction(); + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 800, 'Abe'); + DB::rollback(); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 700); + + DB::rollback(); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 600); + + DB::$nested_transactions = false; + } + + function test_3_transaction_rollback_all() { + DB::$nested_transactions = true; + + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 200, 'Abe'); + + $depth = DB::startTransaction(); + $this->assert($depth === 1); + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 300, 'Abe'); + $depth = DB::startTransaction(); + $this->assert($depth === 2); + + DB::query("UPDATE accounts SET age=%i WHERE username=%s", 400, 'Abe'); + $depth = DB::rollback(true); + $this->assert($depth === 0); + + $age = DB::queryFirstField("SELECT age FROM accounts WHERE username=%s", 'Abe'); + $this->assert($age == 200); + + DB::$nested_transactions = false; + } + +} +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/WhereClauseTest.php b/vendor/sergeytsalkov/meekrodb/simpletest/WhereClauseTest.php new file mode 100644 index 00000000..45843d16 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/WhereClauseTest.php @@ -0,0 +1,73 @@ +add('username=%s', 'Bart'); + $where->add('password=%s', 'hello'); + + $result = DB::query("SELECT * FROM accounts WHERE %l", $where->text()); + $this->assert(count($result) === 1); + $this->assert($result[0]['age'] === '15'); + } + + function test_2_simple_grouping() { + $where = new WhereClause('and'); + $where->add('password=%s', 'hello'); + $subclause = $where->addClause('or'); + $subclause->add('age=%i', 15); + $subclause->add('age=%i', 14); + + $result = DB::query("SELECT * FROM accounts WHERE %l", $where->text()); + $this->assert(count($result) === 1); + $this->assert($result[0]['age'] === '15'); + } + + function test_3_negate_last() { + $where = new WhereClause('and'); + $where->add('password=%s', 'hello'); + $subclause = $where->addClause('or'); + $subclause->add('username!=%s', 'Bart'); + $subclause->negateLast(); + + $result = DB::query("SELECT * FROM accounts WHERE %l", $where->text()); + $this->assert(count($result) === 1); + $this->assert($result[0]['age'] === '15'); + } + + function test_4_negate_last_query() { + $where = new WhereClause('and'); + $where->add('password=%s', 'hello'); + $subclause = $where->addClause('or'); + $subclause->add('username!=%s', 'Bart'); + $where->negateLast(); + + $result = DB::query("SELECT * FROM accounts WHERE %l", $where); + $this->assert(count($result) === 1); + $this->assert($result[0]['age'] === '15'); + } + + function test_5_negate() { + $where = new WhereClause('and'); + $where->add('password=%s', 'hello'); + $subclause = $where->addClause('or'); + $subclause->add('username!=%s', 'Bart'); + $subclause->negate(); + + $result = DB::query("SELECT * FROM accounts WHERE %l", $where); + $this->assert(count($result) === 1); + $this->assert($result[0]['age'] === '15'); + } + + function test_6_or() { + $where = new WhereClause('or'); + $where->add('username=%s', 'Bart'); + $where->add('username=%s', 'Abe'); + + $result = DB::query("SELECT * FROM accounts WHERE %l", $where); + $this->assert(count($result) === 2); + } + + +} + +?> diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/smile1.jpg b/vendor/sergeytsalkov/meekrodb/simpletest/smile1.jpg new file mode 100644 index 00000000..67264965 Binary files /dev/null and b/vendor/sergeytsalkov/meekrodb/simpletest/smile1.jpg differ diff --git a/vendor/sergeytsalkov/meekrodb/simpletest/test.php b/vendor/sergeytsalkov/meekrodb/simpletest/test.php new file mode 100644 index 00000000..654e9ae2 --- /dev/null +++ b/vendor/sergeytsalkov/meekrodb/simpletest/test.php @@ -0,0 +1,86 @@ +#!/usr/bin/php +fail(); + } + + protected function fail($msg = '') { + echo "FAILURE! $msg\n"; + debug_print_backtrace(); + die; + } + + +} + +function microtime_float() +{ + list($usec, $sec) = explode(" ", microtime()); + return ((float)$usec + (float)$sec); +} + +if (phpversion() >= '5.3') $is_php_53 = true; +else $is_php_53 = false; + +ini_set('date.timezone', 'America/Los_Angeles'); + +error_reporting(E_ALL | E_STRICT); +require_once '../db.class.php'; +include 'test_setup.php'; //test config values go here +DB::$user = $set_db_user; +DB::$password = $set_password; +DB::$dbName = $set_db; +DB::$host = $set_host; +DB::get(); //connect to mysql + +require_once 'BasicTest.php'; +require_once 'CallTest.php'; +require_once 'ObjectTest.php'; +require_once 'WhereClauseTest.php'; +require_once 'ErrorTest.php'; +require_once 'TransactionTest.php'; +require_once 'HelperTest.php'; + +$classes_to_test = array( + 'BasicTest', + 'CallTest', + 'WhereClauseTest', + 'ObjectTest', + 'ErrorTest', + 'TransactionTest', + 'HelperTest', +); + +if ($is_php_53) { + require_once 'ErrorTest_53.php'; + $classes_to_test[] = 'ErrorTest_53'; +} else { + echo "PHP 5.3 not detected, skipping 5.3 tests..\n"; +} + +$mysql_version = DB::serverVersion(); +if ($mysql_version >= '5.5') { + require_once 'TransactionTest_55.php'; + $classes_to_test[] = 'TransactionTest_55'; +} else { + echo "MySQL 5.5 not available (version is $mysql_version) -- skipping MySQL 5.5 tests\n"; +} + +$time_start = microtime_float(); +foreach ($classes_to_test as $class) { + $object = new $class(); + + foreach (get_class_methods($object) as $method) { + if (substr($method, 0, 4) != 'test') continue; + echo "Running $class::$method..\n"; + $object->$method(); + } +} +$time_end = microtime_float(); +$time = round($time_end - $time_start, 2); + +echo "Completed in $time seconds\n"; + + +?>