Initial commit: apps.supersam24.ru
This commit is contained in:
commit
72afea602d
2747 files changed
+682150
No files matched your search
@@ -0,0 +1,8 @@
|
||||
{"presets": [
|
||||
"@babel/env",
|
||||
["minify", {
|
||||
"keepFnName": true,
|
||||
"keepClassName": true,
|
||||
"mangle": false
|
||||
}]
|
||||
]}
|
||||
@@ -0,0 +1,24 @@
|
||||
; This file is for unifying the coding style for different editors and IDEs.
|
||||
; More information at http://editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.bat]
|
||||
end_of_line = crlf
|
||||
|
||||
[*.yml]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.twig]
|
||||
insert_final_newline = false
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
@@ -0,0 +1,5 @@
|
||||
tmp
|
||||
logs
|
||||
.idea
|
||||
files
|
||||
archive/*
|
||||
@@ -0,0 +1,13 @@
|
||||
# Uncomment the following to prevent the httpoxy vulnerability
|
||||
# See: https://httpoxy.org/
|
||||
#<IfModule mod_headers.c>
|
||||
# RequestHeader unset Proxy
|
||||
#</IfModule>
|
||||
|
||||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine on
|
||||
RewriteBase /
|
||||
RewriteRule ^(\.well-known/.*)$ $1 [L]
|
||||
RewriteRule ^$ webroot/ [L]
|
||||
RewriteRule (.*) webroot/$1 [L]
|
||||
</IfModule>
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
language: php
|
||||
|
||||
dist: trusty
|
||||
|
||||
sudo: false
|
||||
|
||||
php:
|
||||
- 5.6
|
||||
- 7.0
|
||||
- 7.1
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
|
||||
include:
|
||||
- php: 7.0
|
||||
env: PHPCS=1
|
||||
|
||||
before_script:
|
||||
- if [[ $PHPCS = 1 ]]; then composer require cakephp/cakephp-codesniffer:~2.1; fi
|
||||
- if [[ $PHPCS != 1 ]]; then composer install; fi
|
||||
- if [[ $PHPCS != 1 ]]; then composer require phpunit/phpunit:"^5.7|^6.0"; fi
|
||||
- if [[ $PHPCS != 1 ]]; then composer run-script post-install-cmd --no-interaction; fi
|
||||
|
||||
script:
|
||||
- if [[ $PHPCS != 1 ]]; then vendor/bin/phpunit; fi
|
||||
- if [[ $PHPCS = 1 ]]; then vendor/bin/phpcs -p --extensions=php --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests ./config ./webroot; fi
|
||||
|
||||
notifications:
|
||||
email: false
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env sh
|
||||
################################################################################
|
||||
#
|
||||
# Cake is a shell script for invoking CakePHP shell commands
|
||||
#
|
||||
# CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
#
|
||||
# Licensed under The MIT License
|
||||
# For full copyright and license information, please see the LICENSE.txt
|
||||
# Redistributions of files must retain the above copyright notice.
|
||||
#
|
||||
# @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
# @link https://cakephp.org CakePHP(tm) Project
|
||||
# @since 1.2.0
|
||||
# @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Canonicalize by following every symlink of the given name recursively
|
||||
canonicalize() {
|
||||
NAME="$1"
|
||||
if [ -f "$NAME" ]
|
||||
then
|
||||
DIR=$(dirname -- "$NAME")
|
||||
NAME=$(cd -P "$DIR" > /dev/null && pwd -P)/$(basename -- "$NAME")
|
||||
fi
|
||||
while [ -h "$NAME" ]; do
|
||||
DIR=$(dirname -- "$NAME")
|
||||
SYM=$(readlink "$NAME")
|
||||
NAME=$(cd "$DIR" > /dev/null && cd $(dirname -- "$SYM") > /dev/null && pwd)/$(basename -- "$SYM")
|
||||
done
|
||||
echo "$NAME"
|
||||
}
|
||||
|
||||
CONSOLE=$(dirname -- "$(canonicalize "$0")")
|
||||
APP=$(dirname "$CONSOLE")
|
||||
|
||||
if [ $(basename $0) != 'cake' ]
|
||||
then
|
||||
exec php "$CONSOLE"/cake.php $(basename $0) "$@"
|
||||
else
|
||||
exec php "$CONSOLE"/cake.php "$@"
|
||||
fi
|
||||
|
||||
exit
|
||||
@@ -0,0 +1,27 @@
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::
|
||||
:: Cake is a Windows batch script for invoking CakePHP shell commands
|
||||
::
|
||||
:: CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
:: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
::
|
||||
:: Licensed under The MIT License
|
||||
:: Redistributions of files must retain the above copyright notice.
|
||||
::
|
||||
:: @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
:: @link https://cakephp.org CakePHP(tm) Project
|
||||
:: @since 2.0.0
|
||||
:: @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
|
||||
@echo off
|
||||
|
||||
SET app=%0
|
||||
SET lib=%~dp0
|
||||
|
||||
c:\xampp\php7\php "%lib%cake.php" %*
|
||||
|
||||
echo.
|
||||
|
||||
exit /B %ERRORLEVEL%
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/php -q
|
||||
<?php
|
||||
// Check platform requirements
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Application;
|
||||
use Cake\Console\CommandRunner;
|
||||
|
||||
// Build the runner with an application and root executable name.
|
||||
$runner = new CommandRunner(new Application(dirname(__DIR__) . '/config'), 'cake');
|
||||
exit($runner->run($argv));
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "cakephp/app",
|
||||
"description": "CakePHP skeleton app",
|
||||
"homepage": "https://cakephp.org",
|
||||
"type": "project",
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=7.0",
|
||||
"ext-gd": "*",
|
||||
"ext-mbstring": "*",
|
||||
"cakephp/cakephp": "3.8.*",
|
||||
"cakephp/migrations": "^2.0.0",
|
||||
"cakephp/plugin-installer": "^1.0",
|
||||
"dompdf/dompdf": "^0.8.3",
|
||||
"josegonzalez/dotenv": "3.*",
|
||||
"mobiledetect/mobiledetectlib": "2.*",
|
||||
"mpdf/mpdf": "^8.0",
|
||||
"paragonie/random_compat": "^1.4|^2.0",
|
||||
"parsecsv/php-parsecsv": "^1.1",
|
||||
"phpmailer/phpmailer": "^6.0",
|
||||
"phpoffice/phpspreadsheet": "^1.8"
|
||||
},
|
||||
"require-dev": {
|
||||
"cakephp/bake": "^1.9.0",
|
||||
"cakephp/cakephp-codesniffer": "^3.0",
|
||||
"cakephp/debug_kit": "^3.2",
|
||||
"psy/psysh": "@stable"
|
||||
},
|
||||
"suggest": {
|
||||
"markstory/asset_compress": "An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.",
|
||||
"dereuromark/cakephp-ide-helper": "After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan compatibility.",
|
||||
"phpunit/phpunit": "Allows automated tests to be run without system-wide install.",
|
||||
"cakephp/cakephp-codesniffer": "Allows to check the code against the coding standards used in CakePHP."
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"App\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"App\\Test\\": "tests/",
|
||||
"Cake\\Test\\": "vendor/cakephp/cakephp/tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"post-install-cmd": "App\\Console\\Installer::postInstall",
|
||||
"post-create-project-cmd": "App\\Console\\Installer::postInstall",
|
||||
"post-autoload-dump": "Cake\\Composer\\Installer\\PluginInstaller::postAutoloadDump",
|
||||
"check": [
|
||||
"@test",
|
||||
"@cs-check"
|
||||
],
|
||||
"cs-check": "phpcs --colors -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests",
|
||||
"cs-fix": "phpcbf --colors --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests",
|
||||
"test": "phpunit --colors=always"
|
||||
},
|
||||
"prefer-stable": true,
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
}
|
||||
}
|
||||
Generated
+3612
File diff suppressed because it is too large.
Load diff
+155
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
return [
|
||||
'debug' => false,
|
||||
|
||||
'Release' => "2.4.165",
|
||||
|
||||
'App' => [
|
||||
'namespace' => 'App',
|
||||
'encoding' => env('APP_ENCODING', 'UTF-8'),
|
||||
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
|
||||
'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
|
||||
'base' => false,
|
||||
'dir' => 'src',
|
||||
'webroot' => 'webroot',
|
||||
'wwwRoot' => WWW_ROOT,
|
||||
'imageBaseUrl' => 'img/',
|
||||
'cssBaseUrl' => 'css/',
|
||||
'jsBaseUrl' => 'js/',
|
||||
'paths' => [
|
||||
'plugins' => [ROOT . DS . 'plugins' . DS],
|
||||
'templates' => [APP . 'Template' . DS],
|
||||
'locales' => [APP . 'Locale' . DS],
|
||||
],
|
||||
],
|
||||
|
||||
'Security' => [
|
||||
'salt' => env('SECURITY_SALT', '2ae8d3f453c9f6a290a2fcdb173be1cf4acc871c6e656411c82aa331bbfefc18'),
|
||||
],
|
||||
|
||||
'Asset' => [
|
||||
// 'timestamp' => true,
|
||||
],
|
||||
|
||||
'Cache' => [
|
||||
'default' => [
|
||||
'className' => 'File',
|
||||
'path' => CACHE,
|
||||
'url' => env('CACHE_DEFAULT_URL', null),
|
||||
],
|
||||
|
||||
'_cake_core_' => [
|
||||
'className' => 'File',
|
||||
'prefix' => 'myapp_cake_core_',
|
||||
'path' => CACHE . 'persistent/',
|
||||
'serialize' => true,
|
||||
'duration' => '+1 years',
|
||||
'url' => env('CACHE_CAKECORE_URL', null),
|
||||
],
|
||||
|
||||
'_cake_model_' => [
|
||||
'className' => 'File',
|
||||
'prefix' => 'myapp_cake_model_',
|
||||
'path' => CACHE . 'models/',
|
||||
'serialize' => true,
|
||||
'duration' => '+1 years',
|
||||
'url' => env('CACHE_CAKEMODEL_URL', null),
|
||||
],
|
||||
],
|
||||
|
||||
|
||||
'Error' => [
|
||||
'errorLevel' => E_ALL,
|
||||
'exceptionRenderer' => 'Cake\Error\ExceptionRenderer',
|
||||
'skipLog' => [],
|
||||
'log' => true,
|
||||
'trace' => true,
|
||||
],
|
||||
|
||||
|
||||
'Datasources' => [
|
||||
'default' => [
|
||||
'className' => 'Cake\Database\Connection',
|
||||
'driver' => 'Cake\Database\Driver\Mysql',
|
||||
'persistent' => false,
|
||||
'host' => 'localhost',
|
||||
|
||||
'username' => 'supersam_apps',
|
||||
'password' => 'Ft8wV%e3Fre#ZaH-nJ',
|
||||
'database' => 'supersam_apps',
|
||||
'encoding' => 'utf8',
|
||||
'timezone' => 'UTC',
|
||||
'flags' => [],
|
||||
'cacheMetadata' => true,
|
||||
'log' => false,
|
||||
|
||||
'quoteIdentifiers' => true,
|
||||
'url' => env('DATABASE_URL', null),
|
||||
],
|
||||
],
|
||||
|
||||
'Log' => [
|
||||
'debug' => [
|
||||
'className' => 'Cake\Log\Engine\FileLog',
|
||||
'path' => LOGS,
|
||||
'file' => 'debug',
|
||||
'url' => env('LOG_DEBUG_URL', null),
|
||||
'scopes' => false,
|
||||
'levels' => ['notice', 'info', 'debug'],
|
||||
],
|
||||
'error' => [
|
||||
'className' => 'Cake\Log\Engine\FileLog',
|
||||
'path' => LOGS,
|
||||
'file' => 'error',
|
||||
'url' => env('LOG_ERROR_URL', null),
|
||||
'scopes' => false,
|
||||
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
|
||||
],
|
||||
'queries' => [
|
||||
'className' => 'Cake\Log\Engine\FileLog',
|
||||
'path' => LOGS,
|
||||
'file' => 'queries',
|
||||
'url' => env('LOG_QUERIES_URL', null),
|
||||
'scopes' => ['queriesLog'],
|
||||
],
|
||||
],
|
||||
|
||||
'Session' => [
|
||||
'defaults' => 'php',
|
||||
'ini' => [
|
||||
'session.cookie_lifetime' => 18*60*60, //18h
|
||||
'session.cookie_httponly' => true
|
||||
],
|
||||
'timeout' => 12 * 60 //12h
|
||||
],
|
||||
|
||||
'mpdfPageParams' => [
|
||||
'mode' => 'utf-8',
|
||||
'format' => 'A4',
|
||||
'default_font_size' => 0,
|
||||
'default_font' => 'arial',
|
||||
'margin_left' => 15,
|
||||
'margin_right' => 15,
|
||||
'margin_top' => 17,
|
||||
'margin_bottom' => 30
|
||||
],
|
||||
'smsMinimalBalance' => 50,
|
||||
|
||||
"encrypt" => [
|
||||
"key" => 'fsjlksf$#%WEtfvV34v59fHgi3rs0gBB<T58903--.we8934W$w3',
|
||||
"cipher" => "AES-128-CBC",
|
||||
"options" => OPENSSL_RAW_DATA,
|
||||
"as_binary" => true
|
||||
],
|
||||
|
||||
'ftpParams' => [
|
||||
'ip' => '188.191.27.165',
|
||||
'port' => 53530,
|
||||
'username' => 'soronorus',
|
||||
'password' => '5#NqtYB;XOC;!wAtp',
|
||||
|
||||
'acquiring24Out' => '/supersam24.ru/acquiring-in',
|
||||
'acquiring24In' => '/supersam24.ru/acquiring-out',
|
||||
'acquiring24Refund' => '/supersam24.ru/refund',
|
||||
]
|
||||
];
|
||||
@@ -0,0 +1,243 @@
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/paths.php';
|
||||
|
||||
|
||||
require CORE_PATH . 'config' . DS . 'bootstrap.php';
|
||||
|
||||
use Cake\Cache\Cache;
|
||||
use Cake\Console\ConsoleErrorHandler;
|
||||
use Cake\Core\App;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\Configure\Engine\PhpConfig;
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Database\Type;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\Error\ErrorHandler;
|
||||
use Cake\Http\ServerRequest;
|
||||
use Cake\Log\Log;
|
||||
use Cake\Mailer\Email;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Utility\Inflector;
|
||||
use Cake\Utility\Security;
|
||||
|
||||
try {
|
||||
Configure::config('default', new PhpConfig());
|
||||
Configure::load('app', 'default', false);
|
||||
} catch (\Exception $e) {
|
||||
exit($e->getMessage() . "\n");
|
||||
}
|
||||
|
||||
|
||||
if (Configure::read('debug')) {
|
||||
Configure::write('Cache._cake_model_.duration', '+2 minutes');
|
||||
Configure::write('Cache._cake_core_.duration', '+2 minutes');
|
||||
// disable router cache during development
|
||||
Configure::write('Cache._cake_routes_.duration', '+2 seconds');
|
||||
}
|
||||
|
||||
|
||||
date_default_timezone_set('Europe/Moscow');
|
||||
|
||||
mb_internal_encoding(Configure::read('App.encoding'));
|
||||
|
||||
|
||||
ini_set('intl.default_locale', Configure::read('App.defaultLocale'));
|
||||
|
||||
|
||||
$isCli = PHP_SAPI === 'cli';
|
||||
if ($isCli) {
|
||||
(new ConsoleErrorHandler(Configure::read('Error')))->register();
|
||||
} else {
|
||||
(new ErrorHandler(Configure::read('Error')))->register();
|
||||
}
|
||||
|
||||
|
||||
if ($isCli) {
|
||||
require __DIR__ . '/bootstrap_cli.php';
|
||||
}
|
||||
|
||||
|
||||
if (!Configure::read('App.fullBaseUrl')) {
|
||||
$s = null;
|
||||
if (env('HTTPS')) {
|
||||
$s = 's';
|
||||
}
|
||||
|
||||
$httpHost = env('HTTP_HOST');
|
||||
if (isset($httpHost)) {
|
||||
Configure::write('App.fullBaseUrl', 'http' . $s . '://' . $httpHost);
|
||||
}
|
||||
unset($httpHost, $s);
|
||||
}
|
||||
|
||||
Cache::setConfig(Configure::consume('Cache'));
|
||||
ConnectionManager::setConfig(Configure::consume('Datasources'));
|
||||
//Email::setConfigTransport(Configure::consume('EmailTransport'));
|
||||
//Email::setConfig(Configure::consume('Email'));
|
||||
Log::setConfig(Configure::consume('Log'));
|
||||
Security::setSalt(Configure::consume('Security.salt'));
|
||||
|
||||
|
||||
ServerRequest::addDetector('mobile', function ($request) {
|
||||
$detector = new \Detection\MobileDetect();
|
||||
|
||||
return $detector->isMobile();
|
||||
});
|
||||
ServerRequest::addDetector('tablet', function ($request) {
|
||||
$detector = new \Detection\MobileDetect();
|
||||
|
||||
return $detector->isTablet();
|
||||
});
|
||||
|
||||
|
||||
Type::build('time')
|
||||
->useImmutable();
|
||||
Type::build('date')
|
||||
->useImmutable();
|
||||
Type::build('datetime')
|
||||
->useImmutable();
|
||||
Type::build('timestamp')
|
||||
->useImmutable();
|
||||
|
||||
require_once(ROOT . DS . 'vendor' . DS . 'dbf' . DS . 'DBF.class.php');
|
||||
require_once(ROOT . DS . 'vendor' . DS . 'sms' . DS . 'sms.ru.php');
|
||||
require_once(ROOT . DS . 'vendor' . DS . 'browser_detection' . DS . 'BrowserDetection.php');
|
||||
//require_once(ROOT . DS . 'vendor' . DS . 'mpdf' . DS . 'mpdf.php');
|
||||
|
||||
function cmpDetailsByBothSides($a, $b) {
|
||||
if (max($a->width, $a->height) != max($b->width, $b->height)) {
|
||||
return (max($a->width, $a->height) > max($b->width, $b->height)) ? -1 : 1;
|
||||
} else {
|
||||
if (min($a->width, $a->height) != min($b->width, $b->height)) {
|
||||
return (min($a->width, $a->height) > min($b->width, $b->height)) ? -1 : 1;
|
||||
} else {
|
||||
if ($a->height != $b->height) {
|
||||
return ($a->height > $b->height ) ? -1 : 1;
|
||||
} else {
|
||||
if ($a->width == $b->width ) {
|
||||
return 0;
|
||||
}
|
||||
return ($a->width > $b->width ) ? -1 : 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cmpDetailsByBothSidesReversed($a, $b) {
|
||||
if (max($a->width, $a->height) != max($b->width, $b->height)) {
|
||||
return (max($a->width, $a->height) > max($b->width, $b->height)) ? 1 : -1;
|
||||
} else {
|
||||
if (min($a->width, $a->height) != min($b->width, $b->height)) {
|
||||
return (min($a->width, $a->height) > min($b->width, $b->height)) ? 1 : -1;
|
||||
} else {
|
||||
if ($a->height != $b->height) {
|
||||
return ($a->height > $b->height ) ? 1 : -1;
|
||||
} else {
|
||||
if ($a->width == $b->width ) {
|
||||
return 0;
|
||||
}
|
||||
return ($a->width > $b->width ) ? 1 : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function cmpDetailsByWidth($a, $b) {
|
||||
if ($a->width != $b->width) {
|
||||
return ($a->width > $b->width ) ? -1 : 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function cmpDetailsByWidthReversed($a, $b) {
|
||||
if ($a->width != $b->width) {
|
||||
return ($a->width > $b->width ) ? 1 : -1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function cmpDetailsByHeight($a, $b) {
|
||||
if ($a->height != $b->height) {
|
||||
return ($a->height > $b->height ) ? -1 : 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function cmpDetailsByHeightReversed($a, $b) {
|
||||
if ($a->height != $b->height) {
|
||||
return ($a->height > $b->height ) ? 1 : -1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function cmpDetailsByBothSidesForToTop($a, $b) {
|
||||
if ($a->height != $b->height) {
|
||||
return ($a->height > $b->height ) ? -1 : 1;
|
||||
} else {
|
||||
if ($a->width != $b->width) {
|
||||
return ($a->width > $b->width ) ? -1 : 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
|
||||
function mb_ucfirst($string) {
|
||||
$string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
|
||||
return $string;
|
||||
}
|
||||
}
|
||||
|
||||
function toFixed2($num) {
|
||||
return str_replace(".00", "", number_format(ceil($num * 10000) / 10000, 2, ".", ""));
|
||||
}
|
||||
|
||||
function toFixed2Price($num) {
|
||||
return number_format(str_replace(" ", "", $num), 2, ".", " ");
|
||||
}
|
||||
|
||||
function cleanupPhone($phone) {
|
||||
return str_replace(["+", "-", " ", "(", ")"], "", $phone);
|
||||
}
|
||||
|
||||
function formatPhone($phone) {
|
||||
return "+7 (" . substr($phone, 1, 3) . ") " . substr($phone, 4, 3) . "-" . substr($phone, 7, 2) . "-" . substr($phone, 9, 2);
|
||||
}
|
||||
|
||||
function cleanupEmail($email) {
|
||||
return str_replace([" "], "", $email);
|
||||
}
|
||||
|
||||
function br2nl($str) {
|
||||
return preg_replace('/\<br(\s*)?\/?\>/ui', "\r\n", $str);
|
||||
}
|
||||
|
||||
function cleanupDetailLabel($label) {
|
||||
return preg_replace("/_{2,}/", "_", preg_replace("/[^\w\d\\*]/ui", "_" , $label));
|
||||
}
|
||||
|
||||
function cleanupDetailLabel2($label) {
|
||||
return preg_replace("/_{2,}/", "_", preg_replace("/[^\w\d\\*\-]/ui", "_" , $label));
|
||||
}
|
||||
|
||||
|
||||
function counterPluralForm($number, $before, $after, $echoResults = false ) {
|
||||
$cases = array(2,0,1,1,1,2);
|
||||
|
||||
$result = $before[($number % 100 > 4 && $number % 100 < 20) ? 2 : $cases[min($number % 10, 5)]] . ' ' . $number . ' ' . $after[($number % 100 > 4 && $number % 100 < 20) ? 2 : $cases[min($number % 10, 5)]];
|
||||
|
||||
if ($echoResults) {
|
||||
echo $result;
|
||||
} else {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
use App\Application;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\Exception\MissingPluginException;
|
||||
use Cake\Core\Plugin;
|
||||
|
||||
|
||||
Configure::write('Log.error.file', 'cli-error');
|
||||
|
||||
try {
|
||||
Application::addPlugin('Bake');
|
||||
} catch (MissingPluginException $e) {
|
||||
|
||||
}
|
||||
|
||||
Application::addPlugin('Migrations');
|
||||
|
||||
function isLocked($lock_file) {
|
||||
# If lock file exists, check if stale. If exists and is not stale, return TRUE
|
||||
# Else, create lock file and return FALSE.
|
||||
|
||||
if( file_exists( $lock_file ) ) {
|
||||
# check if it's stale
|
||||
$lockingPID = trim( file_get_contents( $lock_file ) );
|
||||
|
||||
# Get all active PIDs.
|
||||
$pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );
|
||||
|
||||
# If PID is still active, return true
|
||||
if( in_array( $lockingPID, $pids ) ) return true;
|
||||
|
||||
# Lock-file is stale, so kill it. Then move on to re-creating it.
|
||||
//echo "Removing stale lock file.\n";
|
||||
unlink( $lock_file );
|
||||
}
|
||||
|
||||
file_put_contents( $lock_file, getmypid() . "\n" );
|
||||
return false;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license MIT License (https://opensource.org/licenses/mit-license.php)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Use the DS to separate the directories in other defines
|
||||
*/
|
||||
if (!defined('DS')) {
|
||||
define('DS', DIRECTORY_SEPARATOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* These defines should only be edited if you have cake installed in
|
||||
* a directory layout other than the way it is distributed.
|
||||
* When using custom settings be sure to use the DS and do not add a trailing DS.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The full path to the directory which holds "src", WITHOUT a trailing DS.
|
||||
*/
|
||||
define('ROOT', dirname(__DIR__));
|
||||
|
||||
/**
|
||||
* The actual directory name for the application directory. Normally
|
||||
* named 'src'.
|
||||
*/
|
||||
define('APP_DIR', 'src');
|
||||
|
||||
/**
|
||||
* Path to the application's directory.
|
||||
*/
|
||||
define('APP', ROOT . DS . APP_DIR . DS);
|
||||
|
||||
/**
|
||||
* Path to the config directory.
|
||||
*/
|
||||
define('CONFIG', ROOT . DS . 'config' . DS);
|
||||
|
||||
/**
|
||||
* File path to the webroot directory.
|
||||
*/
|
||||
define('WWW_ROOT', ROOT . DS . 'webroot' . DS);
|
||||
|
||||
/**
|
||||
* Path to the tests directory.
|
||||
*/
|
||||
define('TESTS', ROOT . DS . 'tests' . DS);
|
||||
|
||||
/**
|
||||
* Path to the temporary files directory.
|
||||
*/
|
||||
define('TMP', ROOT . DS . 'tmp' . DS);
|
||||
|
||||
/**
|
||||
* Path to the logs directory.
|
||||
*/
|
||||
define('LOGS', ROOT . DS . 'logs' . DS);
|
||||
|
||||
/**
|
||||
* Path to the cache files directory. It can be shared between hosts in a multi-server setup.
|
||||
*/
|
||||
define('CACHE', TMP . 'cache' . DS);
|
||||
|
||||
/**
|
||||
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
|
||||
*
|
||||
* CakePHP should always be installed with composer, so look there.
|
||||
*/
|
||||
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp');
|
||||
|
||||
/**
|
||||
* Path to the cake directory.
|
||||
*/
|
||||
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
|
||||
define('CAKE', CORE_PATH . 'src' . DS);
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Routing\RouteBuilder;
|
||||
use Cake\Routing\Router;
|
||||
use Cake\Routing\Route\DashedRoute;
|
||||
|
||||
Router::defaultRouteClass(DashedRoute::class);
|
||||
|
||||
|
||||
Router::scope('/', function (RouteBuilder $routes) {
|
||||
$routes->connect('/', ['controller' => 'OrderPayment', 'action' => 'display']);
|
||||
|
||||
$routes->connect('/delivery', ['controller' => 'Delivery', 'action' => 'display']);
|
||||
$routes->connect('/delivery/:city', ['controller' => 'Delivery', 'action' => 'display'], ['city' => '\w+', 'pass' => ['city']]);
|
||||
|
||||
$routes->fallbacks(DashedRoute::class);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
#
|
||||
# Licensed under The MIT License
|
||||
# For full copyright and license information, please see the LICENSE.txt
|
||||
# Redistributions of files must retain the above copyright notice.
|
||||
# MIT License (https://opensource.org/licenses/mit-license.php)
|
||||
|
||||
CREATE TABLE i18n (
|
||||
id int NOT NULL auto_increment,
|
||||
locale varchar(6) NOT NULL,
|
||||
model varchar(255) NOT NULL,
|
||||
foreign_key int(10) NOT NULL,
|
||||
field varchar(255) NOT NULL,
|
||||
content text,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE INDEX I18N_LOCALE_FIELD(locale, model, foreign_key, field),
|
||||
INDEX I18N_FIELD(model, foreign_key, field)
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
#
|
||||
# Licensed under The MIT License
|
||||
# For full copyright and license information, please see the LICENSE.txt
|
||||
# Redistributions of files must retain the above copyright notice.
|
||||
# MIT License (https://opensource.org/licenses/mit-license.php)
|
||||
|
||||
CREATE TABLE `sessions` (
|
||||
`id` char(40) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
`created` datetime DEFAULT CURRENT_TIMESTAMP, -- optional, requires MySQL 5.6.5+
|
||||
`modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- optional, requires MySQL 5.6.5+
|
||||
`data` blob DEFAULT NULL, -- for PostgreSQL use bytea instead of blob
|
||||
`expires` int(10) unsigned DEFAULT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
DROP TABLE IF EXISTS `cut_borders`;
|
||||
CREATE TABLE `cut_borders` (
|
||||
`id` int(11) NOT NULL,
|
||||
`label` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
|
||||
`short_label` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
||||
|
||||
INSERT INTO `cut_borders` (`id`, `label`, `short_label`) VALUES
|
||||
(1, 'ORIGIN Рехау 087Т дуб сонома', 'Р 087Т'),
|
||||
(2, 'ORIGIN Рехау 14650 крем', 'Р 14650'),
|
||||
(3, 'ORIGIN Рехау 200V венге темный', 'Р 200V'),
|
||||
(4, 'ORIGIN Рехау 226W акация лэйклэнд', 'Р 226W'),
|
||||
(5, 'ORIGIN Рехау 4163 Орех', 'Р 4163'),
|
||||
(6, 'ORIGIN Рехау 4214 Вишня', 'Р 4214'),
|
||||
(7, 'ORIGIN Рехау 4526 бук', 'Р 4526'),
|
||||
(8, 'ORIGIN Рехау 463W ноче экко', 'Р 463W'),
|
||||
(9, 'ORIGIN Рехау 4919 береза', 'Р 4919'),
|
||||
(10, 'ORIGIN Рехау 553W вудлайн кремовый', 'Р 553W'),
|
||||
(11, 'ORIGIN Рехау 6240', 'Р 6240'),
|
||||
(12, 'ORIGIN Рехау 77002 капучино', 'Р 77002'),
|
||||
(13, 'ORIGIN Рехау 848 W капуччино т-36', 'Р 848W'),
|
||||
(14, 'ORIGIN Рехау 849W дуб дымчатый', 'Р 849W'),
|
||||
(15, 'ORIGIN Рехау 91470 Ш. Б./ORIGIN 77039', 'Р 91470-O 77039'),
|
||||
(16, 'ORIGIN Рехау 9991 Клен', 'Р 9991'),
|
||||
(17, 'ORIGINAL Рехау 710 W Маслина Севилья', 'Р 710W'),
|
||||
(18, 'TREND RAL9010 / ORIGIN Белый структура', 'T RAL9010'),
|
||||
(19, 'TREND/ORIGINAL Рехау 599V Орех', 'T-Р 599V'),
|
||||
(20, 'TREND Рехау 1147W Дуб серый', 'T-Р 1147W'),
|
||||
(21, 'TREND Рехау 1416W Твист светлый', 'T-Р1416W'),
|
||||
(22, 'TREND Рехау 15504 розовый', 'T-Р 15504'),
|
||||
(23, 'TREND Рехау 2127W Ясень Шимо темный', 'T-Р 2127W'),
|
||||
(24, 'TREND Рехау 2128W Ясень Шимо светлый 454', 'T-Р 2128W'),
|
||||
(25, 'TREND Рехау 2459W Орех темный Селект', 'T-Р 2459W'),
|
||||
(26, 'TREND Рехау 322W дуб феррара', 'T-Р 322W'),
|
||||
(27, 'TREND Рехау 589V орех аида натуральный', 'T-Р 589V'),
|
||||
(28, 'TREND Рехау 69164 желто-зеленый', 'T-Р 69164'),
|
||||
(29, 'TREND Рехау 69165 Голубой', 'T-Р 69165'),
|
||||
(30, 'TREND Рехау 76399 Ваниль', 'T-Р 76399'),
|
||||
(31, 'TREND Рехау 76401 Черный/ORIGIN 601', 'T-Р 76401/O-601'),
|
||||
(32, 'TREND Рехау 76962 желтый', 'T-Р 76962'),
|
||||
(33, 'TREND Рехау 76973 черный графит', 'T-Р 76973'),
|
||||
(34, 'TREND Рехау 76989 светло-серый', 'T-Р 76989'),
|
||||
(35, 'TREND Рехау 76996 оранжевый', 'T-Р 76996'),
|
||||
(36, 'TREND Рехау 77039 белый гладкий', 'T-Р 77039'),
|
||||
(37, 'TREND Рехау 78243 Ирис', 'T-Р 78243'),
|
||||
(38, 'TREND Рехау 812V Дуб Шато серый', 'T-Р 812V'),
|
||||
(39, 'TREND/ORIGINAL Рехау 6071 дуб выбеленный', 'T/O-Р 6071'),
|
||||
(40, 'TREND/ORIGINAL Рехау 1309W сосна лоредо', 'T/O-Р 1309W'),
|
||||
(41, 'TREND/ORIGINAL Рехау 7064 дуб молочный', 'T/O-Р 7064');
|
||||
|
||||
DROP TABLE IF EXISTS `cut_border_available_dimensions`;
|
||||
CREATE TABLE `cut_border_available_dimensions` (
|
||||
`id` int(11) NOT NULL,
|
||||
`border_id` int(11) DEFAULT NULL,
|
||||
`border_dimension_id` int(11) NOT NULL,
|
||||
`price` decimal(10,2) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
||||
|
||||
INSERT INTO `cut_border_available_dimensions` (`id`, `border_id`, `border_dimension_id`, `price`) VALUES
|
||||
(1, 1, 1, '8.10'),
|
||||
(2, 1, 4, '41.80'),
|
||||
(3, 13, 3, '22.10'),
|
||||
(4, 14, 1, '8.10'),
|
||||
(5, 14, 3, '22.10'),
|
||||
(6, 14, 4, '31.70'),
|
||||
(7, 3, 1, '8.10'),
|
||||
(8, 3, 3, '22.10'),
|
||||
(9, 3, 4, '31.70'),
|
||||
(10, 7, 1, '8.10'),
|
||||
(11, 7, 3, '22.10'),
|
||||
(12, 7, 4, '31.70'),
|
||||
(13, 10, 1, '8.10'),
|
||||
(14, 10, 3, '22.10'),
|
||||
(15, 10, 4, '31.70'),
|
||||
(16, 41, 1, '8.10'),
|
||||
(17, 41, 3, '22.10'),
|
||||
(18, 41, 4, '31.70'),
|
||||
(22, 4, 1, '8.10'),
|
||||
(23, 4, 2, '28.09'),
|
||||
(24, 4, 4, '31.70'),
|
||||
(25, 9, 1, '8.10'),
|
||||
(26, 9, 2, '28.09'),
|
||||
(27, 9, 4, '31.70'),
|
||||
(28, 6, 1, '8.10'),
|
||||
(29, 6, 3, '28.09'),
|
||||
(30, 6, 4, '31.70'),
|
||||
(31, 16, 1, '8.10'),
|
||||
(32, 16, 3, '28.09'),
|
||||
(33, 16, 4, '31.70'),
|
||||
(34, 2, 1, '6.20'),
|
||||
(35, 2, 3, '20.50'),
|
||||
(36, 2, 4, '24.90'),
|
||||
(37, 12, 1, '6.20'),
|
||||
(38, 12, 3, '20.50'),
|
||||
(39, 12, 4, '24.90'),
|
||||
(40, 15, 1, '6.20'),
|
||||
(41, 15, 3, '20.50'),
|
||||
(42, 15, 4, '24.90'),
|
||||
(43, 30, 1, '7.30'),
|
||||
(44, 30, 3, '22.00'),
|
||||
(45, 30, 4, '30.00'),
|
||||
(46, 34, 1, '7.30'),
|
||||
(47, 34, 3, '22.00'),
|
||||
(48, 34, 4, '30.00'),
|
||||
(49, 35, 1, '7.30'),
|
||||
(50, 35, 3, '22.00'),
|
||||
(51, 35, 4, '30.00'),
|
||||
(52, 36, 1, '7.30'),
|
||||
(53, 36, 3, '22.00'),
|
||||
(54, 36, 4, '30.00'),
|
||||
(55, 26, 1, '10.30'),
|
||||
(56, 26, 3, '25.90'),
|
||||
(57, 26, 4, '41.80'),
|
||||
(58, 38, 1, '10.30'),
|
||||
(59, 38, 3, '25.90'),
|
||||
(60, 38, 4, '41.80'),
|
||||
(61, 40, 1, '10.30'),
|
||||
(62, 40, 3, '25.90'),
|
||||
(63, 40, 4, '31.70'),
|
||||
(64, 5, 1, '7.00'),
|
||||
(65, 5, 3, '22.10'),
|
||||
(66, 5, 4, '31.70'),
|
||||
(67, 27, 1, '10.30'),
|
||||
(68, 27, 4, '31.70'),
|
||||
(69, 23, 1, '10.30'),
|
||||
(70, 23, 4, '41.80'),
|
||||
(71, 24, 1, '10.30'),
|
||||
(72, 24, 4, '41.80'),
|
||||
(73, 20, 1, '10.30'),
|
||||
(74, 20, 4, '41.80'),
|
||||
(75, 21, 1, '10.30'),
|
||||
(76, 21, 4, '41.80'),
|
||||
(77, 25, 1, '10.30'),
|
||||
(78, 25, 4, '41.80'),
|
||||
(79, 39, 1, '10.30'),
|
||||
(80, 39, 4, '31.70'),
|
||||
(81, 33, 1, '7.30'),
|
||||
(82, 33, 4, '30.00'),
|
||||
(83, 22, 1, '7.30'),
|
||||
(84, 22, 4, '30.00'),
|
||||
(85, 28, 1, '7.30'),
|
||||
(86, 28, 4, '30.00'),
|
||||
(87, 29, 1, '7.30'),
|
||||
(88, 29, 4, '30.00'),
|
||||
(89, 32, 1, '7.30'),
|
||||
(90, 32, 4, '30.00'),
|
||||
(91, 37, 1, '7.30'),
|
||||
(92, 37, 4, '30.00'),
|
||||
(93, 19, 1, '8.10'),
|
||||
(94, 19, 4, '41.80'),
|
||||
(95, 31, 3, '22.00'),
|
||||
(96, 31, 4, '24.90'),
|
||||
(97, 11, 2, '20.00'),
|
||||
(98, 11, 4, '31.70'),
|
||||
(99, 17, 2, '28.09'),
|
||||
(100, 17, 4, '31.70'),
|
||||
(101, 8, 3, '28.09'),
|
||||
(102, 18, 3, '25.90'),
|
||||
(103, 18, 1, '8.10'),
|
||||
(104, 18, 4, '31.70');
|
||||
|
||||
DROP TABLE IF EXISTS `cut_border_dimensions`;
|
||||
CREATE TABLE `cut_border_dimensions` (
|
||||
`id` int(11) NOT NULL,
|
||||
`label` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
|
||||
`short_label` varchar(16) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
|
||||
`gluing_price` decimal(10,2) DEFAULT NULL,
|
||||
`2dp_id` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
||||
|
||||
INSERT INTO `cut_border_dimensions` (`id`, `label`, `short_label`, `gluing_price`, `2dp_id`) VALUES
|
||||
(1, '19*0,4 ПВХ', '19*0,4', '18.00', '8'),
|
||||
(2, '23*0,8 ПВХ', '23*0,8', '19.00', '12'),
|
||||
(3, '19*1 ПВХ', '19*1', '19.00', '1'),
|
||||
(4, '19*2 ПВХ', '19*2', '22.00', '2');
|
||||
|
||||
DROP TABLE IF EXISTS `cut_sheets`;
|
||||
CREATE TABLE `cut_sheets` (
|
||||
`id` int(11) NOT NULL,
|
||||
`label` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
|
||||
`sheet_dimension_id` int(11) NOT NULL,
|
||||
`default_border_id` int(11) DEFAULT NULL,
|
||||
`price` decimal(10,2) NOT NULL,
|
||||
`is_active` tinyint(1) NOT NULL DEFAULT '1'
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
||||
|
||||
INSERT INTO `cut_sheets` (`id`, `label`, `sheet_dimension_id`, `default_border_id`, `price`, `is_active`) VALUES
|
||||
(1, 'Белая структура 605 SWA', 2, 18, '1990.00', 1),
|
||||
(2, 'Белая шагрень 605 PE', 2, 15, '1990.00', 1),
|
||||
(3, 'Белый 605 SG', 3, 36, '2255.00', 1),
|
||||
(4, 'Белый 605 SWN', 3, 18, '2255.00', 1),
|
||||
(5, 'Белый гладкий 605 SМ', 2, 15, '1990.00', 1),
|
||||
(6, 'Береза 261 SWN', 3, 13, '2310.00', 1),
|
||||
(7, 'Бодега 100 SWA', 2, 10, '1990.00', 1),
|
||||
(8, 'Бодега 101 SWA', 2, 40, '2040.00', 1),
|
||||
(9, 'Бук Бавария 124 SWA', 2, 7, '1990.00', 1),
|
||||
(10, 'Бук Бавария 124 SWN', 3, 7, '2200.00', 1),
|
||||
(11, 'Ваниль 630 РЕ', 3, 30, '2140.00', 1),
|
||||
(12, 'Венге 175 SWA', 2, 3, '1990.00', 1),
|
||||
(13, 'Венге 175 SWN', 3, 3, '2200.00', 1),
|
||||
(14, 'Графит 665 РЕ', 3, 33, '2410.00', 1),
|
||||
(15, 'Дуб Атланта 302 SWA', 2, 39, '2040.00', 1),
|
||||
(16, 'Дуб Бонифаций 348 SWN', 3, 4, '2310.00', 1),
|
||||
(17, 'Дуб Веллингтон 370 SWN', 3, 23, '2310.00', 1),
|
||||
(18, 'Дуб Кантри 1007 Тиснение WL', 1, 25, '1560.00', 0),
|
||||
(19, 'Дуб Килкини 7225 Тиснение WL', 1, 21, '1850.00', 0),
|
||||
(20, 'Дуб молочный 315 SWA', 2, 41, '1990.00', 1),
|
||||
(21, 'Дуб Сантана 322 SWN', 3, 26, '2260.00', 1),
|
||||
(22, 'Дуб Саттер 369 SWN', 3, 5, '2260.00', 1),
|
||||
(23, 'Дуб Сонома 325 SWA', 2, 1, '1990.00', 1),
|
||||
(24, 'Дуб Сонома 325 SWN', 3, 1, '2210.00', 1),
|
||||
(25, 'Дуб Сонома 351 SWN', 3, 38, '2210.00', 1),
|
||||
(26, 'Дуб Шамони св.331 SWA', 2, 24, '2040.00', 1),
|
||||
(27, 'Дуб Юккон 358 SWN', 3, 14, '2360.00', 1),
|
||||
(28, 'Желтый 650 РЕ', 3, 32, '2720.00', 1),
|
||||
(29, 'Зелёный 651 РЕ', 3, 28, '2720.00', 1),
|
||||
(30, 'Капучино 806 PE', 3, 12, '2280.00', 1),
|
||||
(31, 'Клен Танзау 482 SWA', 2, 16, '1990.00', 1),
|
||||
(32, 'Крем 625 PE', 2, 2, '2050.00', 1),
|
||||
(33, 'Лиственница Сибирская 525 SWN', 3, 10, '2310.00', 1),
|
||||
(34, 'Ноче Гуарнери 408 SWA', 2, 5, '1990.00', 1),
|
||||
(35, 'Ноче Экко 412 SWA', 2, 8, '1990.00', 1),
|
||||
(36, 'Ольха 250 SWA', 2, 6, '2040.00', 1),
|
||||
(37, 'Ольха Горная светлая 254 SWN', 3, 9, '2260.00', 1),
|
||||
(38, 'Оранжевый 655 PE', 3, 35, '2720.00', 1),
|
||||
(39, 'Орех Донской 202 SWA', 2, 19, '1990.00', 1),
|
||||
(40, 'Орех Лион 204 SWN', 3, 27, '2210.00', 1),
|
||||
(41, 'Пепел 621 PE', 2, 34, '1940.00', 1),
|
||||
(42, 'Платина 801 PE', 3, 11, '2280.00', 1),
|
||||
(43, 'Розовый 657 PE', 2, 22, '2165.00', 1),
|
||||
(44, 'Серебро 802 PE', 3, 11, '2280.00', 1),
|
||||
(45, 'Синий 652 PE', 3, 29, '2280.00', 1),
|
||||
(46, 'Сиреневый 658 РЕ', 3, 37, '2410.00', 1),
|
||||
(47, 'Сосна Каньон 529 SWN', 3, 10, '2360.00', 1),
|
||||
(48, 'Таксус 570 SWN', 3, 27, '2310.00', 1),
|
||||
(49, 'Черный 660 PE', 3, 31, '2280.00', 1),
|
||||
(50, 'Эбони индийский светлый 3132 Тиснение WL', 1, 17, '1550.00', 0),
|
||||
(51, 'Ясень Шимо 454 SWA светлый', 2, 24, '1990.00', 1),
|
||||
(52, 'Ясень Шимо 455 SWA темный', 2, 23, '1990.00', 1),
|
||||
(53, 'Ясень Рибейра 3130 Тиснение WL', 1, 20, '1600.00', 0);
|
||||
|
||||
DROP TABLE IF EXISTS `cut_sheet_dimensions`;
|
||||
CREATE TABLE `cut_sheet_dimensions` (
|
||||
`id` int(11) NOT NULL,
|
||||
`width` int(11) DEFAULT NULL,
|
||||
`height` int(11) NOT NULL,
|
||||
`thick` int(11) NOT NULL,
|
||||
`2dp_id` int(11) NOT NULL,
|
||||
`is_active` tinyint(1) NOT NULL DEFAULT '1'
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
||||
|
||||
INSERT INTO `cut_sheet_dimensions` (`id`, `width`, `height`, `thick`, `2dp_id`, `is_active`) VALUES
|
||||
(1, 2440, 1830, 16, 1, 0),
|
||||
(2, 2750, 1830, 16, 1, 1),
|
||||
(3, 2800, 2070, 16, 1, 1);
|
||||
|
||||
ALTER TABLE `cut_borders` ADD PRIMARY KEY (`id`), ADD KEY `label` (`label`);
|
||||
ALTER TABLE `cut_border_available_dimensions` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `cut_border_dimensions` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `cut_sheets` ADD PRIMARY KEY (`id`), ADD KEY `label` (`label`);
|
||||
ALTER TABLE `cut_sheet_dimensions` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `cut_borders` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42;
|
||||
ALTER TABLE `cut_border_available_dimensions` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=105;
|
||||
ALTER TABLE `cut_border_dimensions` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
|
||||
ALTER TABLE `cut_sheets` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=54;
|
||||
ALTER TABLE `cut_sheet_dimensions` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
|
||||
|
||||
DROP TABLE IF EXISTS `cut_orders`;
|
||||
CREATE TABLE `cut_orders` (
|
||||
`id` int(11) NOT NULL,
|
||||
`order_num` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
|
||||
`email` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
|
||||
`phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
|
||||
`comment` text COLLATE utf32_unicode_ci,
|
||||
`is_rotate_allowed` tinyint(1) NOT NULL DEFAULT '1',
|
||||
`sheet_data` text CHARACTER SET utf8,
|
||||
`details` text CHARACTER SET utf8 NOT NULL,
|
||||
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf32 COLLATE=utf32_unicode_ci;
|
||||
|
||||
ALTER TABLE `cut_orders` ADD PRIMARY KEY (`id`);
|
||||
ALTER TABLE `cut_orders` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
|
||||
|
||||
ALTER TABLE `cut_orders` ADD `order_type` ENUM('order','print') NOT NULL DEFAULT 'order' AFTER `id`, ADD `branch_id` INT NULL DEFAULT NULL AFTER `order_type`;
|
||||
|
||||
CREATE USER 'supersam_cut'@'%' IDENTIFIED WITH mysql_native_password AS 'Ft8wV%e3Fre#ZaH-nJS';GRANT USAGE ON *.* TO 'supersam_cut'@'%' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;GRANT ALL PRIVILEGES ON `supersam_cut`.* TO 'supersam_cut'@'%';
|
||||
|
||||
ALTER USER 'supersam_cut'@'%' IDENTIFIED BY 'Ft8wV%e3Fre#ZaH-nJ';
|
||||
|
||||
ALTER TABLE `orders` ADD `print_url` VARCHAR(255) NULL DEFAULT NULL AFTER `taken_date`;
|
||||
|
||||
ALTER TABLE `sheets` ADD `image` VARCHAR(100) NULL DEFAULT NULL AFTER `is_active`, ADD `thumb` VARCHAR(100) NULL DEFAULT NULL AFTER `image`;
|
||||
update borders set image = concat(id, '.jpg');
|
||||
update sheets set image = concat(id, '.jpg');
|
||||
update sheets set thumb = concat(id, '.jpg');
|
||||
|
||||
ALTER TABLE `users` ADD `email` VARCHAR(128) NOT NULL AFTER `name`;
|
||||
ALTER TABLE `orders` ADD `html_letter` TEXT NULL AFTER `print_url`;
|
||||
ALTER TABLE `orders` ADD `text_letter` TEXT NULL AFTER `html_letter`;
|
||||
|
||||
ALTER TABLE `orders` ADD `statistics` TEXT NULL DEFAULT NULL AFTER `text_letter`;
|
||||
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, NULL, 'notifySaveOrderDataMessage', 'Заказ был успешно сохранен.', 'labels');
|
||||
|
||||
ALTER TABLE `orders` ADD `price` DECIMAL(10,2) NOT NULL DEFAULT '0' AFTER `details`;
|
||||
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'Сообщение об ошибке по умолчанию', 'defaultErrorMessage', 'Произошла ошибка. Пожалуйста, проверьте данные, убедитесь, что вы авторизованы и повторите действие.', 'labels');
|
||||
|
||||
ALTER TABLE `orders` ADD `merge_similar_details` TINYINT(1) NOT NULL DEFAULT '1' AFTER `is_rotate_allowed`;
|
||||
|
||||
ALTER TABLE `branches` ADD `is_deleted` TINYINT(1) NOT NULL DEFAULT '0' AFTER `order_notify_manager_sms`;
|
||||
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'Сообщение об ошибке загрузки данных при построении раскроя', 'dataLoadingError', 'Произошла ошибка при загрузке данных. Пожалуйста, повторите позже.', 'labels');
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'Сообщение об ошибке при отправке заказа менеджеру', 'orderSendManagerError', 'Произошла ошибка при отправке вашего заказа менеджеру. Пожалуйста, повторите позже.', 'labels');
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'Сообщение об ошибке при сохранении заказа менеджером', 'orderSaveManagerError', 'Произошла ошибка при сохранении вашего заказа. Пожалуйста, повторите позже.', 'labels');
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'Сообщение о необходимости дождаться окончания расчета раскроя при попытке отправить заказ', 'orderSendManagerCutIsActive', 'Пожалуйста, дождитесь окончания расчета перед печатью заказа или отправкой менеджеру.', 'labels');
|
||||
|
||||
ALTER TABLE `orders` ADD `order_cut_results` TEXT NULL DEFAULT NULL AFTER `updated_by_manager`;
|
||||
|
||||
ALTER TABLE `orders` DROP `is_rotate_allowed`;
|
||||
ALTER TABLE `orders` ADD INDEX( `order_type`, `created`, `manager_id`);
|
||||
ALTER TABLE `orders` ADD INDEX( `order_type`, `branch_id`, `created`, `manager_id`);
|
||||
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'НА РАСПИЛ УКАЗЫВАЮТСЯ ГОТОВЫЕ РАЗМЕРЫ ДЕТАЛЕЙ С УЧЕТОМ КРОМКИ', 'detailWithBordersWarning', 'НА РАСПИЛ УКАЗЫВАЮТСЯ ГОТОВЫЕ РАЗМЕРЫ ДЕТАЛЕЙ С УЧЕТОМ КРОМКИ', 'labels');
|
||||
|
||||
-------------------------
|
||||
delete from cut_settings where `group` = 'updates' or `group` = 'users';
|
||||
delete from settings where `group` != 'updates' and `group` != 'users';
|
||||
ALTER TABLE `cut_settings` CHANGE `group` `group` ENUM('prices','borders','common','labels','sheets','sheetDimensions','borderDimensions','branches','groovePrices','cornerPrices','grooveDefaults','cornerDefaults') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
ALTER TABLE `settings` CHANGE `group` `group` ENUM('users','updates','cut_updates') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
|
||||
ALTER TABLE `users` ADD `available_apps` VARCHAR(256) NOT NULL AFTER `is_active`;
|
||||
UPDATE `users` SET `available_apps` = '[\"cut\",\"calcDoors\"]' WHERE 1;
|
||||
|
||||
ALTER TABLE `settings` CHANGE `group` `group` ENUM('users','updates','cut_updates','common') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
|
||||
ALTER TABLE `cut_orders` ADD `address` VARCHAR(256) NULL DEFAULT NULL AFTER `comment`;
|
||||
|
||||
ALTER TABLE `calc_doors_orders` ADD `ready_date` DATETIME NULL AFTER `order_calc_results`;
|
||||
ALTER TABLE `calc_doors_orders` ADD `actual_price` DECIMAL(15,2) NULL DEFAULT NULL AFTER `ready_date`;
|
||||
|
||||
ALTER TABLE `cut_orders` CHANGE `print_url` `view_order_url` VARCHAR(255) CHARACTER SET utf32 COLLATE utf32_unicode_ci NULL DEFAULT NULL;
|
||||
ALTER TABLE `calc_doors_orders` CHANGE `print_url` `view_order_url` VARCHAR(255) CHARACTER SET utf32 COLLATE utf32_unicode_ci NULL DEFAULT NULL;
|
||||
ALTER TABLE `users` ADD `last_active` DATETIME NULL DEFAULT NULL AFTER `available_apps`;
|
||||
ALTER TABLE `users` ADD `logging_attempts` INT NOT NULL DEFAULT '0' AFTER `last_active`;
|
||||
|
||||
ALTER TABLE `sms_subscribes` CHANGE `created_by` `createdBy` INT(11) NULL DEFAULT NULL;
|
||||
ALTER TABLE `sms_subscribes` CHANGE `queued_by` `queuedBy` INT(11) NULL DEFAULT NULL;
|
||||
ALTER TABLE `sms_subscribes` CHANGE `stopped_by` `stoppedBy` INT(11) NULL DEFAULT NULL;
|
||||
|
||||
ALTER TABLE `cut_orders` ADD INDEX( `order_type`, `name`, `created`);
|
||||
|
||||
-- 2019-09-18
|
||||
ALTER TABLE `calc_doors_orders` ADD `price` DECIMAL(15,2) NULL DEFAULT NULL AFTER `ready_date`;
|
||||
ALTER TABLE `cut_orders` ADD `price` DECIMAL(15,2) NULL DEFAULT NULL AFTER `order_cut_results`;
|
||||
ALTER TABLE `calc_doors_orders` ADD INDEX( `order_type`, `name`, `created`);
|
||||
|
||||
-- 2091-09-27
|
||||
ALTER TABLE `sms_subscribe_recipients` CHANGE `smsSubscribeId` `subscribeId` INT(11) NOT NULL;
|
||||
ALTER TABLE `sms_subscribes` CHANGE `sentSmsCount` `sentRecipientsCount` INT(11) NOT NULL DEFAULT '0';
|
||||
ALTER TABLE `sms_subscribes` CHANGE `sentRecipientsCount` `sentCount` INT(11) NOT NULL DEFAULT '0';
|
||||
ALTER TABLE `email_subscribe_attachments` ADD `mime` VARCHAR(64) NULL AFTER `filesize`;
|
||||
|
||||
|
||||
|
||||
-- 2010-01-21
|
||||
ALTER TABLE `users` CHANGE `role` `role` ENUM('admin','manager','head_of_transport','head_of_warehouse') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'manager';
|
||||
|
||||
-- 2010-01-30
|
||||
ALTER TABLE `cut_sheets` ADD `sheetIdFor1C` VARCHAR(36) NULL DEFAULT NULL AFTER `thumb`;
|
||||
ALTER TABLE `cut_sheets` ADD `quantityIn1C` INT NOT NULL DEFAULT '0' AFTER `sheetIdFor1C`
|
||||
|
||||
ALTER TABLE `cut_sheets` CHANGE `quantityIn1C` `quantityIn1C` INT(11) NULL DEFAULT NULL;
|
||||
UPDATE `cut_sheets` SET `quantityIn1C` = NULL WHERE 1;
|
||||
|
||||
ALTER TABLE `sms_orders_ready` CHANGE `sentDate` `sentDate` DATETIME NULL DEFAULT NULL;
|
||||
|
||||
|
||||
-- 2010-04-06
|
||||
ALTER TABLE `calc_doors` ADD `colorNapravlyaushayaVerh` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `color`,
|
||||
ADD `colorNapravlyaushayaNiz` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL AFTER `colorNapravlyaushayaVerh`;
|
||||
update calc_doors set colorNapravlyaushayaVerh = color, colorNapravlyaushayaNiz = color where 1;
|
||||
|
||||
ALTER TABLE `calc_doors_settings` CHANGE `group` `group` ENUM('prices','common','labels','prices_aristo', 'limits_aristo') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
INSERT INTO `calc_doors_settings` (`label`, `key`, `value`, `group`) VALUES
|
||||
('Минимальная высота проёма, мм', 'minDoorHeight', '740', 'limits_aristo'),
|
||||
('Максимальная высота проёма, мм', 'maxDoorHeight', '2700', 'limits_aristo'),
|
||||
('Минимальная ширина двери, мм', 'minDoorWidth', '450', 'limits_aristo'),
|
||||
('Максимальная ширина двери, мм', 'maxDoorWidth', '900', 'limits_aristo');
|
||||
|
||||
ALTER TABLE `settings` CHANGE `group` `group` ENUM('users','updates','cut_updates','global','common','global_labels','calcDoors_updates','ordersInfo_updates') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
|
||||
|
||||
ALTER TABLE `settings` CHANGE `group` `group` ENUM('users','updates','cut_updates','global','common','global_labels','calcDoors_updates','ordersInfo_updates','order_payment') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
|
||||
|
||||
INSERT INTO `settings` (`id`, `label`, `key`, `value`, `group`) VALUES (NULL, 'API ключ яндекс карт', 'yandexMapApiKey', '96000e94-bf7a-4e74-9180-068e83944d02', 'global');
|
||||
ALTER TABLE `delivery` ADD `shopShippingId` VARCHAR(32) NULL DEFAULT NULL AFTER `minimalCost`;
|
||||
UPDATE `delivery` SET `shopShippingId` = 'carrier_yalta' WHERE `delivery`.`id` = 7;
|
||||
UPDATE `delivery` SET `shopShippingId` = 'carrier_sev' WHERE `delivery`.`id` = 6;
|
||||
|
||||
ALTER TABLE `delivery` ADD `shopOrderMinTotal` DECIMAL(10,2) NULL DEFAULT NULL AFTER `shopShippingId`;
|
||||
UPDATE `delivery` SET `shopOrderMinTotal` = 500 WHERE `delivery`.`id` = 7;
|
||||
UPDATE `delivery` SET `shopOrderMinTotal` = 500 WHERE `delivery`.`id` = 6;
|
||||
|
||||
-- SELECT * FROM `oc_setting` WHERE `code` = 'carrier_sev' or `code` = 'carrier_yalta'
|
||||
|
||||
ALTER TABLE `sms_orders_ready` ADD `smsType` ENUM('order','other') NOT NULL AFTER `statusTime`;
|
||||
UPDATE `sms_orders_ready` SET `smsType` = 'order' WHERE 1;
|
||||
ALTER TABLE `sms_orders_ready` CHANGE `smsType` `smsType` ENUM('order','other','apps_order','supersam24_order') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
|
||||
ALTER TABLE `order_payment` ADD `name` VARCHAR(256) NULL DEFAULT NULL AFTER `order_num`, ADD `summa_order_decimal` DECIMAL(10,2) NULL DEFAULT NULL AFTER `name`;
|
||||
|
||||
|
||||
ALTER TABLE `order_payment` ADD `summa_order_decimal_paid` DECIMAL(10,2) NOT NULL DEFAULT '0' AFTER `payment`;
|
||||
ALTER TABLE `order_payment` ADD `isDeleted` TINYINT(1) NOT NULL DEFAULT '0' AFTER `expiry_date`;
|
||||
ALTER TABLE `orders_info` ADD `created` DATETIME NULL DEFAULT NULL AFTER `isDeleted`;
|
||||
|
||||
|
||||
|
||||
ALTER TABLE `order_payment` ADD `telephone` VARCHAR(20) NULL DEFAULT NULL AFTER `name`;
|
||||
ALTER TABLE `order_payment` ADD `paid_date` DATETIME NULL DEFAULT NULL AFTER `expiry_date`;
|
||||
|
||||
|
||||
|
||||
ALTER TABLE `order_payment` ADD `domain` ENUM('apps.supersamsev.ru','supersam24.ru') NOT NULL DEFAULT 'apps.supersamsev.ru' AFTER `isDeleted`;
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';
|
||||
Generated
+3031
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit
|
||||
colors="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
syntaxCheck="false"
|
||||
bootstrap="./tests/bootstrap.php"
|
||||
>
|
||||
<php>
|
||||
<ini name="memory_limit" value="-1"/>
|
||||
<ini name="apc.enable_cli" value="1"/>
|
||||
</php>
|
||||
|
||||
<!-- Add any additional test suites you want to run here -->
|
||||
<testsuites>
|
||||
<testsuite name="app">
|
||||
<directory>./tests/TestCase</directory>
|
||||
</testsuite>
|
||||
<!-- Add plugin test suites here. -->
|
||||
</testsuites>
|
||||
|
||||
<!-- Setup a listener for fixtures -->
|
||||
<listeners>
|
||||
<listener
|
||||
class="\Cake\TestSuite\Fixture\FixtureInjector"
|
||||
file="./vendor/cakephp/cakephp/src/TestSuite/Fixture/FixtureInjector.php">
|
||||
<arguments>
|
||||
<object class="\Cake\TestSuite\Fixture\FixtureManager" />
|
||||
</arguments>
|
||||
</listener>
|
||||
</listeners>
|
||||
|
||||
<!-- Ignore vendor tests in code coverage reports -->
|
||||
<filter>
|
||||
<whitelist>
|
||||
<directory suffix=".php">./src/</directory>
|
||||
<directory suffix=".php">./plugins/*/src/</directory>
|
||||
</whitelist>
|
||||
</filter>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.3.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Error\Middleware\ErrorHandlerMiddleware;
|
||||
use Cake\Http\BaseApplication;
|
||||
use Cake\Routing\Middleware\AssetMiddleware;
|
||||
use Cake\Routing\Middleware\RoutingMiddleware;
|
||||
|
||||
/**
|
||||
* Application setup class.
|
||||
*
|
||||
* This defines the bootstrapping logic and middleware layers you
|
||||
* want to use in your application.
|
||||
*/
|
||||
class Application extends BaseApplication
|
||||
{
|
||||
/**
|
||||
* Setup the middleware queue your application will use.
|
||||
*
|
||||
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
|
||||
* @return \Cake\Http\MiddlewareQueue The updated middleware queue.
|
||||
*/
|
||||
public function middleware($middlewareQueue)
|
||||
{
|
||||
$middlewareQueue
|
||||
// Catch any exceptions in the lower layers,
|
||||
// and make an error page/response
|
||||
->add(ErrorHandlerMiddleware::class)
|
||||
|
||||
// Handle plugin/theme assets like CakePHP normally does.
|
||||
->add(AssetMiddleware::class)
|
||||
|
||||
// Add routing middleware.
|
||||
->add(new RoutingMiddleware($this));
|
||||
|
||||
return $middlewareQueue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\Console;
|
||||
|
||||
if (!defined('STDIN')) {
|
||||
define('STDIN', fopen('php://stdin', 'r'));
|
||||
}
|
||||
|
||||
use Cake\Utility\Security;
|
||||
use Composer\Script\Event;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Provides installation hooks for when this application is installed via
|
||||
* composer. Customize this class to suit your needs.
|
||||
*/
|
||||
class Installer
|
||||
{
|
||||
|
||||
/**
|
||||
* An array of directories to be made writable
|
||||
*/
|
||||
const WRITABLE_DIRS = [
|
||||
'logs',
|
||||
'tmp',
|
||||
'tmp/cache',
|
||||
'tmp/cache/models',
|
||||
'tmp/cache/persistent',
|
||||
'tmp/cache/views',
|
||||
'tmp/sessions',
|
||||
'tmp/tests'
|
||||
];
|
||||
|
||||
/**
|
||||
* Does some routine installation tasks so people don't have to.
|
||||
*
|
||||
* @param \Composer\Script\Event $event The composer event object.
|
||||
* @throws \Exception Exception raised by validator.
|
||||
* @return void
|
||||
*/
|
||||
public static function postInstall(Event $event)
|
||||
{
|
||||
$io = $event->getIO();
|
||||
|
||||
$rootDir = dirname(dirname(__DIR__));
|
||||
|
||||
static::createAppConfig($rootDir, $io);
|
||||
static::createWritableDirectories($rootDir, $io);
|
||||
|
||||
// ask if the permissions should be changed
|
||||
if ($io->isInteractive()) {
|
||||
$validator = function ($arg) {
|
||||
if (in_array($arg, ['Y', 'y', 'N', 'n'])) {
|
||||
return $arg;
|
||||
}
|
||||
throw new Exception('This is not a valid answer. Please choose Y or n.');
|
||||
};
|
||||
$setFolderPermissions = $io->askAndValidate(
|
||||
'<info>Set Folder Permissions ? (Default to Y)</info> [<comment>Y,n</comment>]? ',
|
||||
$validator,
|
||||
10,
|
||||
'Y'
|
||||
);
|
||||
|
||||
if (in_array($setFolderPermissions, ['Y', 'y'])) {
|
||||
static::setFolderPermissions($rootDir, $io);
|
||||
}
|
||||
} else {
|
||||
static::setFolderPermissions($rootDir, $io);
|
||||
}
|
||||
|
||||
static::setSecuritySalt($rootDir, $io);
|
||||
|
||||
if (class_exists('\Cake\Codeception\Console\Installer')) {
|
||||
\Cake\Codeception\Console\Installer::customizeCodeceptionBinary($event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the config/app.php file if it does not exist.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function createAppConfig($dir, $io)
|
||||
{
|
||||
$appConfig = $dir . '/config/app.php';
|
||||
$defaultConfig = $dir . '/config/app.default.php';
|
||||
if (!file_exists($appConfig)) {
|
||||
copy($defaultConfig, $appConfig);
|
||||
$io->write('Created `config/app.php` file');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the `logs` and `tmp` directories.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function createWritableDirectories($dir, $io)
|
||||
{
|
||||
foreach (static::WRITABLE_DIRS as $path) {
|
||||
$path = $dir . '/' . $path;
|
||||
if (!file_exists($path)) {
|
||||
mkdir($path);
|
||||
$io->write('Created `' . $path . '` directory');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set globally writable permissions on the "tmp" and "logs" directory.
|
||||
*
|
||||
* This is not the most secure default, but it gets people up and running quickly.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function setFolderPermissions($dir, $io)
|
||||
{
|
||||
// Change the permissions on a path and output the results.
|
||||
$changePerms = function ($path, $perms, $io) {
|
||||
// Get permission bits from stat(2) result.
|
||||
$currentPerms = fileperms($path) & 0777;
|
||||
if (($currentPerms & $perms) == $perms) {
|
||||
return;
|
||||
}
|
||||
|
||||
$res = chmod($path, $currentPerms | $perms);
|
||||
if ($res) {
|
||||
$io->write('Permissions set on ' . $path);
|
||||
} else {
|
||||
$io->write('Failed to set permissions on ' . $path);
|
||||
}
|
||||
};
|
||||
|
||||
$walker = function ($dir, $perms, $io) use (&$walker, $changePerms) {
|
||||
$files = array_diff(scandir($dir), ['.', '..']);
|
||||
foreach ($files as $file) {
|
||||
$path = $dir . '/' . $file;
|
||||
|
||||
if (!is_dir($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$changePerms($path, $perms, $io);
|
||||
$walker($path, $perms, $io);
|
||||
}
|
||||
};
|
||||
|
||||
$worldWritable = bindec('0000000111');
|
||||
$walker($dir . '/tmp', $worldWritable, $io);
|
||||
$changePerms($dir . '/tmp', $worldWritable, $io);
|
||||
$changePerms($dir . '/logs', $worldWritable, $io);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the security.salt value in the application's config file.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function setSecuritySalt($dir, $io)
|
||||
{
|
||||
$newKey = hash('sha256', Security::randomBytes(64));
|
||||
static::setSecuritySaltInFile($dir, $io, $newKey, 'app.php');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the security.salt value in a given file
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @param string $newKey key to set in the file
|
||||
* @param string $file A path to a file relative to the application's root
|
||||
* @return void
|
||||
*/
|
||||
public static function setSecuritySaltInFile($dir, $io, $newKey, $file)
|
||||
{
|
||||
$config = $dir . '/config/' . $file;
|
||||
$content = file_get_contents($config);
|
||||
|
||||
$content = str_replace('__SALT__', $newKey, $content, $count);
|
||||
|
||||
if ($count == 0) {
|
||||
$io->write('No Security.salt placeholder to replace.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = file_put_contents($config, $content);
|
||||
if ($result) {
|
||||
$io->write('Updated Security.salt value in config/' . $file);
|
||||
|
||||
return;
|
||||
}
|
||||
$io->write('Unable to update Security.salt value.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the APP_NAME value in a given file
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @param string $appName app name to set in the file
|
||||
* @param string $file A path to a file relative to the application's root
|
||||
* @return void
|
||||
*/
|
||||
public static function setAppNameInFile($dir, $io, $appName, $file)
|
||||
{
|
||||
$config = $dir . '/config/' . $file;
|
||||
$content = file_get_contents($config);
|
||||
$content = str_replace('__APP_NAME__', $appName, $content, $count);
|
||||
|
||||
if ($count == 0) {
|
||||
$io->write('No __APP_NAME__ placeholder to replace.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = file_put_contents($config, $content);
|
||||
if ($result) {
|
||||
$io->write('Updated __APP_NAME__ value in config/' . $file);
|
||||
|
||||
return;
|
||||
}
|
||||
$io->write('Unable to update __APP_NAME__ value.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\Controller\Controller;
|
||||
use Cake\ORM\TableRegistry;
|
||||
use Cake\Http\Exception\NotFoundException;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Routing\Router;
|
||||
use BrowserDetection;
|
||||
use Cake\Utility\Hash;
|
||||
|
||||
class AppController extends Controller
|
||||
{
|
||||
public $config = null;
|
||||
|
||||
public function initialize() {
|
||||
parent::initialize();
|
||||
|
||||
$this->loadComponent('RequestHandler', [
|
||||
'enableBeforeRedirect' => false
|
||||
]);
|
||||
|
||||
$this->loadComponent('Flash');
|
||||
|
||||
}
|
||||
|
||||
public function beforeFilter(Event $event) {
|
||||
parent::beforeFilter($event);
|
||||
|
||||
$browser = new BrowserDetection();
|
||||
if (($browser->getName() == BrowserDetection::BROWSER_IE &&
|
||||
$browser->compareVersions($browser->getVersion(), '11.0') < 0) ||
|
||||
|
||||
($browser->getName() == BrowserDetection::BROWSER_OPERA &&
|
||||
$browser->compareVersions($browser->getVersion(), '20.0') < 0) ||
|
||||
|
||||
($browser->getName() == BrowserDetection::BROWSER_CHROME &&
|
||||
$browser->compareVersions($browser->getVersion(), '40.0') < 0) ||
|
||||
|
||||
($browser->getName() == BrowserDetection::BROWSER_FIREFOX &&
|
||||
$browser->compareVersions($browser->getVersion(), '50.0') < 0)
|
||||
){
|
||||
$this->set("isRejectedBrowser", true);
|
||||
}
|
||||
|
||||
$request = Router::getRequest();
|
||||
$controller = $request->getParam('controller');
|
||||
|
||||
if (in_array($controller, ["OrderPayment"])) {
|
||||
$currentApp = "orderPayment";
|
||||
}
|
||||
|
||||
$this->config = $this->getAppConfig($currentApp);
|
||||
$this->set('siteTitle', $this->config['common']['siteTitle']['value']);
|
||||
}
|
||||
|
||||
public function jsonSimpleResponse($result, $withCORS = false) {
|
||||
if ($withCORS) {
|
||||
$this->response->setHeader('Access-Control-Allow-Origin: *');
|
||||
}
|
||||
|
||||
$this->set(compact('result'));
|
||||
$this->RequestHandler->renderAs($this, 'json');
|
||||
$this->render('/Element/json_result');
|
||||
}
|
||||
|
||||
public function getAppConfig($app) {
|
||||
$config = [];
|
||||
|
||||
$settings = TableRegistry::getTableLocator()->get('Settings')->find('all')->toArray();
|
||||
foreach ($settings as $s) {
|
||||
if (!isset($config[$s['group']])) {
|
||||
$config[$s['group']] = [];
|
||||
}
|
||||
|
||||
if (in_array($s['key'], ["smtpParams"])) {
|
||||
$s['value'] = @json_decode($s['value'], true);
|
||||
}
|
||||
|
||||
$config[$s['group']][$s['key']] = [
|
||||
"id" => $s['key'],
|
||||
"label" => $s['label'],
|
||||
"value" => $s['value']
|
||||
];
|
||||
};
|
||||
|
||||
|
||||
$config["encrypt"] = Configure::read("encrypt");
|
||||
|
||||
$tmpDelivery = $this->getDeliveryListForJS();
|
||||
$config['delivery'] = [];
|
||||
foreach ($tmpDelivery as $delivery) {
|
||||
$config['delivery'][$delivery['id']] = $delivery->toArray();
|
||||
}
|
||||
|
||||
$config["appsList"] = [
|
||||
"cut" => [
|
||||
"id" => "cut",
|
||||
"label" => "Раскрой ДСП",
|
||||
"label_long" => "Раскрой ДСП",
|
||||
"site_label" => "Online распил ДСП",
|
||||
"url" => "cut",
|
||||
],
|
||||
"fasad" => [
|
||||
"id" => "fasad",
|
||||
"label" => "Распил фасадов",
|
||||
"label_long" => "Распил фасадов",
|
||||
"site_label" => "Online распил фасадов",
|
||||
"url" => "fasad",
|
||||
],
|
||||
/*"calcDoors" => [
|
||||
"id" => "calcDoors",
|
||||
"label" => "Двери",
|
||||
"label_long" => "Расчет стоимости изготовления дверей",
|
||||
"url" => "calc-doors",
|
||||
],*/
|
||||
"ordersInfo" => [
|
||||
"id" => "ordersInfo",
|
||||
"label" => "Информация по счетам",
|
||||
"label_long" => "Информация по счетам",
|
||||
"url" => "orders-info",
|
||||
],
|
||||
|
||||
];
|
||||
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
public function getAppJsConfig($app = "", $isManager = false, $savedOrderData = null, $orderClientId = null) {
|
||||
//$conditions = [];
|
||||
$jsConfig = [
|
||||
"urls" => [],
|
||||
"primarySiteUrl" => "https://supersam24.ru/",
|
||||
"siteDomain" => (!empty(env('HTTP_CUSTOMHOST')) ? str_replace('apps.', '', env('HTTP_CUSTOMHOST')) : "supersam24.ru"),
|
||||
"primarySiteTitle" => "СуперСам – Центр мебельных технологий",
|
||||
"branches" => [],
|
||||
"delivery" => [],
|
||||
"global_labels" => $this->config["global_labels"],
|
||||
];
|
||||
|
||||
//$conditions = ['is_active' => true];
|
||||
|
||||
$jsConfig = array_merge($jsConfig, [
|
||||
"version" => Configure::read('Release')
|
||||
]);
|
||||
|
||||
$jsConfig = array_merge($jsConfig, [
|
||||
"common" => $this->config["common"],
|
||||
"global" => $this->config["global"],
|
||||
]);
|
||||
|
||||
|
||||
if ($app == "orderPayment") {
|
||||
$jsConfig = array_merge($jsConfig, [
|
||||
"getPaymentStatusUrl" => Router::url(['controller' => 'OrderPayment', 'action' => 'get_payment_status', 'prefix' => false]),
|
||||
"orderPayment" => (isset($this->config["order_payment"]) ? $this->config["order_payment"] : []),
|
||||
]);
|
||||
}
|
||||
|
||||
$request = Router::getRequest();
|
||||
$jsConfig["appsList"] = $this->config["appsList"];
|
||||
|
||||
foreach ($this->config["delivery"] as $cfgKey => $cfgDelivery) {
|
||||
if (empty($cfgDelivery["is_deleted"])) {
|
||||
$jsConfig["delivery"][] = array_merge(['id' => $cfgKey], $cfgDelivery);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($savedOrderData)) {
|
||||
$jsConfig['savedOrderData'] = $savedOrderData;
|
||||
}
|
||||
|
||||
return $jsConfig;
|
||||
}
|
||||
|
||||
public function patchTimestampForJS($date, $delta = 1, $returnDateString = true, $format = 'd-m-Y H:i') {
|
||||
$date = new \DateTime($date);
|
||||
date_sub($date, date_interval_create_from_date_string($delta . ' hour'));
|
||||
|
||||
if ($returnDateString) {
|
||||
return $date->format($format);
|
||||
} else {
|
||||
return $date;
|
||||
}
|
||||
}
|
||||
|
||||
public function getDeliveryListForJS() {
|
||||
return TableRegistry::getTableLocator()->get('Delivery')->find('all')->order(['Delivery.label' => 'ASC'])->all()->toArray();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
namespace App\Controller;
|
||||
|
||||
use Cake\Event\Event;
|
||||
use Cake\ORM\TableRegistry;
|
||||
|
||||
class DeliveryController extends AppController {
|
||||
public function beforeFilter(Event $event)
|
||||
{
|
||||
parent::beforeFilter($event);
|
||||
// $this->Auth->allow(['display']);
|
||||
$this->viewBuilder()->setLayout('delivery');
|
||||
}
|
||||
|
||||
|
||||
public function display($city = null) {
|
||||
$isCityFound = false;
|
||||
if (!empty($city)) {
|
||||
$deliveryTable = TableRegistry::getTableLocator()->get('Delivery');
|
||||
|
||||
$delivery = $deliveryTable->find('all')->where(['slug' => $city, 'is_deleted' => false])->first();
|
||||
if (!empty($delivery)) {
|
||||
$delivery = $delivery->toArray();
|
||||
|
||||
$this->set('apiKey', $this->config['global']['yandexMapApiKey']['value']);
|
||||
$this->set('siteTitle', $delivery['label']);
|
||||
$this->set('delivery', $delivery);
|
||||
$isCityFound = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($isCityFound)) {
|
||||
$this->redirect('/404');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
namespace App\Controller;
|
||||
|
||||
use Cake\Event\Event;
|
||||
|
||||
class ErrorController extends AppController {
|
||||
|
||||
public $config = null;
|
||||
|
||||
public function initialize() {
|
||||
$this->loadComponent('RequestHandler');
|
||||
}
|
||||
|
||||
public function beforeFilter(Event $event) {
|
||||
}
|
||||
|
||||
public function beforeRender(Event $event) {
|
||||
parent::beforeRender($event);
|
||||
|
||||
$this->viewBuilder()->setTemplatePath('Error');
|
||||
$this->config = $this->getAppConfig("");
|
||||
$this->set('jsConfig', $this->getAppJsConfig("", false));
|
||||
}
|
||||
|
||||
public function afterFilter(Event $event) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
namespace App\Controller;
|
||||
|
||||
class OrderPaymentController extends AppController {
|
||||
public function display() {
|
||||
$this->redirect('https://apps.supersamsev.ru/services');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
namespace App\Model\Entity;
|
||||
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
use Cake\Auth\DefaultPasswordHasher;
|
||||
|
||||
class User extends Entity {
|
||||
|
||||
protected $_accessible = [
|
||||
'*' => true,
|
||||
'id' => false
|
||||
];
|
||||
|
||||
protected function _setPassword($password) {
|
||||
return (new DefaultPasswordHasher)->hash($password);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
<div id="result"></div>
|
||||
<div id="map"></div>
|
||||
|
||||
<a tabindex="-1" href="/services" title="{{::config.primarySiteTitle}}" target="_blank" class="delivery-logo-row">
|
||||
<img class="apps-logo" src="/img/logo-<?=$jsConfig['siteDomain'];?>.png" alt="{{::config.primarySiteTitle}}">
|
||||
</a>
|
||||
|
||||
<script type="text/javascript">
|
||||
function resultsClose() {
|
||||
$('#result').removeClass('active');
|
||||
}
|
||||
|
||||
function init() {
|
||||
var myMap = new ymaps.Map('map', {
|
||||
center: [<?=$delivery['location'];?>],
|
||||
zoom: 17,
|
||||
type: 'yandex#map',
|
||||
controls: []
|
||||
}),
|
||||
|
||||
searchFinishPoint = new ymaps.control.SearchControl({
|
||||
options: {
|
||||
useMapBounds: true,
|
||||
noCentering: true,
|
||||
noPopup: true,
|
||||
noPlacemark: true,
|
||||
placeholderContent: 'Адрес доставки',
|
||||
size: 'large',
|
||||
float: 'none',
|
||||
position: { left: 10, top: 44 }
|
||||
}
|
||||
}),
|
||||
|
||||
|
||||
calculator = new DeliveryCalculator(myMap, myMap.getCenter()) ;
|
||||
|
||||
searchFinishPoint.events.add('load', function (event) { $('#result').removeClass('active'); });
|
||||
searchFinishPoint.events.add('clear', function (event) { $('#result').removeClass('active'); });
|
||||
searchFinishPoint.events.add('submit', function (event) { $('#result').removeClass('active'); });
|
||||
|
||||
|
||||
myMap.controls.add(searchFinishPoint);
|
||||
calculator.setStartPoint([<?=$delivery['location'];?>]);
|
||||
|
||||
searchFinishPoint.events.add('resultselect', function (e) {
|
||||
var results = searchFinishPoint.getResultsArray(),
|
||||
selected = e.get('index'),
|
||||
point = results[selected].geometry.getCoordinates();
|
||||
|
||||
calculator.setFinishPoint(point);
|
||||
})
|
||||
.add('load', function (event) {
|
||||
if (!event.get('skip') && searchFinishPoint.getResultsCount()) {
|
||||
searchFinishPoint.showResult(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function DeliveryCalculator(map, finish) {
|
||||
this._map = map;
|
||||
this._start = null;
|
||||
this._route = null;
|
||||
this._startBalloon;
|
||||
this._finishBalloon;
|
||||
|
||||
map.events.add('click', this._onClick, this);
|
||||
}
|
||||
|
||||
var ptp = DeliveryCalculator.prototype;
|
||||
|
||||
ptp._onClick= function (e) {
|
||||
if (this._start) {
|
||||
this.setFinishPoint(e.get('coords'));
|
||||
} else {
|
||||
this.setStartPoint(e.get('coords'));
|
||||
}
|
||||
};
|
||||
|
||||
ptp._onStartDragEnd = function (e) {
|
||||
var coords = this._start.geometry.getCoordinates();
|
||||
this.geocode("start", coords);
|
||||
};
|
||||
|
||||
ptp._onFinishDragEnd = function (e) {
|
||||
var coords = this._finish.geometry.getCoordinates();
|
||||
this.geocode("finish", coords);
|
||||
};
|
||||
|
||||
ptp.getDirection = function () {
|
||||
if(this._route) {
|
||||
this._map.geoObjects.remove(this._route);
|
||||
}
|
||||
|
||||
if (this._start && this._finish) {
|
||||
var self = this,
|
||||
start = this._start.geometry.getCoordinates(),
|
||||
finish = this._finish.geometry.getCoordinates(),
|
||||
startBalloon = this._startBalloon,
|
||||
finishBalloon = this._finishBalloon;
|
||||
|
||||
ymaps.route([
|
||||
finish,
|
||||
start,
|
||||
], {multiRoute: true})
|
||||
.then(function (router) {
|
||||
//self._map.geoObjects.add(router);
|
||||
|
||||
var routes = router.getRoutes(), distanceWithTolls = 0, distanceWithoutTolls = 0, distance = 0,
|
||||
selectedRoute, selectedRouteWithTolls, selectedRouteWithoutTolls;
|
||||
for (var i = 0, l = routes.getLength(); i < l; i++) {
|
||||
var route = routes.get(i);
|
||||
|
||||
if (!route.properties.get('blocked')) {
|
||||
distance = Math.ceil(route.properties.get('distance').value / 1000)
|
||||
if (route.properties.get('hasTolls')) {
|
||||
if ((distanceWithTolls == 0) || (distance < distanceWithTolls)) {
|
||||
selectedRouteWithTolls = route;
|
||||
distanceWithTolls = distance;
|
||||
}
|
||||
} else {
|
||||
if ((distanceWithoutTolls == 0) || (distance < distanceWithoutTolls)) {
|
||||
selectedRouteWithoutTolls = route;
|
||||
distanceWithoutTolls = distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (distanceWithoutTolls > 0) { //route without tolls exists
|
||||
selectedRoute = selectedRouteWithoutTolls;
|
||||
distance = distanceWithoutTolls;
|
||||
} else {
|
||||
selectedRoute = selectedRouteWithTolls;
|
||||
distance = distanceWithTolls;
|
||||
}
|
||||
|
||||
|
||||
router.setActiveRoute(selectedRoute);
|
||||
|
||||
var /*distance = Math.round(router.getLength() / 1000),*/
|
||||
distanceLabel = "",
|
||||
message = '<div class="resultInner"><span>Расстояние: ' + (distance < 1 ? 1 : distance) + 'км.</span><br/>' +
|
||||
'<span style="font-weight: bold; font-style: italic; ">Стоимость доставки: %sр.</span><span id="resultsClose" onClick="javascript:resultsClose();">×</span><div>'
|
||||
distanceLabel = self.calculate(distance);
|
||||
self._route = selectedRoute.getPaths();
|
||||
self._route.options.set({ strokeWidth: 5, strokeColor: '0000ffff', opacity: 0.5 });
|
||||
self._map.geoObjects.add(self._route);
|
||||
self._start.properties.set('balloonContentBody', startBalloon + message.replace('%s', distanceLabel));
|
||||
self._finish.properties.set('balloonContentBody', finishBalloon + message.replace('%s', distanceLabel));
|
||||
$('#result').html(finishBalloon + message.replace('%s', distanceLabel)).addClass('active');
|
||||
});
|
||||
|
||||
self._map.setBounds(self._map.geoObjects.getBounds())
|
||||
}
|
||||
};
|
||||
|
||||
ptp.setStartPoint = function (position) {
|
||||
if(this._start) {
|
||||
this._start.geometry.setCoordinates(position);
|
||||
}
|
||||
else {
|
||||
this._start = new ymaps.Placemark(position, { iconContent: 'А', }, { draggable: false });
|
||||
this._start.events.add('dragend', this._onStartDragEnd, this);
|
||||
this._map.geoObjects.add(this._start);
|
||||
}
|
||||
this.geocode("start", position);
|
||||
};
|
||||
|
||||
ptp.setFinishPoint = function (position) {
|
||||
if(this._finish) {
|
||||
this._finish.geometry.setCoordinates(position);
|
||||
}
|
||||
else {
|
||||
this._finish = new ymaps.Placemark(position, { iconContent: 'Б' }, { draggable: true });
|
||||
this._finish.events.add('dragend', this._onFinishDragEnd, this);
|
||||
this._map.geoObjects.add(this._finish);
|
||||
}
|
||||
if (this._start) {
|
||||
this.geocode("finish", position);
|
||||
}
|
||||
};
|
||||
|
||||
ptp.geocode = function (str, point) {
|
||||
ymaps.geocode(point).then(function(geocode) {
|
||||
if (str == "start") {
|
||||
this._startBalloon = "<h3><?=$delivery['address'];?></h3><p>" + geocode.geoObjects.get(0).properties.get('description') + "</p>";
|
||||
this._start.properties.set('balloonContentBody', this._startBalloon);
|
||||
} else {
|
||||
this._finishBalloon = geocode.geoObjects.get(0) &&
|
||||
geocode.geoObjects.get(0).properties.get('balloonContentBody') || '';
|
||||
}
|
||||
this.getDirection();
|
||||
}, this);
|
||||
|
||||
}
|
||||
ptp.calculate = function (len) {
|
||||
// Константы.
|
||||
var DELIVERY_TARIF = <?=$delivery['costPerKm'];?>,
|
||||
MINIMUM_COST = <?=$delivery['minimalCost'];?>;
|
||||
if (len == 1) return (MINIMUM_COST);
|
||||
return Math.max((len - 1) * DELIVERY_TARIF + MINIMUM_COST, MINIMUM_COST);
|
||||
};
|
||||
|
||||
ymaps.ready(init);
|
||||
|
||||
</script>
|
||||
|
||||
<?php $this->Assign('title', $siteTitle);?>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
$class = 'message';
|
||||
if (!empty($params['class'])) {
|
||||
$class .= ' ' . $params['class'];
|
||||
}
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="<?= h($class) ?>" onclick="this.classList.add('hidden');"><?= $message ?></div>
|
||||
@@ -0,0 +1,4 @@
|
||||
<div class="alert alert-danger alert-dismissable">
|
||||
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
|
||||
<p><?= $message ?></p>
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="message success" onclick="this.classList.add('hidden')"><?= $message ?></div>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php use Cake\Core\Configure;?>
|
||||
|
||||
<script type="text/javascript">
|
||||
supersamApp.factory('config', function() {
|
||||
return <?php echo json_encode(isset($jsConfig) ? $jsConfig : []); ?>;
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,38 @@
|
||||
<script type="text/javascript">
|
||||
function getCookie(name) {
|
||||
var value = "; " + document.cookie;
|
||||
var parts = value.split("; " + name + "=");
|
||||
if (parts.length == 2) return parts.pop().split(";").shift();
|
||||
else return null;
|
||||
}
|
||||
|
||||
function setCookie(name,value,days) {
|
||||
var expires = "";
|
||||
if (days) {
|
||||
var date = new Date();
|
||||
date.setTime(date.getTime() + (days*24*60*60*1000));
|
||||
expires = "; expires=" + date.toUTCString();
|
||||
}
|
||||
document.cookie = name + "=" + (value || "") + expires + "; path=/";
|
||||
}
|
||||
|
||||
(function($, document) {
|
||||
$(document).ready(function () {
|
||||
var cookieConsent = getCookie("cookie_consent");
|
||||
if (cookieConsent == null) {
|
||||
$("<div class=\"cookie-consent-container-wrap\"><div class=\"cookie-consent-container\"></div>"+
|
||||
"<div class=\"cookie-consent-content\">"+
|
||||
"<div><span>Мы используем файлы cookie, чтобы обеспечить максимальное удобство пользователям. Продолжая использовать этот сайт, вы даете согласие на использование файлов cookies.</span> <a href=\"https://supersamsev.ru/cookie-policy\" class=\"cookie-consent-more\" target=\"_blank\">Подробнее</a></div>"+
|
||||
"<a class=\"cookie-consent-ok\">Согласен</a>"+
|
||||
"</div>"+
|
||||
"</div>").appendTo('body');
|
||||
|
||||
|
||||
$(".cookie-consent-ok").on('click', function () {
|
||||
setCookie('cookie_consent', true, 1095);
|
||||
$(".cookie-consent-container-wrap").css({'opacity': '0', 'visibility': 'hidden'});
|
||||
});
|
||||
}
|
||||
})
|
||||
})(jQuery, document);
|
||||
</script>
|
||||
@@ -0,0 +1,8 @@
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/img/favicon/favicon_32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/img/favicon/favicon_16.png">
|
||||
|
||||
<link rel="shortcut icon" type="image/png" href="/img/favicon/favicon_16.png" />
|
||||
<?php foreach(['57', '60', '76', '114', '120', '128', '144', '152', '167', '180', '192'] as $s) {
|
||||
echo '<link rel="apple-touch-icon-precomposed" sizes="' . $s . 'x' . $s . '" href="/img/favicon/apple-touch-icon-' . $s . '-precomposed.png" />' . "\n";
|
||||
} ?>
|
||||
<link rel="apple-touch-icon-precomposed" href="/img/favicon/apple-touch-icon-57-precomposed.png" />
|
||||
@@ -0,0 +1,2 @@
|
||||
<?php
|
||||
echo json_encode($result);
|
||||
@@ -0,0 +1,15 @@
|
||||
<div class="page-404">
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-12 text-center">
|
||||
<a href="<?=$jsConfig['primarySiteUrl'];?>" title="<?=$jsConfig['primarySiteTitle'];?>"><img class="apps-logo" src="/img/logo-<?=$jsConfig['siteDomain'];?>.png"></a><br/><br/>
|
||||
|
||||
<?= $this->element("services");?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,34 @@
|
||||
<div>
|
||||
<a href="https://supersam24.ru" class="services-link btn btn-primary">Магазин фурнитуры</a>
|
||||
<a href="https://supersamsev.ru" class="services-link btn btn-primary">Магазин ДСП</a>
|
||||
<a href="https://prometeysev.ru" class="services-link btn btn-primary">Все для кухни, ремонта и дома</a>
|
||||
|
||||
<div class="services-social-links">
|
||||
<a class="vk" href="https://vk.com/supersam_aristo" target="_blank">
|
||||
<img src="/img/social/vk-h.png">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<br/><br/></div>
|
||||
|
||||
<b>Также вы можете воспользоваться нашими сервисами:</b><br/>
|
||||
<div>
|
||||
<?php
|
||||
foreach ($jsConfig["appsList"] as $app) {
|
||||
if (!empty($app['url'])) {
|
||||
echo '<a href="' . $app['url'] . '" class="services-link btn btn-info">' . (!empty($app['site_label']) ? $app['site_label'] : $app['label_long']) . '</a>';
|
||||
}
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
<br/>
|
||||
|
||||
<div>
|
||||
<?php
|
||||
foreach ($jsConfig["delivery"] as $delivery) {
|
||||
if (empty($delivery['is_deleted'])) {
|
||||
echo '<a href="/delivery/' . $delivery['slug'] . '" class="services-link btn btn-info">' . $delivery['label404'] . '</a>';
|
||||
}
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
$content = explode("\n", $content);
|
||||
|
||||
foreach ($content as $line) :
|
||||
echo '<p> ' . $line . "</p>\n";
|
||||
endforeach;
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
echo $content;
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Error\Debugger;
|
||||
|
||||
$this->layout = 'error';
|
||||
|
||||
if (Configure::read('debug')) :
|
||||
$this->layout = 'dev_error';
|
||||
|
||||
$this->assign('title', $message);
|
||||
$this->assign('templateName', 'error400.ctp');
|
||||
|
||||
$this->start('file');
|
||||
?>
|
||||
<?php if (!empty($error->queryString)) : ?>
|
||||
<p class="notice">
|
||||
<strong>SQL Query: </strong>
|
||||
<?= h($error->queryString) ?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
<?php if (!empty($error->params)) : ?>
|
||||
<strong>SQL Query Params: </strong>
|
||||
<?php Debugger::dump($error->params) ?>
|
||||
<?php endif; ?>
|
||||
<?= $this->element('auto_table_warning') ?>
|
||||
<?php
|
||||
if (extension_loaded('xdebug')) :
|
||||
xdebug_print_function_stack();
|
||||
endif;
|
||||
|
||||
$this->end();
|
||||
endif;
|
||||
?>
|
||||
<?= $this->element("page404");?>
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Error\Debugger;
|
||||
|
||||
$this->layout = 'error';
|
||||
|
||||
if (Configure::read('debug')) :
|
||||
$this->layout = 'dev_error';
|
||||
|
||||
$this->assign('title', $message);
|
||||
$this->assign('templateName', 'error500.ctp');
|
||||
|
||||
$this->start('file');
|
||||
?>
|
||||
<?php if (!empty($error->queryString)) : ?>
|
||||
<p class="notice">
|
||||
<strong>SQL Query: </strong>
|
||||
<?= h($error->queryString) ?>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
<?php if (!empty($error->params)) : ?>
|
||||
<strong>SQL Query Params: </strong>
|
||||
<?php Debugger::dump($error->params) ?>
|
||||
<?php endif; ?>
|
||||
<?php if ($error instanceof Error) : ?>
|
||||
<strong>Error in: </strong>
|
||||
<?= sprintf('%s, line %s', str_replace(ROOT, 'ROOT', $error->getFile()), $error->getLine()) ?>
|
||||
<?php endif; ?>
|
||||
<?php
|
||||
echo $this->element('auto_table_warning');
|
||||
|
||||
if (extension_loaded('xdebug')) :
|
||||
xdebug_print_function_stack();
|
||||
endif;
|
||||
|
||||
$this->end();
|
||||
endif;
|
||||
?>
|
||||
<?= $this->element("page404");?>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
|
||||
<html>
|
||||
<head>
|
||||
<title><?= $this->fetch('title') ?></title>
|
||||
</head>
|
||||
<body>
|
||||
<?= $this->fetch('content') ?>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
echo $this->fetch('content');
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
echo $this->fetch('content');
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php use Cake\Core\Configure; ?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<?= $this->Html->charset() ?>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<title><?= $this->fetch('title');?></title>
|
||||
<?php echo $this->element("favicon"); ?>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
|
||||
<?php if (empty($isRejectedBrowser)) {
|
||||
$release = "?v".Configure::read('Release');
|
||||
|
||||
$cssList = [
|
||||
"delivery.css",
|
||||
];
|
||||
|
||||
foreach ($cssList as $key => $css) {
|
||||
$cssList[$key] = $css.$release;
|
||||
}
|
||||
echo $this->Html->css($cssList);
|
||||
} else {
|
||||
echo $this->Html->css('jquery.reject');
|
||||
} ?>
|
||||
|
||||
<?= $this->fetch('meta'); ?>
|
||||
<?= $this->fetch('css'); ?>
|
||||
<?= $this->fetch('script'); ?>
|
||||
|
||||
<base href="/">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php if (empty($isRejectedBrowser)) {
|
||||
$scripts = [
|
||||
"jquery.min.js",
|
||||
];
|
||||
|
||||
foreach ($scripts as $key => $script) {
|
||||
$scripts[$key] = $script.$release;
|
||||
}
|
||||
$scripts[] = "https://api-maps.yandex.ru/2.1/?apikey=".$apiKey."&lang=ru_RU";
|
||||
|
||||
echo $this->Html->script($scripts);
|
||||
|
||||
echo $this->fetch('content');
|
||||
echo $this->element('cookie_consent');
|
||||
} else {
|
||||
echo $this->Html->script("jquery-1.min.js");
|
||||
echo $this->Html->script("jquery.reject.js");
|
||||
echo $this->Html->script("jquery.reject-config.js");
|
||||
} ?>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php use Cake\Core\Configure; ?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<?= $this->Html->charset() ?>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<title>СуперСам :: 404</title>
|
||||
<?php echo $this->element("favicon"); ?>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
|
||||
<?php if (empty($isRejectedBrowser)) {
|
||||
$release = "?v".Configure::read('Release');
|
||||
|
||||
$cssList = [
|
||||
"bootstrap.min.css",
|
||||
"styles.css",
|
||||
];
|
||||
|
||||
foreach ($cssList as $key => $css) {
|
||||
$cssList[$key] = $css.$release;
|
||||
}
|
||||
echo $this->Html->css($cssList);
|
||||
} else {
|
||||
echo $this->Html->css('jquery.reject');
|
||||
} ?>
|
||||
|
||||
<?= $this->fetch('meta'); ?>
|
||||
<?= $this->fetch('css'); ?>
|
||||
<?= $this->fetch('script'); ?>
|
||||
|
||||
<base href="/">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php if (empty($isRejectedBrowser)) {
|
||||
$scripts = [
|
||||
"jquery.min.js",
|
||||
];
|
||||
|
||||
foreach ($scripts as $key => $script) {
|
||||
$scripts[$key] = $script.$release;
|
||||
}
|
||||
|
||||
echo $this->Html->script($scripts);
|
||||
echo $this->fetch('content');
|
||||
echo $this->element('cookie_consent');
|
||||
} else {
|
||||
echo $this->Html->script("jquery-1.min.js");
|
||||
echo $this->Html->script("jquery.reject.js");
|
||||
echo $this->Html->script("jquery.reject-config.js");
|
||||
} ?>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
if (!isset($channel)) :
|
||||
$channel = [];
|
||||
endif;
|
||||
if (!isset($channel['title'])) :
|
||||
$channel['title'] = $this->fetch('title');
|
||||
endif;
|
||||
|
||||
echo $this->Rss->document(
|
||||
$this->Rss->channel([], $channel, $this->fetch('content'))
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
<div class="services">
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-12 text-center">
|
||||
<a href="<?=$jsConfig['primarySiteUrl'];?>" title="<?=$jsConfig['primarySiteTitle'];?>"><img src="/img/logo.png"></a><br/><br/>
|
||||
|
||||
<?= $this->element("services");?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<?php $this->Assign('title', $siteTitle);?>
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.4
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\View;
|
||||
|
||||
use Cake\Event\EventManager;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* A view class that is used for AJAX responses.
|
||||
* Currently only switches the default layout and sets the response type -
|
||||
* which just maps to text/html by default.
|
||||
*/
|
||||
class AjaxView extends AppView
|
||||
{
|
||||
|
||||
/**
|
||||
* The name of the layout file to render the view inside of. The name
|
||||
* specified is the filename of the layout in /src/Template/Layout without
|
||||
* the .ctp extension.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $layout = 'ajax';
|
||||
|
||||
/**
|
||||
* Initialization hook method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
parent::initialize();
|
||||
|
||||
$this->response = $this->response->withType('ajax');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\View;
|
||||
|
||||
use Cake\View\View;
|
||||
|
||||
/**
|
||||
* Application View
|
||||
*
|
||||
* Your application’s default view class
|
||||
*
|
||||
* @link https://book.cakephp.org/3.0/en/views.html#the-app-view
|
||||
*/
|
||||
class AppView extends View
|
||||
{
|
||||
|
||||
/**
|
||||
* Initialization hook method.
|
||||
*
|
||||
* Use this method to add common initialization code like loading helpers.
|
||||
*
|
||||
* e.g. `$this->loadHelper('Html');`
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize()
|
||||
{
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
+1778
File diff suppressed because it is too large.
Load diff
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2005-present, Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
|
||||
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.
|
||||
Vendored
+91
@@ -0,0 +1,91 @@
|
||||
<p align="center">
|
||||
<a href="https://cakephp.org/" target="_blank" >
|
||||
<img alt="CakePHP" src="https://cakephp.org/v2/img/logos/CakePHP_Logo.svg" width="400" />
|
||||
</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="LICENSE" target="_blank">
|
||||
<img alt="Software License" src="https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square">
|
||||
</a>
|
||||
<a href="https://travis-ci.org/cakephp/cakephp" target="_blank">
|
||||
<img alt="Build Status" src="https://img.shields.io/travis/cakephp/cakephp/master.svg?style=flat-square">
|
||||
</a>
|
||||
<a href="https://codecov.io/github/cakephp/cakephp" target="_blank">
|
||||
<img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/cakephp/cakephp.svg?style=flat-square">
|
||||
</a>
|
||||
<a href="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/" target="_blank">
|
||||
<img alt="Code Consistency" src="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/grade.svg">
|
||||
</a>
|
||||
<a href="https://packagist.org/packages/cakephp/cakephp" target="_blank">
|
||||
<img alt="Total Downloads" src="https://img.shields.io/packagist/dt/cakephp/cakephp.svg?style=flat-square">
|
||||
</a>
|
||||
<a href="https://packagist.org/packages/cakephp/cakephp" target="_blank">
|
||||
<img alt="Latest Stable Version" src="https://img.shields.io/packagist/v/cakephp/cakephp.svg?style=flat-square&label=stable">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
[CakePHP](https://cakephp.org) is a rapid development framework for PHP which
|
||||
uses commonly known design patterns like Associative Data
|
||||
Mapping, Front Controller, and MVC. Our primary goal is to provide a structured
|
||||
framework that enables PHP users at all levels to rapidly develop robust web
|
||||
applications, without any loss to flexibility.
|
||||
|
||||
## Installing CakePHP via Composer
|
||||
|
||||
You can install CakePHP into your project using
|
||||
[Composer](https://getcomposer.org). If you're starting a new project, we
|
||||
recommend using the [app skeleton](https://github.com/cakephp/app) as
|
||||
a starting point. For existing applications you can run the following:
|
||||
|
||||
``` bash
|
||||
$ composer require cakephp/cakephp
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
Assuming you have PHPUnit installed system wide using one of the methods stated
|
||||
[here](https://phpunit.de/manual/current/en/installation.html), you can run the
|
||||
tests for CakePHP by doing the following:
|
||||
|
||||
1. Copy `phpunit.xml.dist` to `phpunit.xml`.
|
||||
2. Add the relevant database credentials to your `phpunit.xml` if you want to run tests against
|
||||
a non-SQLite datasource.
|
||||
3. Run `phpunit`.
|
||||
|
||||
## Some Handy Links
|
||||
|
||||
* [CakePHP](https://cakephp.org) - The rapid development PHP framework.
|
||||
* [CookBook](https://book.cakephp.org) - The CakePHP user documentation; start learning here!
|
||||
* [API](https://api.cakephp.org) - A reference to CakePHP's classes.
|
||||
* [Awesome CakePHP](https://github.com/FriendsOfCake/awesome-cakephp) - A list of featured resources around the framework.
|
||||
* [Plugins](https://plugins.cakephp.org) - A repository of extensions to the framework.
|
||||
* [The Bakery](https://bakery.cakephp.org) - Tips, tutorials and articles.
|
||||
* [Community Center](https://community.cakephp.org) - A source for everything community related.
|
||||
* [Training](https://training.cakephp.org) - Join a live session and get skilled with the framework.
|
||||
* [CakeFest](https://cakefest.org) - Don't miss our annual CakePHP conference.
|
||||
* [Cake Software Foundation](https://cakefoundation.org) - Promoting development related to CakePHP.
|
||||
|
||||
## Get Support!
|
||||
|
||||
* [Slack](https://cakesf.herokuapp.com/) - Join us on Slack.
|
||||
* [#cakephp](https://webchat.freenode.net/?channels=#cakephp) on irc.freenode.net - Come chat with us, we have cake.
|
||||
* [Forum](https://discourse.cakephp.org/) - Official CakePHP forum.
|
||||
* [GitHub Issues](https://github.com/cakephp/cakephp/issues) - Got issues? Please tell us!
|
||||
* [Roadmaps](https://github.com/cakephp/cakephp/wiki#roadmaps) - Want to contribute? Get involved!
|
||||
|
||||
## Contributing
|
||||
|
||||
* [CONTRIBUTING.md](.github/CONTRIBUTING.md) - Quick pointers for contributing to the CakePHP project.
|
||||
* [CookBook "Contributing" Section](https://book.cakephp.org/3/en/contributing.html) - Details about contributing to the project.
|
||||
|
||||
# Security
|
||||
|
||||
If you’ve found a security issue in CakePHP, please use the following procedure instead of the normal bug reporting system. Instead of using the bug tracker, mailing list or IRC please send an email to security [at] cakephp.org. Emails sent to this address go to the CakePHP core team on a private mailing list.
|
||||
|
||||
For each report, we try to first confirm the vulnerability. Once confirmed, the CakePHP team will take the following actions:
|
||||
|
||||
- Acknowledge to the reporter that we’ve received the issue, and are working on a fix. We ask that the reporter keep the issue confidential until we announce it.
|
||||
- Get a fix/patch prepared.
|
||||
- Prepare a post describing the vulnerability, and the possible exploits.
|
||||
- Release new versions of all affected versions.
|
||||
- Prominently feature the problem in the release announcement.
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
We support fixing security issues on the following releases:
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 3.7.x | :white_check_mark: |
|
||||
| 3.6.x | :white_check_mark: |
|
||||
| <= 3.5 | :x: |
|
||||
| 2.10.x | :white_check_mark: |
|
||||
| <= 2.9 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you’ve found a security issue in CakePHP, please use the following procedure
|
||||
instead of the normal bug reporting system. Instead of using the bug tracker,
|
||||
mailing list or IRC please send an email to security [at] cakephp.org. Emails
|
||||
sent to this address go to the CakePHP core team on a private mailing list.
|
||||
|
||||
For each report, we try to first confirm the vulnerability. Once confirmed,
|
||||
the CakePHP team will take the following actions:
|
||||
|
||||
* Acknowledge to the reporter that we’ve received the issue, and are
|
||||
working on a fix. We ask that the reporter keep the issue confidential until we announce it.
|
||||
* Get a fix/patch prepared.
|
||||
* Prepare a post describing the vulnerability, and the possible exploits.
|
||||
* Release new versions of all affected versions.
|
||||
* Prominently feature the problem in the release announcement
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// +--------------------------------------------------------------------------------------------+ //
|
||||
// CakePHP Version
|
||||
//
|
||||
// Holds a static string representing the current version of CakePHP
|
||||
//
|
||||
// CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
// Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
//
|
||||
// Licensed under The MIT License
|
||||
// Redistributions of files must retain the above copyright notice.
|
||||
//
|
||||
// @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
// @link https://cakephp.org
|
||||
// @since CakePHP(tm) v 0.2.9
|
||||
// @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
// +--------------------------------------------------------------------------------------------+ //
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
3.8.9
|
||||
Vendored
+105
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"name": "cakephp/cakephp",
|
||||
"description": "The CakePHP framework",
|
||||
"type": "library",
|
||||
"keywords": [
|
||||
"framework",
|
||||
"mvc",
|
||||
"rapid-development",
|
||||
"conventions over configuration",
|
||||
"dry",
|
||||
"orm",
|
||||
"form",
|
||||
"validation",
|
||||
"psr-7"
|
||||
],
|
||||
"homepage": "https://cakephp.org",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "CakePHP Community",
|
||||
"homepage": "https://github.com/cakephp/cakephp/graphs/contributors"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/cakephp/cakephp/issues",
|
||||
"forum": "https://stackoverflow.com/tags/cakephp",
|
||||
"irc": "irc://irc.freenode.org/cakephp",
|
||||
"source": "https://github.com/cakephp/cakephp"
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.6.0",
|
||||
"ext-intl": "*",
|
||||
"ext-mbstring": "*",
|
||||
"cakephp/chronos": "^1.0.1",
|
||||
"aura/intl": "^3.0.0",
|
||||
"psr/log": "^1.0.0",
|
||||
"psr/simple-cache": "^1.0.0",
|
||||
"zendframework/zend-diactoros": "^1.4.0"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-openssl": "To use Security::encrypt() or have secure CSRF token generation.",
|
||||
"ext-curl": "To enable more efficient network calls in Http\\Client.",
|
||||
"lib-ICU": "The intl PHP library, to use Text::transliterate() or Text::slug()"
|
||||
},
|
||||
"require-dev": {
|
||||
"cakephp/cakephp-codesniffer": "^3.0",
|
||||
"cakephp/chronos": "^1.2.1",
|
||||
"phpunit/phpunit": "^5.7.14|^6.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Cake\\": "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/Core/functions.php",
|
||||
"src/Collection/functions.php",
|
||||
"src/I18n/functions.php",
|
||||
"src/Utility/bootstrap.php"
|
||||
]
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Cake\\PHPStan\\": "tests/PHPStan/",
|
||||
"Cake\\Test\\": "tests/",
|
||||
"TestApp\\": "tests/test_app/TestApp/",
|
||||
"TestPlugin\\": "tests/test_app/Plugin/TestPlugin/src/",
|
||||
"TestPlugin\\Test\\": "tests/test_app/Plugin/TestPlugin/tests/",
|
||||
"TestPluginTwo\\": "tests/test_app/Plugin/TestPluginTwo/src/",
|
||||
"Company\\TestPluginThree\\": "tests/test_app/Plugin/Company/TestPluginThree/src/",
|
||||
"Company\\TestPluginThree\\Test\\": "tests/test_app/Plugin/Company/TestPluginThree/tests/",
|
||||
"ParentPlugin\\": "tests/test_app/Plugin/ParentPlugin/src/",
|
||||
"PluginJs\\": "tests/test_app/Plugin/PluginJs/src/"
|
||||
}
|
||||
},
|
||||
"replace": {
|
||||
"cakephp/cache": "self.version",
|
||||
"cakephp/collection": "self.version",
|
||||
"cakephp/core": "self.version",
|
||||
"cakephp/datasource": "self.version",
|
||||
"cakephp/database": "self.version",
|
||||
"cakephp/event": "self.version",
|
||||
"cakephp/filesystem": "self.version",
|
||||
"cakephp/form": "self.version",
|
||||
"cakephp/i18n": "self.version",
|
||||
"cakephp/log": "self.version",
|
||||
"cakephp/orm": "self.version",
|
||||
"cakephp/utility": "self.version",
|
||||
"cakephp/validation": "self.version"
|
||||
},
|
||||
"conflict": {
|
||||
"phpunit/phpunit": "<5.7"
|
||||
},
|
||||
"scripts": {
|
||||
"check": [
|
||||
"@cs-check",
|
||||
"@test"
|
||||
],
|
||||
"cs-check": "phpcs --colors --parallel=16 -p src/ tests/",
|
||||
"cs-fix": "phpcbf --colors --parallel=16 -p src/ tests/",
|
||||
"test": "phpunit",
|
||||
"test-coverage": "phpunit --coverage-clover=clover.xml",
|
||||
"phpstan": "phpstan analyse -c phpstan.neon -l 2 src/",
|
||||
"phpstan-setup": "cp composer.json composer.backup && composer require --dev phpstan/phpstan-shim:^0.11 && mv composer.backup composer.json"
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.2.9
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
use Cake\Routing\Router;
|
||||
|
||||
define('TIME_START', microtime(true));
|
||||
|
||||
require CAKE . 'basics.php';
|
||||
|
||||
// Sets the initial router state so future reloads work.
|
||||
Router::reload();
|
||||
+3401
File diff suppressed because it is too large.
Load diff
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
/**
|
||||
* Core Configurations.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.1.11
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
$versionFile = file(CORE_PATH . 'VERSION.txt');
|
||||
return [
|
||||
'Cake.version' => trim(array_pop($versionFile)),
|
||||
];
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.4.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Core\InstanceConfigTrait;
|
||||
|
||||
/**
|
||||
* Abstract password hashing class
|
||||
*/
|
||||
abstract class AbstractPasswordHasher
|
||||
{
|
||||
use InstanceConfigTrait;
|
||||
|
||||
/**
|
||||
* Default config
|
||||
*
|
||||
* These are merged with user-provided config when the object is used.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $config Array of config.
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
$this->setConfig($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates password hash.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @return string|false Either the password hash string or false
|
||||
*/
|
||||
abstract public function hash($password);
|
||||
|
||||
/**
|
||||
* Check hash. Generate hash from user provided password string or data array
|
||||
* and check against existing hash.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @param string $hashedPassword Existing hashed password.
|
||||
* @return bool True if hashes match else false.
|
||||
*/
|
||||
abstract public function check($password, $hashedPassword);
|
||||
|
||||
/**
|
||||
* Returns true if the password need to be rehashed, due to the password being
|
||||
* created with anything else than the passwords generated by this class.
|
||||
*
|
||||
* Returns true by default since the only implementation users should rely
|
||||
* on is the one provided by default in php 5.5+ or any compatible library
|
||||
*
|
||||
* @param string $password The password to verify
|
||||
* @return bool
|
||||
*/
|
||||
public function needsRehash($password)
|
||||
{
|
||||
return password_needs_rehash($password, PASSWORD_DEFAULT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Controller\ComponentRegistry;
|
||||
use Cake\Core\InstanceConfigTrait;
|
||||
use Cake\Event\EventListenerInterface;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
|
||||
/**
|
||||
* Base Authentication class with common methods and properties.
|
||||
*/
|
||||
abstract class BaseAuthenticate implements EventListenerInterface
|
||||
{
|
||||
use InstanceConfigTrait;
|
||||
use LocatorAwareTrait;
|
||||
|
||||
/**
|
||||
* Default config for this object.
|
||||
*
|
||||
* - `fields` The fields to use to identify a user by.
|
||||
* - `userModel` The alias for users table, defaults to Users.
|
||||
* - `finder` The finder method to use to fetch user record. Defaults to 'all'.
|
||||
* You can set finder name as string or an array where key is finder name and value
|
||||
* is an array passed to `Table::find()` options.
|
||||
* E.g. ['finderName' => ['some_finder_option' => 'some_value']]
|
||||
* - `passwordHasher` Password hasher class. Can be a string specifying class name
|
||||
* or an array containing `className` key, any other keys will be passed as
|
||||
* config to the class. Defaults to 'Default'.
|
||||
* - Options `scope` and `contain` have been deprecated since 3.1. Use custom
|
||||
* finder instead to modify the query to fetch user record.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'fields' => [
|
||||
'username' => 'username',
|
||||
'password' => 'password',
|
||||
],
|
||||
'userModel' => 'Users',
|
||||
'scope' => [],
|
||||
'finder' => 'all',
|
||||
'contain' => null,
|
||||
'passwordHasher' => 'Default',
|
||||
];
|
||||
|
||||
/**
|
||||
* A Component registry, used to get more components.
|
||||
*
|
||||
* @var \Cake\Controller\ComponentRegistry
|
||||
*/
|
||||
protected $_registry;
|
||||
|
||||
/**
|
||||
* Password hasher instance.
|
||||
*
|
||||
* @var \Cake\Auth\AbstractPasswordHasher|null
|
||||
*/
|
||||
protected $_passwordHasher;
|
||||
|
||||
/**
|
||||
* Whether or not the user authenticated by this class
|
||||
* requires their password to be rehashed with another algorithm.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_needsPasswordRehash = false;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Cake\Controller\ComponentRegistry $registry The Component registry used on this request.
|
||||
* @param array $config Array of config to use.
|
||||
*/
|
||||
public function __construct(ComponentRegistry $registry, array $config = [])
|
||||
{
|
||||
$this->_registry = $registry;
|
||||
$this->setConfig($config);
|
||||
|
||||
if ($this->getConfig('scope') || $this->getConfig('contain')) {
|
||||
deprecationWarning(
|
||||
'The `scope` and `contain` options for Authentication are deprecated. ' .
|
||||
'Use the `finder` option instead to define additional conditions.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a user record using the username and password provided.
|
||||
*
|
||||
* Input passwords will be hashed even when a user doesn't exist. This
|
||||
* helps mitigate timing attacks that are attempting to find valid usernames.
|
||||
*
|
||||
* @param string $username The username/identifier.
|
||||
* @param string|null $password The password, if not provided password checking is skipped
|
||||
* and result of find is returned.
|
||||
* @return array|false Either false on failure, or an array of user data.
|
||||
*/
|
||||
protected function _findUser($username, $password = null)
|
||||
{
|
||||
$result = $this->_query($username)->first();
|
||||
|
||||
if ($result === null) {
|
||||
// Waste time hashing the password, to prevent
|
||||
// timing side-channels. However, don't hash
|
||||
// null passwords as authentication systems
|
||||
// like digest auth don't use passwords
|
||||
// and hashing *could* create a timing side-channel.
|
||||
if ($password !== null) {
|
||||
$hasher = $this->passwordHasher();
|
||||
$hasher->hash($password);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$passwordField = $this->_config['fields']['password'];
|
||||
if ($password !== null) {
|
||||
$hasher = $this->passwordHasher();
|
||||
$hashedPassword = $result->get($passwordField);
|
||||
|
||||
if ($hashedPassword === null || $hashedPassword === '') {
|
||||
// Waste time hashing the password, to prevent
|
||||
// timing side-channels to distinguish whether
|
||||
// user has password or not.
|
||||
$hasher->hash($password);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$hasher->check($password, $hashedPassword)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword);
|
||||
$result->unsetProperty($passwordField);
|
||||
}
|
||||
$hidden = $result->getHidden();
|
||||
if ($password === null && in_array($passwordField, $hidden, true)) {
|
||||
$key = array_search($passwordField, $hidden, true);
|
||||
unset($hidden[$key]);
|
||||
$result->setHidden($hidden);
|
||||
}
|
||||
|
||||
return $result->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get query object for fetching user from database.
|
||||
*
|
||||
* @param string $username The username/identifier.
|
||||
* @return \Cake\ORM\Query
|
||||
*/
|
||||
protected function _query($username)
|
||||
{
|
||||
$config = $this->_config;
|
||||
$table = $this->getTableLocator()->get($config['userModel']);
|
||||
|
||||
$options = [
|
||||
'conditions' => [$table->aliasField($config['fields']['username']) => $username],
|
||||
];
|
||||
|
||||
if (!empty($config['scope'])) {
|
||||
$options['conditions'] = array_merge($options['conditions'], $config['scope']);
|
||||
}
|
||||
if (!empty($config['contain'])) {
|
||||
$options['contain'] = $config['contain'];
|
||||
}
|
||||
|
||||
$finder = $config['finder'];
|
||||
if (is_array($finder)) {
|
||||
$options += current($finder);
|
||||
$finder = key($finder);
|
||||
}
|
||||
|
||||
if (!isset($options['username'])) {
|
||||
$options['username'] = $username;
|
||||
}
|
||||
|
||||
return $table->find($finder, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return password hasher object
|
||||
*
|
||||
* @return \Cake\Auth\AbstractPasswordHasher Password hasher instance
|
||||
* @throws \RuntimeException If password hasher class not found or
|
||||
* it does not extend AbstractPasswordHasher
|
||||
*/
|
||||
public function passwordHasher()
|
||||
{
|
||||
if ($this->_passwordHasher !== null) {
|
||||
return $this->_passwordHasher;
|
||||
}
|
||||
|
||||
$passwordHasher = $this->_config['passwordHasher'];
|
||||
|
||||
return $this->_passwordHasher = PasswordHasherFactory::build($passwordHasher);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not the password stored in the repository for the logged in user
|
||||
* requires to be rehashed with another algorithm
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function needsPasswordRehash()
|
||||
{
|
||||
return $this->_needsPasswordRehash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate a user based on the request information.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request to get authentication information from.
|
||||
* @param \Cake\Http\Response $response A response object that can have headers added.
|
||||
* @return array|false Either false on failure, or an array of user data on success.
|
||||
*/
|
||||
abstract public function authenticate(ServerRequest $request, Response $response);
|
||||
|
||||
/**
|
||||
* Get a user based on information in the request. Primarily used by stateless authentication
|
||||
* systems like basic and digest auth.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request object.
|
||||
* @return array|false Either false or an array of user information
|
||||
*/
|
||||
public function getUser(ServerRequest $request)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle unauthenticated access attempt. In implementation valid return values
|
||||
* can be:
|
||||
*
|
||||
* - Null - No action taken, AuthComponent should return appropriate response.
|
||||
* - Cake\Http\Response - A response object, which will cause AuthComponent to
|
||||
* simply return that response.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request A request object.
|
||||
* @param \Cake\Http\Response $response A response object.
|
||||
* @return void
|
||||
*/
|
||||
public function unauthenticated(ServerRequest $request, Response $response)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of all events that this authenticate class will listen to.
|
||||
*
|
||||
* An authenticate class can listen to following events fired by AuthComponent:
|
||||
*
|
||||
* - `Auth.afterIdentify` - Fired after a user has been identified using one of
|
||||
* configured authenticate class. The callback function should have signature
|
||||
* like `afterIdentify(Event $event, array $user)` when `$user` is the
|
||||
* identified user record.
|
||||
*
|
||||
* - `Auth.logout` - Fired when AuthComponent::logout() is called. The callback
|
||||
* function should have signature like `logout(Event $event, array $user)`
|
||||
* where `$user` is the user about to be logged out.
|
||||
*
|
||||
* @return array List of events this class listens to. Defaults to `[]`.
|
||||
*/
|
||||
public function implementedEvents()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Controller\ComponentRegistry;
|
||||
use Cake\Core\InstanceConfigTrait;
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* Abstract base authorization adapter for AuthComponent.
|
||||
*
|
||||
* @see \Cake\Controller\Component\AuthComponent::$authenticate
|
||||
*/
|
||||
abstract class BaseAuthorize
|
||||
{
|
||||
use InstanceConfigTrait;
|
||||
|
||||
/**
|
||||
* ComponentRegistry instance for getting more components.
|
||||
*
|
||||
* @var \Cake\Controller\ComponentRegistry
|
||||
*/
|
||||
protected $_registry;
|
||||
|
||||
/**
|
||||
* Default config for authorize objects.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Cake\Controller\ComponentRegistry $registry The controller for this request.
|
||||
* @param array $config An array of config. This class does not use any config.
|
||||
*/
|
||||
public function __construct(ComponentRegistry $registry, array $config = [])
|
||||
{
|
||||
$this->_registry = $registry;
|
||||
$this->setConfig($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks user authorization.
|
||||
*
|
||||
* @param array|\ArrayAccess $user Active user data
|
||||
* @param \Cake\Http\ServerRequest $request Request instance.
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function authorize($user, ServerRequest $request);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Http\Exception\UnauthorizedException;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* Basic Authentication adapter for AuthComponent.
|
||||
*
|
||||
* Provides Basic HTTP authentication support for AuthComponent. Basic Auth will
|
||||
* authenticate users against the configured userModel and verify the username
|
||||
* and passwords match.
|
||||
*
|
||||
* ### Using Basic auth
|
||||
*
|
||||
* Load `AuthComponent` in your controller's `initialize()` and add 'Basic' in 'authenticate' key
|
||||
* ```
|
||||
* $this->loadComponent('Auth', [
|
||||
* 'authenticate' => ['Basic']
|
||||
* 'storage' => 'Memory',
|
||||
* 'unauthorizedRedirect' => false,
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* You should set `storage` to `Memory` to prevent CakePHP from sending a
|
||||
* session cookie to the client.
|
||||
*
|
||||
* You should set `unauthorizedRedirect` to `false`. This causes `AuthComponent` to
|
||||
* throw a `ForbiddenException` exception instead of redirecting to another page.
|
||||
*
|
||||
* Since HTTP Basic Authentication is stateless you don't need call `setUser()`
|
||||
* in your controller. The user credentials will be checked on each request. If
|
||||
* valid credentials are not provided, required authentication headers will be sent
|
||||
* by this authentication provider which triggers the login dialog in the browser/client.
|
||||
*
|
||||
* @see https://book.cakephp.org/3/en/controllers/components/authentication.html
|
||||
*/
|
||||
class BasicAuthenticate extends BaseAuthenticate
|
||||
{
|
||||
/**
|
||||
* Authenticate a user using HTTP auth. Will use the configured User model and attempt a
|
||||
* login using HTTP auth.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request The request to authenticate with.
|
||||
* @param \Cake\Http\Response $response The response to add headers to.
|
||||
* @return array|false Either false on failure, or an array of user data on success.
|
||||
*/
|
||||
public function authenticate(ServerRequest $request, Response $response)
|
||||
{
|
||||
return $this->getUser($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user based on information in the request. Used by cookie-less auth for stateless clients.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request object.
|
||||
* @return array|false Either false or an array of user information
|
||||
*/
|
||||
public function getUser(ServerRequest $request)
|
||||
{
|
||||
$username = $request->getEnv('PHP_AUTH_USER');
|
||||
$pass = $request->getEnv('PHP_AUTH_PW');
|
||||
|
||||
if (!is_string($username) || $username === '' || !is_string($pass) || $pass === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->_findUser($username, $pass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an unauthenticated access attempt by sending appropriate login headers
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request A request object.
|
||||
* @param \Cake\Http\Response $response A response object.
|
||||
* @return void
|
||||
* @throws \Cake\Http\Exception\UnauthorizedException
|
||||
*/
|
||||
public function unauthenticated(ServerRequest $request, Response $response)
|
||||
{
|
||||
$Exception = new UnauthorizedException();
|
||||
$Exception->responseHeader($this->loginHeaders($request));
|
||||
throw $Exception;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the login headers
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request object.
|
||||
* @return string[] Headers for logging in.
|
||||
*/
|
||||
public function loginHeaders(ServerRequest $request)
|
||||
{
|
||||
$realm = $this->getConfig('realm') ?: $request->getEnv('SERVER_NAME');
|
||||
|
||||
return [
|
||||
'WWW-Authenticate' => sprintf('Basic realm="%s"', $realm),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Controller\ComponentRegistry;
|
||||
use Cake\Controller\Controller;
|
||||
use Cake\Core\Exception\Exception;
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* An authorization adapter for AuthComponent. Provides the ability to authorize
|
||||
* using a controller callback. Your controller's isAuthorized() method should
|
||||
* return a boolean to indicate whether or not the user is authorized.
|
||||
*
|
||||
* ```
|
||||
* public function isAuthorized($user)
|
||||
* {
|
||||
* if ($this->request->getParam('admin')) {
|
||||
* return $user['role'] === 'admin';
|
||||
* }
|
||||
* return !empty($user);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* The above is simple implementation that would only authorize users of the
|
||||
* 'admin' role to access admin routing.
|
||||
*
|
||||
* @see \Cake\Controller\Component\AuthComponent::$authenticate
|
||||
*/
|
||||
class ControllerAuthorize extends BaseAuthorize
|
||||
{
|
||||
/**
|
||||
* Controller for the request.
|
||||
*
|
||||
* @var \Cake\Controller\Controller
|
||||
*/
|
||||
protected $_Controller;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function __construct(ComponentRegistry $registry, array $config = [])
|
||||
{
|
||||
parent::__construct($registry, $config);
|
||||
$this->controller($registry->getController());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get/set the controller this authorize object will be working with. Also
|
||||
* checks that isAuthorized is implemented.
|
||||
*
|
||||
* @param \Cake\Controller\Controller|null $controller null to get, a controller to set.
|
||||
* @return \Cake\Controller\Controller
|
||||
* @throws \Cake\Core\Exception\Exception If controller does not have method `isAuthorized()`.
|
||||
*/
|
||||
public function controller(Controller $controller = null)
|
||||
{
|
||||
if ($controller) {
|
||||
if (!method_exists($controller, 'isAuthorized')) {
|
||||
throw new Exception(sprintf(
|
||||
'%s does not implement an isAuthorized() method.',
|
||||
get_class($controller)
|
||||
));
|
||||
}
|
||||
$this->_Controller = $controller;
|
||||
}
|
||||
|
||||
return $this->_Controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks user authorization using a controller callback.
|
||||
*
|
||||
* @param array|\ArrayAccess $user Active user data
|
||||
* @param \Cake\Http\ServerRequest $request Request instance.
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize($user, ServerRequest $request)
|
||||
{
|
||||
return (bool)$this->_Controller->isAuthorized($user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
/**
|
||||
* Default password hashing class.
|
||||
*/
|
||||
class DefaultPasswordHasher extends AbstractPasswordHasher
|
||||
{
|
||||
/**
|
||||
* Default config for this object.
|
||||
*
|
||||
* ### Options
|
||||
*
|
||||
* - `hashType` - Hashing algo to use. Valid values are those supported by `$algo`
|
||||
* argument of `password_hash()`. Defaults to `PASSWORD_DEFAULT`
|
||||
* - `hashOptions` - Associative array of options. Check the PHP manual for
|
||||
* supported options for each hash type. Defaults to empty array.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'hashType' => PASSWORD_DEFAULT,
|
||||
'hashOptions' => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* Generates password hash.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @return string|false Password hash or false on failure
|
||||
* @link https://book.cakephp.org/3/en/controllers/components/authentication.html#hashing-passwords
|
||||
*/
|
||||
public function hash($password)
|
||||
{
|
||||
return password_hash(
|
||||
$password,
|
||||
$this->_config['hashType'],
|
||||
$this->_config['hashOptions']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check hash. Generate hash for user provided password and check against existing hash.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @param string $hashedPassword Existing hashed password.
|
||||
* @return bool True if hashes match else false.
|
||||
*/
|
||||
public function check($password, $hashedPassword)
|
||||
{
|
||||
return password_verify($password, $hashedPassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the password need to be rehashed, due to the password being
|
||||
* created with anything else than the passwords generated by this class.
|
||||
*
|
||||
* @param string $password The password to verify
|
||||
* @return bool
|
||||
*/
|
||||
public function needsRehash($password)
|
||||
{
|
||||
return password_needs_rehash($password, $this->_config['hashType'], $this->_config['hashOptions']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Controller\ComponentRegistry;
|
||||
use Cake\Http\ServerRequest;
|
||||
use Cake\Utility\Security;
|
||||
|
||||
/**
|
||||
* Digest Authentication adapter for AuthComponent.
|
||||
*
|
||||
* Provides Digest HTTP authentication support for AuthComponent.
|
||||
*
|
||||
* ### Using Digest auth
|
||||
*
|
||||
* Load `AuthComponent` in your controller's `initialize()` and add 'Digest' in 'authenticate' key
|
||||
*
|
||||
* ```
|
||||
* $this->loadComponent('Auth', [
|
||||
* 'authenticate' => ['Digest'],
|
||||
* 'storage' => 'Memory',
|
||||
* 'unauthorizedRedirect' => false,
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* You should set `storage` to `Memory` to prevent CakePHP from sending a
|
||||
* session cookie to the client.
|
||||
*
|
||||
* You should set `unauthorizedRedirect` to `false`. This causes `AuthComponent` to
|
||||
* throw a `ForbiddenException` exception instead of redirecting to another page.
|
||||
*
|
||||
* Since HTTP Digest Authentication is stateless you don't need call `setUser()`
|
||||
* in your controller. The user credentials will be checked on each request. If
|
||||
* valid credentials are not provided, required authentication headers will be sent
|
||||
* by this authentication provider which triggers the login dialog in the browser/client.
|
||||
*
|
||||
* ### Generating passwords compatible with Digest authentication.
|
||||
*
|
||||
* DigestAuthenticate requires a special password hash that conforms to RFC2617.
|
||||
* You can generate this password using `DigestAuthenticate::password()`
|
||||
*
|
||||
* ```
|
||||
* $digestPass = DigestAuthenticate::password($username, $password, env('SERVER_NAME'));
|
||||
* ```
|
||||
*
|
||||
* If you wish to use digest authentication alongside other authentication methods,
|
||||
* it's recommended that you store the digest authentication separately. For
|
||||
* example `User.digest_pass` could be used for a digest password, while
|
||||
* `User.password` would store the password hash for use with other methods like
|
||||
* Basic or Form.
|
||||
*
|
||||
* @see https://book.cakephp.org/3/en/controllers/components/authentication.html
|
||||
*/
|
||||
class DigestAuthenticate extends BasicAuthenticate
|
||||
{
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* Besides the keys specified in BaseAuthenticate::$_defaultConfig,
|
||||
* DigestAuthenticate uses the following extra keys:
|
||||
*
|
||||
* - `secret` The secret to use for nonce validation. Defaults to Security::getSalt().
|
||||
* - `realm` The realm authentication is for, Defaults to the servername.
|
||||
* - `qop` Defaults to 'auth', no other values are supported at this time.
|
||||
* - `opaque` A string that must be returned unchanged by clients.
|
||||
* Defaults to `md5($config['realm'])`
|
||||
* - `nonceLifetime` The number of seconds that nonces are valid for. Defaults to 300.
|
||||
*
|
||||
* @param \Cake\Controller\ComponentRegistry $registry The Component registry
|
||||
* used on this request.
|
||||
* @param array $config Array of config to use.
|
||||
*/
|
||||
public function __construct(ComponentRegistry $registry, array $config = [])
|
||||
{
|
||||
$this->setConfig([
|
||||
'nonceLifetime' => 300,
|
||||
'secret' => Security::getSalt(),
|
||||
'realm' => null,
|
||||
'qop' => 'auth',
|
||||
'opaque' => null,
|
||||
]);
|
||||
|
||||
parent::__construct($registry, $config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user based on information in the request. Used by cookie-less auth for stateless clients.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request object.
|
||||
* @return array|false Either false or an array of user information
|
||||
*/
|
||||
public function getUser(ServerRequest $request)
|
||||
{
|
||||
$digest = $this->_getDigest($request);
|
||||
if (empty($digest)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$user = $this->_findUser($digest['username']);
|
||||
if (empty($user)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->validNonce($digest['nonce'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$field = $this->_config['fields']['password'];
|
||||
$password = $user[$field];
|
||||
unset($user[$field]);
|
||||
|
||||
$hash = $this->generateResponseHash($digest, $password, $request->getEnv('ORIGINAL_REQUEST_METHOD'));
|
||||
if (hash_equals($hash, $digest['response'])) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the digest headers from the request/environment.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request object.
|
||||
* @return array|bool Array of digest information.
|
||||
*/
|
||||
protected function _getDigest(ServerRequest $request)
|
||||
{
|
||||
$digest = $request->getEnv('PHP_AUTH_DIGEST');
|
||||
if (empty($digest) && function_exists('apache_request_headers')) {
|
||||
$headers = apache_request_headers();
|
||||
if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
|
||||
$digest = substr($headers['Authorization'], 7);
|
||||
}
|
||||
}
|
||||
if (empty($digest)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->parseAuthData($digest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the digest authentication headers and split them up.
|
||||
*
|
||||
* @param string $digest The raw digest authentication headers.
|
||||
* @return array|null An array of digest authentication headers
|
||||
*/
|
||||
public function parseAuthData($digest)
|
||||
{
|
||||
if (substr($digest, 0, 7) === 'Digest ') {
|
||||
$digest = substr($digest, 7);
|
||||
}
|
||||
$keys = $match = [];
|
||||
$req = ['nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1];
|
||||
preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9\:\#\%\?\&@=\.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
|
||||
|
||||
foreach ($match as $i) {
|
||||
$keys[$i[1]] = $i[3];
|
||||
unset($req[$i[1]]);
|
||||
}
|
||||
|
||||
if (empty($req)) {
|
||||
return $keys;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the response hash for a given digest array.
|
||||
*
|
||||
* @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData().
|
||||
* @param string $password The digest hash password generated with DigestAuthenticate::password()
|
||||
* @param string $method Request method
|
||||
* @return string Response hash
|
||||
*/
|
||||
public function generateResponseHash($digest, $password, $method)
|
||||
{
|
||||
return md5(
|
||||
$password .
|
||||
':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
|
||||
md5($method . ':' . $digest['uri'])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an auth digest password hash to store
|
||||
*
|
||||
* @param string $username The username to use in the digest hash.
|
||||
* @param string $password The unhashed password to make a digest hash for.
|
||||
* @param string $realm The realm the password is for.
|
||||
* @return string the hashed password that can later be used with Digest authentication.
|
||||
*/
|
||||
public static function password($username, $password, $realm)
|
||||
{
|
||||
return md5($username . ':' . $realm . ':' . $password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the login headers
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request object.
|
||||
* @return string[] Headers for logging in.
|
||||
*/
|
||||
public function loginHeaders(ServerRequest $request)
|
||||
{
|
||||
$realm = $this->_config['realm'] ?: $request->getEnv('SERVER_NAME');
|
||||
|
||||
$options = [
|
||||
'realm' => $realm,
|
||||
'qop' => $this->_config['qop'],
|
||||
'nonce' => $this->generateNonce(),
|
||||
'opaque' => $this->_config['opaque'] ?: md5($realm),
|
||||
];
|
||||
|
||||
$digest = $this->_getDigest($request);
|
||||
if ($digest && isset($digest['nonce']) && !$this->validNonce($digest['nonce'])) {
|
||||
$options['stale'] = true;
|
||||
}
|
||||
|
||||
$opts = [];
|
||||
foreach ($options as $k => $v) {
|
||||
if (is_bool($v)) {
|
||||
$v = $v ? 'true' : 'false';
|
||||
$opts[] = sprintf('%s=%s', $k, $v);
|
||||
} else {
|
||||
$opts[] = sprintf('%s="%s"', $k, $v);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'WWW-Authenticate' => 'Digest ' . implode(',', $opts),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a nonce value that is validated in future requests.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function generateNonce()
|
||||
{
|
||||
$expiryTime = microtime(true) + $this->getConfig('nonceLifetime');
|
||||
$secret = $this->getConfig('secret');
|
||||
$signatureValue = hash_hmac('sha256', $expiryTime . ':' . $secret, $secret);
|
||||
$nonceValue = $expiryTime . ':' . $signatureValue;
|
||||
|
||||
return base64_encode($nonceValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the nonce to ensure it is valid and not expired.
|
||||
*
|
||||
* @param string $nonce The nonce value to check.
|
||||
* @return bool
|
||||
*/
|
||||
protected function validNonce($nonce)
|
||||
{
|
||||
$value = base64_decode($nonce);
|
||||
if ($value === false) {
|
||||
return false;
|
||||
}
|
||||
$parts = explode(':', $value);
|
||||
if (count($parts) !== 2) {
|
||||
return false;
|
||||
}
|
||||
list($expires, $checksum) = $parts;
|
||||
if ($expires < microtime(true)) {
|
||||
return false;
|
||||
}
|
||||
$secret = $this->getConfig('secret');
|
||||
$check = hash_hmac('sha256', $expires . ':' . $secret, $secret);
|
||||
|
||||
return hash_equals($check, $checksum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
/**
|
||||
* A password hasher that can use multiple different hashes where only
|
||||
* one is the preferred one. This is useful when trying to migrate an
|
||||
* existing database of users from one password type to another.
|
||||
*/
|
||||
class FallbackPasswordHasher extends AbstractPasswordHasher
|
||||
{
|
||||
/**
|
||||
* Default config for this object.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'hashers' => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* Holds the list of password hasher objects that will be used
|
||||
*
|
||||
* @var \Cake\Auth\AbstractPasswordHasher[]
|
||||
*/
|
||||
protected $_hashers = [];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $config configuration options for this object. Requires the
|
||||
* `hashers` key to be present in the array with a list of other hashers to be
|
||||
* used
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
parent::__construct($config);
|
||||
|
||||
foreach ($this->_config['hashers'] as $key => $hasher) {
|
||||
if (is_array($hasher) && !isset($hasher['className'])) {
|
||||
$hasher['className'] = $key;
|
||||
}
|
||||
$this->_hashers[] = PasswordHasherFactory::build($hasher);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates password hash.
|
||||
*
|
||||
* Uses the first password hasher in the list to generate the hash
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @return string|false Password hash
|
||||
*/
|
||||
public function hash($password)
|
||||
{
|
||||
return $this->_hashers[0]->hash($password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that the provided password corresponds to its hashed version
|
||||
*
|
||||
* This will iterate over all configured hashers until one of them returns
|
||||
* true.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @param string $hashedPassword Existing hashed password.
|
||||
* @return bool True if hashes match else false.
|
||||
*/
|
||||
public function check($password, $hashedPassword)
|
||||
{
|
||||
foreach ($this->_hashers as $hasher) {
|
||||
if ($hasher->check($password, $hashedPassword)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the password need to be rehashed, with the first hasher present
|
||||
* in the list of hashers
|
||||
*
|
||||
* @param string $password The password to verify
|
||||
* @return bool
|
||||
*/
|
||||
public function needsRehash($password)
|
||||
{
|
||||
return $this->_hashers[0]->needsRehash($password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
/**
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* Form authentication adapter for AuthComponent.
|
||||
*
|
||||
* Allows you to authenticate users based on form POST data.
|
||||
* Usually, this is a login form that users enter information into.
|
||||
*
|
||||
* ### Using Form auth
|
||||
*
|
||||
* Load `AuthComponent` in your controller's `initialize()` and add 'Form' in 'authenticate' key
|
||||
*
|
||||
* ```
|
||||
* $this->loadComponent('Auth', [
|
||||
* 'authenticate' => [
|
||||
* 'Form' => [
|
||||
* 'fields' => ['username' => 'email', 'password' => 'passwd'],
|
||||
* 'finder' => 'auth',
|
||||
* ]
|
||||
* ]
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* When configuring FormAuthenticate you can pass in config to which fields, model and finder
|
||||
* are used. See `BaseAuthenticate::$_defaultConfig` for more information.
|
||||
*
|
||||
* @see https://book.cakephp.org/3/en/controllers/components/authentication.html
|
||||
*/
|
||||
class FormAuthenticate extends BaseAuthenticate
|
||||
{
|
||||
/**
|
||||
* Checks the fields to ensure they are supplied.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request The request that contains login information.
|
||||
* @param array $fields The fields to be checked.
|
||||
* @return bool False if the fields have not been supplied. True if they exist.
|
||||
*/
|
||||
protected function _checkFields(ServerRequest $request, array $fields)
|
||||
{
|
||||
foreach ([$fields['username'], $fields['password']] as $field) {
|
||||
$value = $request->getData($field);
|
||||
if (empty($value) || !is_string($value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates the identity contained in a request. Will use the `config.userModel`, and `config.fields`
|
||||
* to find POST data that is used to find a matching record in the `config.userModel`. Will return false if
|
||||
* there is no post data, either username or password is missing, or if the scope conditions have not been met.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request The request that contains login information.
|
||||
* @param \Cake\Http\Response $response Unused response object.
|
||||
* @return array|false False on login failure. An array of User data on success.
|
||||
*/
|
||||
public function authenticate(ServerRequest $request, Response $response)
|
||||
{
|
||||
$fields = $this->_config['fields'];
|
||||
if (!$this->_checkFields($request, $fields)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->_findUser(
|
||||
$request->getData($fields['username']),
|
||||
$request->getData($fields['password'])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Core\App;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Builds password hashing objects
|
||||
*/
|
||||
class PasswordHasherFactory
|
||||
{
|
||||
/**
|
||||
* Returns password hasher object out of a hasher name or a configuration array
|
||||
*
|
||||
* @param string|array $passwordHasher Name of the password hasher or an array with
|
||||
* at least the key `className` set to the name of the class to use
|
||||
* @return \Cake\Auth\AbstractPasswordHasher Password hasher instance
|
||||
* @throws \RuntimeException If password hasher class not found or
|
||||
* it does not extend Cake\Auth\AbstractPasswordHasher
|
||||
*/
|
||||
public static function build($passwordHasher)
|
||||
{
|
||||
$config = [];
|
||||
if (is_string($passwordHasher)) {
|
||||
$class = $passwordHasher;
|
||||
} else {
|
||||
$class = $passwordHasher['className'];
|
||||
$config = $passwordHasher;
|
||||
unset($config['className']);
|
||||
}
|
||||
|
||||
$className = App::className($class, 'Auth', 'PasswordHasher');
|
||||
if ($className === false) {
|
||||
throw new RuntimeException(sprintf('Password hasher class "%s" was not found.', $class));
|
||||
}
|
||||
|
||||
$hasher = new $className($config);
|
||||
|
||||
if (!($hasher instanceof AbstractPasswordHasher)) {
|
||||
throw new RuntimeException('Password hasher must extend AbstractPasswordHasher class.');
|
||||
}
|
||||
|
||||
return $hasher;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.1.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth\Storage;
|
||||
|
||||
/**
|
||||
* Memory based non-persistent storage for authenticated user record.
|
||||
*/
|
||||
class MemoryStorage implements StorageInterface
|
||||
{
|
||||
/**
|
||||
* User record.
|
||||
*
|
||||
* @var \ArrayAccess|array|null
|
||||
*/
|
||||
protected $_user;
|
||||
|
||||
/**
|
||||
* Redirect URL.
|
||||
*
|
||||
* @var string|array|null
|
||||
*/
|
||||
protected $_redirectUrl;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
return $this->_user;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function write($user)
|
||||
{
|
||||
$this->_user = $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
$this->_user = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function redirectUrl($url = null)
|
||||
{
|
||||
if ($url === null) {
|
||||
return $this->_redirectUrl;
|
||||
}
|
||||
|
||||
if ($url === false) {
|
||||
$this->_redirectUrl = null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->_redirectUrl = $url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.1.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth\Storage;
|
||||
|
||||
use Cake\Core\InstanceConfigTrait;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* Session based persistent storage for authenticated user record.
|
||||
*/
|
||||
class SessionStorage implements StorageInterface
|
||||
{
|
||||
use InstanceConfigTrait;
|
||||
|
||||
/**
|
||||
* User record.
|
||||
*
|
||||
* Stores user record array if fetched from session or false if session
|
||||
* does not have user record.
|
||||
*
|
||||
* @var \ArrayAccess|array|false|null
|
||||
*/
|
||||
protected $_user;
|
||||
|
||||
/**
|
||||
* Session object.
|
||||
*
|
||||
* @var \Cake\Http\Session
|
||||
*/
|
||||
protected $_session;
|
||||
|
||||
/**
|
||||
* Default configuration for this class.
|
||||
*
|
||||
* Keys:
|
||||
*
|
||||
* - `key` - Session key used to store user record.
|
||||
* - `redirect` - Session key used to store redirect URL.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'key' => 'Auth.User',
|
||||
'redirect' => 'Auth.redirect',
|
||||
];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Request instance.
|
||||
* @param \Cake\Http\Response $response Response instance.
|
||||
* @param array $config Configuration list.
|
||||
*/
|
||||
public function __construct(ServerRequest $request, Response $response, array $config = [])
|
||||
{
|
||||
$this->_session = $request->getSession();
|
||||
$this->setConfig($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read user record from session.
|
||||
*
|
||||
* @return array|null User record if available else null.
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
if ($this->_user !== null) {
|
||||
return $this->_user ?: null;
|
||||
}
|
||||
|
||||
$this->_user = $this->_session->read($this->_config['key']) ?: false;
|
||||
|
||||
return $this->_user ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write user record to session.
|
||||
*
|
||||
* The session id is also renewed to help mitigate issues with session replays.
|
||||
*
|
||||
* @param array|\ArrayAccess $user User record.
|
||||
* @return void
|
||||
*/
|
||||
public function write($user)
|
||||
{
|
||||
$this->_user = $user;
|
||||
|
||||
$this->_session->renew();
|
||||
$this->_session->write($this->_config['key'], $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete user record from session.
|
||||
*
|
||||
* The session id is also renewed to help mitigate issues with session replays.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
$this->_user = false;
|
||||
|
||||
$this->_session->delete($this->_config['key']);
|
||||
$this->_session->renew();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function redirectUrl($url = null)
|
||||
{
|
||||
if ($url === null) {
|
||||
return $this->_session->read($this->_config['redirect']);
|
||||
}
|
||||
|
||||
if ($url === false) {
|
||||
$this->_session->delete($this->_config['redirect']);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->_session->write($this->_config['redirect'], $url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.1.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth\Storage;
|
||||
|
||||
/**
|
||||
* Describes the methods that any class representing an Auth data storage should
|
||||
* comply with.
|
||||
*/
|
||||
interface StorageInterface
|
||||
{
|
||||
/**
|
||||
* Read user record.
|
||||
*
|
||||
* @return \ArrayAccess|array|null
|
||||
*/
|
||||
public function read();
|
||||
|
||||
/**
|
||||
* Write user record.
|
||||
*
|
||||
* @param array|\ArrayAccess $user User record.
|
||||
* @return void
|
||||
*/
|
||||
public function write($user);
|
||||
|
||||
/**
|
||||
* Delete user record.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete();
|
||||
|
||||
/**
|
||||
* Get/set redirect URL.
|
||||
*
|
||||
* @param mixed $url Redirect URL. If `null` returns current URL. If `false`
|
||||
* deletes currently set URL.
|
||||
* @return string|array|null
|
||||
*/
|
||||
public function redirectUrl($url = null);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Auth;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Error\Debugger;
|
||||
use Cake\Utility\Security;
|
||||
|
||||
/**
|
||||
* Password hashing class that use weak hashing algorithms. This class is
|
||||
* intended only to be used with legacy databases where passwords have
|
||||
* not been migrated to a stronger algorithm yet.
|
||||
*/
|
||||
class WeakPasswordHasher extends AbstractPasswordHasher
|
||||
{
|
||||
/**
|
||||
* Default config for this object.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'hashType' => null,
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function __construct(array $config = [])
|
||||
{
|
||||
if (Configure::read('debug')) {
|
||||
Debugger::checkSecurityKeys();
|
||||
}
|
||||
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates password hash.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @return string Password hash
|
||||
*/
|
||||
public function hash($password)
|
||||
{
|
||||
return Security::hash($password, $this->_config['hashType'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check hash. Generate hash for user provided password and check against existing hash.
|
||||
*
|
||||
* @param string $password Plain text password to hash.
|
||||
* @param string $hashedPassword Existing hashed password.
|
||||
* @return bool True if hashes match else false.
|
||||
*/
|
||||
public function check($password, $hashedPassword)
|
||||
{
|
||||
return $hashedPassword === $this->hash($password);
|
||||
}
|
||||
}
|
||||
+696
@@ -0,0 +1,696 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.2.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache;
|
||||
|
||||
use Cake\Cache\Engine\NullEngine;
|
||||
use Cake\Core\ObjectRegistry;
|
||||
use Cake\Core\StaticConfigTrait;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Cache provides a consistent interface to Caching in your application. It allows you
|
||||
* to use several different Cache engines, without coupling your application to a specific
|
||||
* implementation. It also allows you to change out cache storage or configuration without effecting
|
||||
* the rest of your application.
|
||||
*
|
||||
* ### Configuring Cache engines
|
||||
*
|
||||
* You can configure Cache engines in your application's `Config/cache.php` file.
|
||||
* A sample configuration would be:
|
||||
*
|
||||
* ```
|
||||
* Cache::config('shared', [
|
||||
* 'className' => 'Cake\Cache\Engine\ApcuEngine',
|
||||
* 'prefix' => 'my_app_'
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* This would configure an APCu cache engine to the 'shared' alias. You could then read and write
|
||||
* to that cache alias by using it for the `$config` parameter in the various Cache methods.
|
||||
*
|
||||
* In general all Cache operations are supported by all cache engines.
|
||||
* However, Cache::increment() and Cache::decrement() are not supported by File caching.
|
||||
*
|
||||
* There are 7 built-in caching engines:
|
||||
*
|
||||
* - `ApcuEngine` - Uses the APCu object cache, one of the fastest caching engines.
|
||||
* - `ArrayEngine` - Uses only memory to store all data, not actually a persistent engine.
|
||||
* Can be useful in test or CLI environment.
|
||||
* - `FileEngine` - Uses simple files to store content. Poor performance, but good for
|
||||
* storing large objects, or things that are not IO sensitive. Well suited to development
|
||||
* as it is an easy cache to inspect and manually flush.
|
||||
* - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage.
|
||||
* Fast reads/writes, and benefits from memcache being distributed.
|
||||
* - `RedisEngine` - Uses redis and php-redis extension to store cache data.
|
||||
* - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
|
||||
* This engine is recommended to people deploying on windows with IIS.
|
||||
* - `XcacheEngine` - Uses the Xcache extension, an alternative to APCu.
|
||||
*
|
||||
* See Cache engine documentation for expected configuration keys.
|
||||
*
|
||||
* @see config/app.php for configuration settings
|
||||
*/
|
||||
class Cache
|
||||
{
|
||||
use StaticConfigTrait;
|
||||
|
||||
/**
|
||||
* An array mapping url schemes to fully qualified caching engine
|
||||
* class names.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected static $_dsnClassMap = [
|
||||
'array' => 'Cake\Cache\Engine\ArrayEngine',
|
||||
'apc' => 'Cake\Cache\Engine\ApcuEngine', // @deprecated Since 3.6. Use apcu instead.
|
||||
'apcu' => 'Cake\Cache\Engine\ApcuEngine',
|
||||
'file' => 'Cake\Cache\Engine\FileEngine',
|
||||
'memcached' => 'Cake\Cache\Engine\MemcachedEngine',
|
||||
'null' => 'Cake\Cache\Engine\NullEngine',
|
||||
'redis' => 'Cake\Cache\Engine\RedisEngine',
|
||||
'wincache' => 'Cake\Cache\Engine\WincacheEngine',
|
||||
'xcache' => 'Cake\Cache\Engine\XcacheEngine',
|
||||
];
|
||||
|
||||
/**
|
||||
* Flag for tracking whether or not caching is enabled.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $_enabled = true;
|
||||
|
||||
/**
|
||||
* Group to Config mapping
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $_groups = [];
|
||||
|
||||
/**
|
||||
* Cache Registry used for creating and using cache adapters.
|
||||
*
|
||||
* @var \Cake\Core\ObjectRegistry
|
||||
*/
|
||||
protected static $_registry;
|
||||
|
||||
/**
|
||||
* Returns the Cache Registry instance used for creating and using cache adapters.
|
||||
*
|
||||
* @return \Cake\Core\ObjectRegistry
|
||||
*/
|
||||
public static function getRegistry()
|
||||
{
|
||||
if (!static::$_registry) {
|
||||
static::$_registry = new CacheRegistry();
|
||||
}
|
||||
|
||||
return static::$_registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Cache Registry instance used for creating and using cache adapters.
|
||||
*
|
||||
* Also allows for injecting of a new registry instance.
|
||||
*
|
||||
* @param \Cake\Core\ObjectRegistry $registry Injectable registry object.
|
||||
* @return void
|
||||
*/
|
||||
public static function setRegistry(ObjectRegistry $registry)
|
||||
{
|
||||
static::$_registry = $registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Cache Registry instance used for creating and using cache adapters.
|
||||
* Also allows for injecting of a new registry instance.
|
||||
*
|
||||
* @param \Cake\Core\ObjectRegistry|null $registry Injectable registry object.
|
||||
* @return \Cake\Core\ObjectRegistry
|
||||
* @deprecated Deprecated since 3.5. Use getRegistry() and setRegistry() instead.
|
||||
*/
|
||||
public static function registry(ObjectRegistry $registry = null)
|
||||
{
|
||||
deprecationWarning('Use Cache::getRegistry() and Cache::setRegistry() instead.');
|
||||
if ($registry) {
|
||||
static::setRegistry($registry);
|
||||
}
|
||||
|
||||
return static::getRegistry();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and builds the instance of the required engine class.
|
||||
*
|
||||
* @param string $name Name of the config array that needs an engine instance built
|
||||
* @return void
|
||||
* @throws \InvalidArgumentException When a cache engine cannot be created.
|
||||
*/
|
||||
protected static function _buildEngine($name)
|
||||
{
|
||||
$registry = static::getRegistry();
|
||||
|
||||
if (empty(static::$_config[$name]['className'])) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('The "%s" cache configuration does not exist.', $name)
|
||||
);
|
||||
}
|
||||
|
||||
$config = static::$_config[$name];
|
||||
|
||||
try {
|
||||
$registry->load($name, $config);
|
||||
} catch (RuntimeException $e) {
|
||||
if (!array_key_exists('fallback', $config)) {
|
||||
$registry->set($name, new NullEngine());
|
||||
trigger_error($e->getMessage(), E_USER_WARNING);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($config['fallback'] === false) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($config['fallback'] === $name) {
|
||||
throw new InvalidArgumentException(sprintf('"%s" cache configuration cannot fallback to itself.', $name), null, $e);
|
||||
}
|
||||
|
||||
$fallbackEngine = clone static::engine($config['fallback']);
|
||||
$newConfig = $config + ['groups' => [], 'prefix' => null];
|
||||
$fallbackEngine->setConfig('groups', $newConfig['groups'], false);
|
||||
if ($newConfig['prefix']) {
|
||||
$fallbackEngine->setConfig('prefix', $newConfig['prefix'], false);
|
||||
}
|
||||
$registry->set($name, $fallbackEngine);
|
||||
}
|
||||
|
||||
if ($config['className'] instanceof CacheEngine) {
|
||||
$config = $config['className']->getConfig();
|
||||
}
|
||||
|
||||
if (!empty($config['groups'])) {
|
||||
foreach ($config['groups'] as $group) {
|
||||
static::$_groups[$group][] = $name;
|
||||
static::$_groups[$group] = array_unique(static::$_groups[$group]);
|
||||
sort(static::$_groups[$group]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the engine attached to a specific configuration name.
|
||||
*
|
||||
* If the cache engine & configuration are missing an error will be
|
||||
* triggered.
|
||||
*
|
||||
* @param string $config The configuration name you want an engine for.
|
||||
* @return \Cake\Cache\CacheEngine When caching is disabled a null engine will be returned.
|
||||
* @deprecated 3.7.0 Use Cache::pool() instead. In 4.0 all cache engines will implement the
|
||||
* PSR16 interface and this method does not return objects implementing that interface.
|
||||
*/
|
||||
public static function engine($config)
|
||||
{
|
||||
if (!static::$_enabled) {
|
||||
return new NullEngine();
|
||||
}
|
||||
|
||||
$registry = static::getRegistry();
|
||||
|
||||
if (isset($registry->{$config})) {
|
||||
return $registry->{$config};
|
||||
}
|
||||
|
||||
static::_buildEngine($config);
|
||||
|
||||
return $registry->{$config};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a SimpleCacheEngine object for the named cache pool.
|
||||
*
|
||||
* @param string $config The name of the configured cache backend.
|
||||
* @return \Cake\Cache\SimpleCacheEngine
|
||||
*/
|
||||
public static function pool($config)
|
||||
{
|
||||
return new SimpleCacheEngine(static::engine($config));
|
||||
}
|
||||
|
||||
/**
|
||||
* Garbage collection
|
||||
*
|
||||
* Permanently remove all expired and deleted data
|
||||
*
|
||||
* @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
|
||||
* @param int|null $expires [optional] An expires timestamp. Defaults to NULL
|
||||
* @return void
|
||||
* @deprecated 3.7.0 Will be removed in 4.0
|
||||
*/
|
||||
public static function gc($config = 'default', $expires = null)
|
||||
{
|
||||
$engine = static::engine($config);
|
||||
$engine->gc($expires);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Writing to the active cache config:
|
||||
*
|
||||
* ```
|
||||
* Cache::write('cached_data', $data);
|
||||
* ```
|
||||
*
|
||||
* Writing to a specific cache config:
|
||||
*
|
||||
* ```
|
||||
* Cache::write('cached_data', $data, 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached - anything except a resource
|
||||
* @param string $config Optional string configuration name to write to. Defaults to 'default'
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
public static function write($key, $value, $config = 'default')
|
||||
{
|
||||
if (is_resource($value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$backend = static::pool($config);
|
||||
$success = $backend->set($key, $value);
|
||||
if ($success === false && $value !== '') {
|
||||
trigger_error(
|
||||
sprintf(
|
||||
"%s cache was unable to write '%s' to %s cache",
|
||||
$config,
|
||||
$key,
|
||||
get_class($backend)
|
||||
),
|
||||
E_USER_WARNING
|
||||
);
|
||||
}
|
||||
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for many keys into cache.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Writing to the active cache config:
|
||||
*
|
||||
* ```
|
||||
* Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2']);
|
||||
* ```
|
||||
*
|
||||
* Writing to a specific cache config:
|
||||
*
|
||||
* ```
|
||||
* Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2'], 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param array $data An array of data to be stored in the cache
|
||||
* @param string $config Optional string configuration name to write to. Defaults to 'default'
|
||||
* @return array of bools for each key provided, indicating true for success or false for fail
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function writeMany($data, $config = 'default')
|
||||
{
|
||||
$engine = static::engine($config);
|
||||
|
||||
$return = $engine->writeMany($data);
|
||||
foreach ($return as $key => $success) {
|
||||
if ($success === false && $data[$key] !== '') {
|
||||
throw new RuntimeException(sprintf(
|
||||
'%s cache was unable to write \'%s\' to %s cache',
|
||||
$config,
|
||||
$key,
|
||||
get_class($engine)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Reading from the active cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::read('my_data');
|
||||
* ```
|
||||
*
|
||||
* Reading from a specific cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::read('my_data', 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param string $config optional name of the configuration to use. Defaults to 'default'
|
||||
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
|
||||
*/
|
||||
public static function read($key, $config = 'default')
|
||||
{
|
||||
// TODO In 4.x this needs to change to use pool()
|
||||
$engine = static::engine($config);
|
||||
|
||||
return $engine->read($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read multiple keys from the cache.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Reading multiple keys from the active cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::readMany(['my_data_1', 'my_data_2]);
|
||||
* ```
|
||||
*
|
||||
* Reading from a specific cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::readMany(['my_data_1', 'my_data_2], 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param array $keys an array of keys to fetch from the cache
|
||||
* @param string $config optional name of the configuration to use. Defaults to 'default'
|
||||
* @return array An array containing, for each of the given $keys, the cached data or false if cached data could not be
|
||||
* retrieved.
|
||||
*/
|
||||
public static function readMany($keys, $config = 'default')
|
||||
{
|
||||
// In 4.x this needs to change to use pool()
|
||||
$engine = static::engine($config);
|
||||
|
||||
return $engine->readMany($keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment a number under the key and return incremented value.
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to add
|
||||
* @param string $config Optional string configuration name. Defaults to 'default'
|
||||
* @return int|false New value, or false if the data doesn't exist, is not integer,
|
||||
* or if there was an error fetching it.
|
||||
*/
|
||||
public static function increment($key, $offset = 1, $config = 'default')
|
||||
{
|
||||
$engine = static::pool($config);
|
||||
if (!is_int($offset) || $offset < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $engine->increment($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement a number under the key and return decremented value.
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @param string $config Optional string configuration name. Defaults to 'default'
|
||||
* @return int|false New value, or false if the data doesn't exist, is not integer,
|
||||
* or if there was an error fetching it
|
||||
*/
|
||||
public static function decrement($key, $offset = 1, $config = 'default')
|
||||
{
|
||||
$engine = static::pool($config);
|
||||
if (!is_int($offset) || $offset < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $engine->decrement($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Deleting from the active cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::delete('my_data');
|
||||
* ```
|
||||
*
|
||||
* Deleting from a specific cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::delete('my_data', 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param string $config name of the configuration to use. Defaults to 'default'
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
public static function delete($key, $config = 'default')
|
||||
{
|
||||
$backend = static::pool($config);
|
||||
|
||||
return $backend->delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete many keys from the cache.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Deleting multiple keys from the active cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::deleteMany(['my_data_1', 'my_data_2']);
|
||||
* ```
|
||||
*
|
||||
* Deleting from a specific cache configuration.
|
||||
*
|
||||
* ```
|
||||
* Cache::deleteMany(['my_data_1', 'my_data_2], 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param array $keys Array of cache keys to be deleted
|
||||
* @param string $config name of the configuration to use. Defaults to 'default'
|
||||
* @return array of boolean values that are true if the value was successfully deleted,
|
||||
* false if it didn't exist or couldn't be removed.
|
||||
*/
|
||||
public static function deleteMany($keys, $config = 'default')
|
||||
{
|
||||
$backend = static::pool($config);
|
||||
|
||||
$return = [];
|
||||
foreach ($keys as $key) {
|
||||
$return[$key] = $backend->delete($key);
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache.
|
||||
*
|
||||
* @param bool $check if true will check expiration, otherwise delete all. This parameter
|
||||
* will become a no-op value in 4.0 as it is deprecated.
|
||||
* @param string $config name of the configuration to use. Defaults to 'default'
|
||||
* @return bool True if the cache was successfully cleared, false otherwise
|
||||
*/
|
||||
public static function clear($check = false, $config = 'default')
|
||||
{
|
||||
$engine = static::engine($config);
|
||||
|
||||
return $engine->clear($check);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache from all configurations.
|
||||
*
|
||||
* @param bool $check if true will check expiration, otherwise delete all. This parameter
|
||||
* will become a no-op value in 4.0 as it is deprecated.
|
||||
* @return array Status code. For each configuration, it reports the status of the operation
|
||||
*/
|
||||
public static function clearAll($check = false)
|
||||
{
|
||||
$status = [];
|
||||
|
||||
foreach (self::configured() as $config) {
|
||||
$status[$config] = self::clear($check, $config);
|
||||
}
|
||||
|
||||
return $status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache belonging to the same group.
|
||||
*
|
||||
* @param string $group name of the group to be cleared
|
||||
* @param string $config name of the configuration to use. Defaults to 'default'
|
||||
* @return bool True if the cache group was successfully cleared, false otherwise
|
||||
*/
|
||||
public static function clearGroup($group, $config = 'default')
|
||||
{
|
||||
$engine = static::pool($config);
|
||||
|
||||
return $engine->clearGroup($group);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve group names to config mapping.
|
||||
*
|
||||
* ```
|
||||
* Cache::config('daily', ['duration' => '1 day', 'groups' => ['posts']]);
|
||||
* Cache::config('weekly', ['duration' => '1 week', 'groups' => ['posts', 'archive']]);
|
||||
* $configs = Cache::groupConfigs('posts');
|
||||
* ```
|
||||
*
|
||||
* $configs will equal to `['posts' => ['daily', 'weekly']]`
|
||||
* Calling this method will load all the configured engines.
|
||||
*
|
||||
* @param string|null $group group name or null to retrieve all group mappings
|
||||
* @return array map of group and all configuration that has the same group
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function groupConfigs($group = null)
|
||||
{
|
||||
foreach (array_keys(static::$_config) as $config) {
|
||||
static::engine($config);
|
||||
}
|
||||
if ($group === null) {
|
||||
return static::$_groups;
|
||||
}
|
||||
|
||||
if (isset(self::$_groups[$group])) {
|
||||
return [$group => self::$_groups[$group]];
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(sprintf('Invalid cache group %s', $group));
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-enable caching.
|
||||
*
|
||||
* If caching has been disabled with Cache::disable() this method will reverse that effect.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function enable()
|
||||
{
|
||||
static::$_enabled = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable caching.
|
||||
*
|
||||
* When disabled all cache operations will return null.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function disable()
|
||||
{
|
||||
static::$_enabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether or not caching is enabled.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function enabled()
|
||||
{
|
||||
return static::$_enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides the ability to easily do read-through caching.
|
||||
*
|
||||
* When called if the $key is not set in $config, the $callable function
|
||||
* will be invoked. The results will then be stored into the cache config
|
||||
* at key.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* Using a Closure to provide data, assume `$this` is a Table object:
|
||||
*
|
||||
* ```
|
||||
* $results = Cache::remember('all_articles', function () {
|
||||
* return $this->find('all');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param string $key The cache key to read/store data at.
|
||||
* @param callable $callable The callable that provides data in the case when
|
||||
* the cache key is empty. Can be any callable type supported by your PHP.
|
||||
* @param string $config The cache configuration to use for this operation.
|
||||
* Defaults to default.
|
||||
* @return mixed If the key is found: the cached data, false if the data
|
||||
* missing/expired, or an error. If the key is not found: boolean of the
|
||||
* success of the write
|
||||
*/
|
||||
public static function remember($key, $callable, $config = 'default')
|
||||
{
|
||||
$existing = self::read($key, $config);
|
||||
if ($existing !== false) {
|
||||
return $existing;
|
||||
}
|
||||
$results = call_user_func($callable);
|
||||
self::write($key, $results, $config);
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into a cache engine if it doesn't exist already.
|
||||
*
|
||||
* ### Usage:
|
||||
*
|
||||
* Writing to the active cache config:
|
||||
*
|
||||
* ```
|
||||
* Cache::add('cached_data', $data);
|
||||
* ```
|
||||
*
|
||||
* Writing to a specific cache config:
|
||||
*
|
||||
* ```
|
||||
* Cache::add('cached_data', $data, 'long_term');
|
||||
* ```
|
||||
*
|
||||
* @param string $key Identifier for the data.
|
||||
* @param mixed $value Data to be cached - anything except a resource.
|
||||
* @param string $config Optional string configuration name to write to. Defaults to 'default'.
|
||||
* @return bool True if the data was successfully cached, false on failure.
|
||||
* Or if the key existed already.
|
||||
*/
|
||||
public static function add($key, $value, $config = 'default')
|
||||
{
|
||||
$pool = static::pool($config);
|
||||
if (is_resource($value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $pool->add($key, $value);
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.2.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache;
|
||||
|
||||
use Cake\Core\InstanceConfigTrait;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Storage engine for CakePHP caching
|
||||
*/
|
||||
abstract class CacheEngine
|
||||
{
|
||||
use InstanceConfigTrait;
|
||||
|
||||
/**
|
||||
* The default cache configuration is overridden in most cache adapters. These are
|
||||
* the keys that are common to all adapters. If overridden, this property is not used.
|
||||
*
|
||||
* - `duration` Specify how long items in this cache configuration last.
|
||||
* - `groups` List of groups or 'tags' associated to every key stored in this config.
|
||||
* handy for deleting a complete group from cache.
|
||||
* - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
|
||||
* with either another cache config or another application.
|
||||
* - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
|
||||
* cache::gc from ever being called automatically.
|
||||
* - `warnOnWriteFailures` Some engines, such as ApcuEngine, may raise warnings on
|
||||
* write failures.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'duration' => 3600,
|
||||
'groups' => [],
|
||||
'prefix' => 'cake_',
|
||||
'probability' => 100,
|
||||
'warnOnWriteFailures' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* Contains the compiled string with all groups
|
||||
* prefixes to be prepended to every key in this cache engine
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $_groupPrefix;
|
||||
|
||||
/**
|
||||
* Initialize the cache engine
|
||||
*
|
||||
* Called automatically by the cache frontend. Merge the runtime config with the defaults
|
||||
* before use.
|
||||
*
|
||||
* @param array $config Associative array of parameters for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
$this->setConfig($config);
|
||||
|
||||
if (!empty($this->_config['groups'])) {
|
||||
sort($this->_config['groups']);
|
||||
$this->_groupPrefix = str_repeat('%s_', count($this->_config['groups']));
|
||||
}
|
||||
if (!is_numeric($this->_config['duration'])) {
|
||||
$this->_config['duration'] = strtotime($this->_config['duration']) - time();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Garbage collection
|
||||
*
|
||||
* Permanently remove all expired and deleted data
|
||||
*
|
||||
* @param int|null $expires [optional] An expires timestamp, invalidating all data before.
|
||||
* @return void
|
||||
*/
|
||||
public function gc($expires = null)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Write value for a key into cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
abstract public function write($key, $value);
|
||||
|
||||
/**
|
||||
* Write data for many keys into cache
|
||||
*
|
||||
* @param array $data An array of data to be stored in the cache
|
||||
* @return array of bools for each key provided, true if the data was successfully cached, false on failure
|
||||
*/
|
||||
public function writeMany($data)
|
||||
{
|
||||
$return = [];
|
||||
foreach ($data as $key => $value) {
|
||||
$return[$key] = $this->write($key, $value);
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
|
||||
*/
|
||||
abstract public function read($key);
|
||||
|
||||
/**
|
||||
* Read multiple keys from the cache
|
||||
*
|
||||
* @param array $keys An array of identifiers for the data
|
||||
* @return array For each cache key (given as the array key) the cache data associated or false if the data doesn't
|
||||
* exist, has expired, or if there was an error fetching it
|
||||
*/
|
||||
public function readMany($keys)
|
||||
{
|
||||
$return = [];
|
||||
foreach ($keys as $key) {
|
||||
$return[$key] = $this->read($key);
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment a number under the key and return incremented value
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to add
|
||||
* @return bool|int New incremented value, false otherwise
|
||||
*/
|
||||
abstract public function increment($key, $offset = 1);
|
||||
|
||||
/**
|
||||
* Decrement a number under the key and return decremented value
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return bool|int New incremented value, false otherwise
|
||||
*/
|
||||
abstract public function decrement($key, $offset = 1);
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
abstract public function delete($key);
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache
|
||||
*
|
||||
* @param bool $check if true will check expiration, otherwise delete all
|
||||
* @return bool True if the cache was successfully cleared, false otherwise
|
||||
*/
|
||||
abstract public function clear($check);
|
||||
|
||||
/**
|
||||
* Deletes keys from the cache
|
||||
*
|
||||
* @param array $keys An array of identifiers for the data
|
||||
* @return array For each provided cache key (given back as the array key) true if the value was successfully deleted,
|
||||
* false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
public function deleteMany($keys)
|
||||
{
|
||||
$return = [];
|
||||
foreach ($keys as $key) {
|
||||
$return[$key] = $this->delete($key);
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a key to the cache if it does not already exist.
|
||||
*
|
||||
* Defaults to a non-atomic implementation. Subclasses should
|
||||
* prefer atomic implementations.
|
||||
*
|
||||
* @param string $key Identifier for the data.
|
||||
* @param mixed $value Data to be cached.
|
||||
* @return bool True if the data was successfully cached, false on failure.
|
||||
*/
|
||||
public function add($key, $value)
|
||||
{
|
||||
$cachedValue = $this->read($key);
|
||||
if ($cachedValue === false) {
|
||||
return $this->write($key, $value);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all values belonging to a group. Is up to the implementing engine
|
||||
* to decide whether actually delete the keys or just simulate it to achieve
|
||||
* the same result.
|
||||
*
|
||||
* @param string $group name of the group to be cleared
|
||||
* @return bool
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does whatever initialization for each group is required
|
||||
* and returns the `group value` for each of them, this is
|
||||
* the token representing each group in the cache key
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
return $this->_config['groups'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a safe key for use with cache engine storage engines.
|
||||
*
|
||||
* @param string $key the key passed over
|
||||
* @return string|false string key or false
|
||||
*/
|
||||
public function key($key)
|
||||
{
|
||||
if (!$key) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$prefix = '';
|
||||
if ($this->_groupPrefix) {
|
||||
$prefix = md5(implode('_', $this->groups()));
|
||||
}
|
||||
|
||||
$key = preg_replace('/[\s]+/', '_', strtolower(trim(str_replace([DIRECTORY_SEPARATOR, '/', '.'], '_', (string)$key))));
|
||||
|
||||
return $prefix . $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a safe key, taking account of the configured key prefix
|
||||
*
|
||||
* @param string $key the key passed over
|
||||
* @return string Key
|
||||
* @throws \InvalidArgumentException If key's value is empty
|
||||
*/
|
||||
protected function _key($key)
|
||||
{
|
||||
$key = $this->key($key);
|
||||
if ($key === false) {
|
||||
throw new InvalidArgumentException('An empty value is not valid as a cache key');
|
||||
}
|
||||
|
||||
return $this->_config['prefix'] . $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache Engines may trigger warnings if they encounter failures during operation,
|
||||
* if option warnOnWriteFailures is set to true.
|
||||
*
|
||||
* @param string $message The warning message.
|
||||
* @return void
|
||||
*/
|
||||
protected function warning($message)
|
||||
{
|
||||
if ($this->getConfig('warnOnWriteFailures') !== true) {
|
||||
return;
|
||||
}
|
||||
|
||||
triggerWarning($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.7.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache;
|
||||
|
||||
/**
|
||||
* Interface for cache engines that defines methods
|
||||
* outside of the PSR16 interface that are used by `Cache`.
|
||||
*
|
||||
* Internally Cache uses this interface when calling engine
|
||||
* methods.
|
||||
*
|
||||
* @since 3.7.0
|
||||
*/
|
||||
interface CacheEngineInterface
|
||||
{
|
||||
/**
|
||||
* Write data for key into a cache engine if it doesn't exist already.
|
||||
*
|
||||
* @param string $key Identifier for the data.
|
||||
* @param mixed $value Data to be cached - anything except a resource.
|
||||
* @return bool True if the data was successfully cached, false on failure.
|
||||
* Or if the key existed already.
|
||||
*/
|
||||
public function add($key, $value);
|
||||
|
||||
/**
|
||||
* Increment a number under the key and return incremented value
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to add
|
||||
* @return bool|int New incremented value, false otherwise
|
||||
*/
|
||||
public function increment($key, $offset = 1);
|
||||
|
||||
/**
|
||||
* Decrement a number under the key and return decremented value
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return bool|int New incremented value, false otherwise
|
||||
*/
|
||||
public function decrement($key, $offset = 1);
|
||||
|
||||
/**
|
||||
* Clear all values belonging to the named group.
|
||||
*
|
||||
* Each implementation needs to decide whether actually
|
||||
* delete the keys or just augment a group generation value
|
||||
* to achieve the same result.
|
||||
*
|
||||
* @param string $group name of the group to be cleared
|
||||
* @return bool
|
||||
*/
|
||||
public function clearGroup($group);
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache;
|
||||
|
||||
use BadMethodCallException;
|
||||
use Cake\Core\App;
|
||||
use Cake\Core\ObjectRegistry;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* An object registry for cache engines.
|
||||
*
|
||||
* Used by Cake\Cache\Cache to load and manage cache engines.
|
||||
*/
|
||||
class CacheRegistry extends ObjectRegistry
|
||||
{
|
||||
/**
|
||||
* Resolve a cache engine classname.
|
||||
*
|
||||
* Part of the template method for Cake\Core\ObjectRegistry::load()
|
||||
*
|
||||
* @param string $class Partial classname to resolve.
|
||||
* @return string|false Either the correct classname or false.
|
||||
*/
|
||||
protected function _resolveClassName($class)
|
||||
{
|
||||
if (is_object($class)) {
|
||||
return $class;
|
||||
}
|
||||
|
||||
return App::className($class, 'Cache/Engine', 'Engine');
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws an exception when a cache engine is missing.
|
||||
*
|
||||
* Part of the template method for Cake\Core\ObjectRegistry::load()
|
||||
*
|
||||
* @param string $class The classname that is missing.
|
||||
* @param string $plugin The plugin the cache is missing in.
|
||||
* @return void
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
protected function _throwMissingClassError($class, $plugin)
|
||||
{
|
||||
throw new BadMethodCallException(sprintf('Cache engine %s is not available.', $class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the cache engine instance.
|
||||
*
|
||||
* Part of the template method for Cake\Core\ObjectRegistry::load()
|
||||
*
|
||||
* @param string|\Cake\Cache\CacheEngine $class The classname or object to make.
|
||||
* @param string $alias The alias of the object.
|
||||
* @param array $config An array of settings to use for the cache engine.
|
||||
* @return \Cake\Cache\CacheEngine The constructed CacheEngine class.
|
||||
* @throws \RuntimeException when an object doesn't implement the correct interface.
|
||||
*/
|
||||
protected function _create($class, $alias, $config)
|
||||
{
|
||||
if (is_object($class)) {
|
||||
$instance = $class;
|
||||
}
|
||||
|
||||
unset($config['className']);
|
||||
if (!isset($instance)) {
|
||||
$instance = new $class($config);
|
||||
}
|
||||
|
||||
if (!($instance instanceof CacheEngine)) {
|
||||
throw new RuntimeException(
|
||||
'Cache engines must use Cake\Cache\CacheEngine as a base class.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!$instance->init($config)) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Cache engine %s is not properly configured.', get_class($instance))
|
||||
);
|
||||
}
|
||||
|
||||
$config = $instance->getConfig();
|
||||
if (isset($config['probability']) && time() % $config['probability'] === 0) {
|
||||
$instance->gc();
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a single adapter from the registry.
|
||||
*
|
||||
* @param string $name The adapter name.
|
||||
* @return void
|
||||
*/
|
||||
public function unload($name)
|
||||
{
|
||||
unset($this->_loaded[$name]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.2.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
// @deprecated 3.6.0 Add backwards compat alias.
|
||||
class_alias('Cake\Cache\Engine\ApcuEngine', 'Cake\Cache\Engine\ApcEngine');
|
||||
|
||||
deprecationWarning('Use Cake\Cache\Engine\ApcuEngine instead of Cake\Cache\Engine\ApcEngine.');
|
||||
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.5.4
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use APCuIterator;
|
||||
use Cake\Cache\CacheEngine;
|
||||
|
||||
/**
|
||||
* APCu storage engine for cache
|
||||
*/
|
||||
class ApcuEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* Contains the compiled group names
|
||||
* (prefixed with the global configuration prefix)
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $_compiledGroupNames = [];
|
||||
|
||||
/**
|
||||
* Initialize the Cache Engine
|
||||
*
|
||||
* Called automatically by the cache frontend
|
||||
*
|
||||
* @param array $config array of setting for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
if (!extension_loaded('apcu')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::init($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
* @link https://secure.php.net/manual/en/function.apcu-store.php
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
$duration = $this->_config['duration'];
|
||||
|
||||
return apcu_store($key, $value, $duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist,
|
||||
* has expired, or if there was an error fetching it
|
||||
* @link https://secure.php.net/manual/en/function.apcu-fetch.php
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return apcu_fetch($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to increment
|
||||
* @return int|false New incremented value, false otherwise
|
||||
* @link https://secure.php.net/manual/en/function.apcu-inc.php
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return apcu_inc($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return int|false New decremented value, false otherwise
|
||||
* @link https://secure.php.net/manual/en/function.apcu-dec.php
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return apcu_dec($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
* @link https://secure.php.net/manual/en/function.apcu-delete.php
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return apcu_delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache. This will clear every cache config using APC.
|
||||
*
|
||||
* @param bool $check If true, nothing will be cleared, as entries are removed
|
||||
* from APC as they expired. This flag is really only used by FileEngine.
|
||||
* @return bool True Returns true.
|
||||
* @link https://secure.php.net/manual/en/function.apcu-cache-info.php
|
||||
* @link https://secure.php.net/manual/en/function.apcu-delete.php
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
if ($check) {
|
||||
return true;
|
||||
}
|
||||
if (class_exists('APCuIterator', false)) {
|
||||
$iterator = new APCuIterator(
|
||||
'/^' . preg_quote($this->_config['prefix'], '/') . '/',
|
||||
APC_ITER_NONE
|
||||
);
|
||||
apcu_delete($iterator);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$cache = apcu_cache_info(); // Raises warning by itself already
|
||||
foreach ($cache['cache_list'] as $key) {
|
||||
if (strpos($key['info'], $this->_config['prefix']) === 0) {
|
||||
apcu_delete($key['info']);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache if it doesn't exist already.
|
||||
* If it already exists, it fails and returns false.
|
||||
*
|
||||
* @param string $key Identifier for the data.
|
||||
* @param mixed $value Data to be cached.
|
||||
* @return bool True if the data was successfully cached, false on failure.
|
||||
* @link https://secure.php.net/manual/en/function.apcu-add.php
|
||||
*/
|
||||
public function add($key, $value)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
$duration = $this->_config['duration'];
|
||||
|
||||
return apcu_add($key, $value, $duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `group value` for each of the configured groups
|
||||
* If the group initial value was not found, then it initializes
|
||||
* the group accordingly.
|
||||
*
|
||||
* @return string[]
|
||||
* @link https://secure.php.net/manual/en/function.apcu-fetch.php
|
||||
* @link https://secure.php.net/manual/en/function.apcu-store.php
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
if (empty($this->_compiledGroupNames)) {
|
||||
foreach ($this->_config['groups'] as $group) {
|
||||
$this->_compiledGroupNames[] = $this->_config['prefix'] . $group;
|
||||
}
|
||||
}
|
||||
|
||||
$success = false;
|
||||
$groups = apcu_fetch($this->_compiledGroupNames, $success);
|
||||
if ($success && count($groups) !== count($this->_config['groups'])) {
|
||||
foreach ($this->_compiledGroupNames as $group) {
|
||||
if (!isset($groups[$group])) {
|
||||
$value = 1;
|
||||
if (apcu_store($group, $value) === false) {
|
||||
$this->warning(
|
||||
sprintf('Failed to store key "%s" with value "%s" into APCu cache.', $group, $value)
|
||||
);
|
||||
}
|
||||
$groups[$group] = $value;
|
||||
}
|
||||
}
|
||||
ksort($groups);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$groups = array_values($groups);
|
||||
foreach ($this->_config['groups'] as $i => $group) {
|
||||
$result[] = $group . $groups[$i];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the group value to simulate deletion of all keys under a group
|
||||
* old values will remain in storage until they expire.
|
||||
*
|
||||
* @param string $group The group to clear.
|
||||
* @return bool success
|
||||
* @link https://secure.php.net/manual/en/function.apcu-inc.php
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
$success = false;
|
||||
apcu_inc($this->_config['prefix'] . $group, 1, $success);
|
||||
|
||||
return $success;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.7.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
|
||||
/**
|
||||
* Array storage engine for cache.
|
||||
*
|
||||
* Not actually a persistent cache engine. All data is only
|
||||
* stored in memory for the duration of a single process. While not
|
||||
* useful in production settings this engine can be useful in tests
|
||||
* or console tools where you don't want the overhead of interacting
|
||||
* with a cache servers, but want the work saving properties a cache
|
||||
* provides.
|
||||
*/
|
||||
class ArrayEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* Cached data.
|
||||
*
|
||||
* Structured as [key => [exp => expiration, val => value]]
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $data = [];
|
||||
|
||||
/**
|
||||
* Write data for key into cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
$expires = time() + $this->_config['duration'];
|
||||
$this->data[$key] = ['exp' => $expires, 'val' => $value];
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist,
|
||||
* has expired, or if there was an error fetching it
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
if (!isset($this->data[$key])) {
|
||||
return false;
|
||||
}
|
||||
$data = $this->data[$key];
|
||||
|
||||
// Check expiration
|
||||
$now = time();
|
||||
if ($data['exp'] <= $now) {
|
||||
unset($this->data[$key]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $data['val'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to increment
|
||||
* @return int|false New incremented value, false otherwise
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
if (!$this->read($key)) {
|
||||
$this->write($key, 0);
|
||||
}
|
||||
$key = $this->_key($key);
|
||||
$this->data[$key]['val'] += $offset;
|
||||
|
||||
return $this->data[$key]['val'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return int|false New decremented value, false otherwise
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
if (!$this->read($key)) {
|
||||
$this->write($key, 0);
|
||||
}
|
||||
$key = $this->_key($key);
|
||||
$this->data[$key]['val'] -= $offset;
|
||||
|
||||
return $this->data[$key]['val'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
unset($this->data[$key]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache. This will clear every cache config using APC.
|
||||
*
|
||||
* @param bool $check Unused argument required by interface.
|
||||
* @return bool True Returns true.
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
$this->data = [];
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `group value` for each of the configured groups
|
||||
* If the group initial value was not found, then it initializes
|
||||
* the group accordingly.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
$result = [];
|
||||
foreach ($this->_config['groups'] as $group) {
|
||||
$key = $this->_config['prefix'] . $group;
|
||||
if (!isset($this->data[$key])) {
|
||||
$this->data[$key] = ['exp' => PHP_INT_MAX, 'val' => 1];
|
||||
}
|
||||
$value = $this->data[$key]['val'];
|
||||
$result[] = $group . $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the group value to simulate deletion of all keys under a group
|
||||
* old values will remain in storage until they expire.
|
||||
*
|
||||
* @param string $group The group to clear.
|
||||
* @return bool success
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
$key = $this->_config['prefix'] . $group;
|
||||
if (isset($this->data[$key])) {
|
||||
$this->data[$key]['val'] += 1;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.2.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
use Cake\Utility\Inflector;
|
||||
use CallbackFilterIterator;
|
||||
use Exception;
|
||||
use LogicException;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use SplFileInfo;
|
||||
use SplFileObject;
|
||||
|
||||
/**
|
||||
* File Storage engine for cache. Filestorage is the slowest cache storage
|
||||
* to read and write. However, it is good for servers that don't have other storage
|
||||
* engine available, or have content which is not performance sensitive.
|
||||
*
|
||||
* You can configure a FileEngine cache, using Cache::config()
|
||||
*/
|
||||
class FileEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* Instance of SplFileObject class
|
||||
*
|
||||
* @var \SplFileObject|null
|
||||
*/
|
||||
protected $_File;
|
||||
|
||||
/**
|
||||
* The default config used unless overridden by runtime configuration
|
||||
*
|
||||
* - `duration` Specify how long items in this cache configuration last.
|
||||
* - `groups` List of groups or 'tags' associated to every key stored in this config.
|
||||
* handy for deleting a complete group from cache.
|
||||
* - `isWindows` Automatically populated with whether the host is windows or not
|
||||
* - `lock` Used by FileCache. Should files be locked before writing to them?
|
||||
* - `mask` The mask used for created files
|
||||
* - `path` Path to where cachefiles should be saved. Defaults to system's temp dir.
|
||||
* - `prefix` Prepended to all entries. Good for when you need to share a keyspace
|
||||
* with either another cache config or another application.
|
||||
* - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
|
||||
* cache::gc from ever being called automatically.
|
||||
* - `serialize` Should cache objects be serialized first.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'duration' => 3600,
|
||||
'groups' => [],
|
||||
'isWindows' => false,
|
||||
'lock' => true,
|
||||
'mask' => 0664,
|
||||
'path' => null,
|
||||
'prefix' => 'cake_',
|
||||
'probability' => 100,
|
||||
'serialize' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* True unless FileEngine::__active(); fails
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_init = true;
|
||||
|
||||
/**
|
||||
* Initialize File Cache Engine
|
||||
*
|
||||
* Called automatically by the cache frontend.
|
||||
*
|
||||
* @param array $config array of setting for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
parent::init($config);
|
||||
|
||||
if ($this->_config['path'] === null) {
|
||||
$this->_config['path'] = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cake_cache' . DIRECTORY_SEPARATOR;
|
||||
}
|
||||
if (DIRECTORY_SEPARATOR === '\\') {
|
||||
$this->_config['isWindows'] = true;
|
||||
}
|
||||
if (substr($this->_config['path'], -1) !== DIRECTORY_SEPARATOR) {
|
||||
$this->_config['path'] .= DIRECTORY_SEPARATOR;
|
||||
}
|
||||
if ($this->_groupPrefix) {
|
||||
$this->_groupPrefix = str_replace('_', DIRECTORY_SEPARATOR, $this->_groupPrefix);
|
||||
}
|
||||
|
||||
return $this->_active();
|
||||
}
|
||||
|
||||
/**
|
||||
* Garbage collection. Permanently remove all expired and deleted data
|
||||
*
|
||||
* @param int|null $expires [optional] An expires timestamp, invalidating all data before.
|
||||
* @return bool True if garbage collection was successful, false on failure
|
||||
*/
|
||||
public function gc($expires = null)
|
||||
{
|
||||
return $this->clear(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $data Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
public function write($key, $data)
|
||||
{
|
||||
if ($data === '' || !$this->_init) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$key = $this->_key($key);
|
||||
|
||||
if ($this->_setKey($key, true) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$lineBreak = "\n";
|
||||
|
||||
if ($this->_config['isWindows']) {
|
||||
$lineBreak = "\r\n";
|
||||
}
|
||||
|
||||
if (!empty($this->_config['serialize'])) {
|
||||
if ($this->_config['isWindows']) {
|
||||
$data = str_replace('\\', '\\\\\\\\', serialize($data));
|
||||
} else {
|
||||
$data = serialize($data);
|
||||
}
|
||||
}
|
||||
|
||||
$duration = $this->_config['duration'];
|
||||
$expires = time() + $duration;
|
||||
$contents = implode([$expires, $lineBreak, $data, $lineBreak]);
|
||||
|
||||
if ($this->_config['lock']) {
|
||||
$this->_File->flock(LOCK_EX);
|
||||
}
|
||||
|
||||
$this->_File->rewind();
|
||||
$success = $this->_File->ftruncate(0) &&
|
||||
$this->_File->fwrite($contents) &&
|
||||
$this->_File->fflush();
|
||||
|
||||
if ($this->_config['lock']) {
|
||||
$this->_File->flock(LOCK_UN);
|
||||
}
|
||||
$this->_File = null;
|
||||
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist, has
|
||||
* expired, or if there was an error fetching it
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
if (!$this->_init || $this->_setKey($key) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->_config['lock']) {
|
||||
$this->_File->flock(LOCK_SH);
|
||||
}
|
||||
|
||||
$this->_File->rewind();
|
||||
$time = time();
|
||||
$cachetime = (int)$this->_File->current();
|
||||
|
||||
if ($cachetime < $time) {
|
||||
if ($this->_config['lock']) {
|
||||
$this->_File->flock(LOCK_UN);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = '';
|
||||
$this->_File->next();
|
||||
while ($this->_File->valid()) {
|
||||
$data .= $this->_File->current();
|
||||
$this->_File->next();
|
||||
}
|
||||
|
||||
if ($this->_config['lock']) {
|
||||
$this->_File->flock(LOCK_UN);
|
||||
}
|
||||
|
||||
$data = trim($data);
|
||||
|
||||
if ($data !== '' && !empty($this->_config['serialize'])) {
|
||||
if ($this->_config['isWindows']) {
|
||||
$data = str_replace('\\\\\\\\', '\\', $data);
|
||||
}
|
||||
$data = unserialize((string)$data);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't
|
||||
* exist or couldn't be removed
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
if ($this->_setKey($key) === false || !$this->_init) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$path = $this->_File->getRealPath();
|
||||
$this->_File = null;
|
||||
|
||||
//@codingStandardsIgnoreStart
|
||||
return @unlink($path);
|
||||
//@codingStandardsIgnoreEnd
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all values from the cache
|
||||
*
|
||||
* @param bool $check Optional - only delete expired cache items
|
||||
* @return bool True if the cache was successfully cleared, false otherwise
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
if (!$this->_init) {
|
||||
return false;
|
||||
}
|
||||
$this->_File = null;
|
||||
|
||||
$threshold = $now = false;
|
||||
if ($check) {
|
||||
$now = time();
|
||||
$threshold = $now - $this->_config['duration'];
|
||||
}
|
||||
|
||||
$this->_clearDirectory($this->_config['path'], $now, $threshold);
|
||||
|
||||
$directory = new RecursiveDirectoryIterator(
|
||||
$this->_config['path'],
|
||||
\FilesystemIterator::SKIP_DOTS
|
||||
);
|
||||
$contents = new RecursiveIteratorIterator(
|
||||
$directory,
|
||||
RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
$cleared = [];
|
||||
foreach ($contents as $path) {
|
||||
if ($path->isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$path = $path->getRealPath() . DIRECTORY_SEPARATOR;
|
||||
if (!in_array($path, $cleared, true)) {
|
||||
$this->_clearDirectory($path, $now, $threshold);
|
||||
$cleared[] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to clear a directory of matching files.
|
||||
*
|
||||
* @param string $path The path to search.
|
||||
* @param int $now The current timestamp
|
||||
* @param int $threshold Any file not modified after this value will be deleted.
|
||||
* @return void
|
||||
*/
|
||||
protected function _clearDirectory($path, $now, $threshold)
|
||||
{
|
||||
if (!is_dir($path)) {
|
||||
return;
|
||||
}
|
||||
$prefixLength = strlen($this->_config['prefix']);
|
||||
|
||||
$dir = dir($path);
|
||||
while (($entry = $dir->read()) !== false) {
|
||||
if (substr($entry, 0, $prefixLength) !== $this->_config['prefix']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$file = new SplFileObject($path . $entry, 'r');
|
||||
} catch (Exception $e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($threshold) {
|
||||
$mtime = $file->getMTime();
|
||||
if ($mtime > $threshold) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$expires = (int)$file->current();
|
||||
if ($expires > $now) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ($file->isFile()) {
|
||||
$filePath = $file->getRealPath();
|
||||
$file = null;
|
||||
|
||||
//@codingStandardsIgnoreStart
|
||||
@unlink($filePath);
|
||||
//@codingStandardsIgnoreEnd
|
||||
}
|
||||
}
|
||||
|
||||
$dir->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Not implemented
|
||||
*
|
||||
* @param string $key The key to decrement
|
||||
* @param int $offset The number to offset
|
||||
* @return void
|
||||
* @throws \LogicException
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
throw new LogicException('Files cannot be atomically decremented.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Not implemented
|
||||
*
|
||||
* @param string $key The key to increment
|
||||
* @param int $offset The number to offset
|
||||
* @return void
|
||||
* @throws \LogicException
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
throw new LogicException('Files cannot be atomically incremented.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current cache key this class is managing, and creates a writable SplFileObject
|
||||
* for the cache file the key is referring to.
|
||||
*
|
||||
* @param string $key The key
|
||||
* @param bool $createKey Whether the key should be created if it doesn't exists, or not
|
||||
* @return bool true if the cache key could be set, false otherwise
|
||||
*/
|
||||
protected function _setKey($key, $createKey = false)
|
||||
{
|
||||
$groups = null;
|
||||
if ($this->_groupPrefix) {
|
||||
$groups = vsprintf($this->_groupPrefix, $this->groups());
|
||||
}
|
||||
$dir = $this->_config['path'] . $groups;
|
||||
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0775, true);
|
||||
}
|
||||
|
||||
$path = new SplFileInfo($dir . $key);
|
||||
|
||||
if (!$createKey && !$path->isFile()) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
empty($this->_File) ||
|
||||
$this->_File->getBasename() !== $key ||
|
||||
$this->_File->valid() === false
|
||||
) {
|
||||
$exists = file_exists($path->getPathname());
|
||||
try {
|
||||
$this->_File = $path->openFile('c+');
|
||||
} catch (Exception $e) {
|
||||
trigger_error($e->getMessage(), E_USER_WARNING);
|
||||
|
||||
return false;
|
||||
}
|
||||
unset($path);
|
||||
|
||||
if (!$exists && !chmod($this->_File->getPathname(), (int)$this->_config['mask'])) {
|
||||
trigger_error(sprintf(
|
||||
'Could not apply permission mask "%s" on cache file "%s"',
|
||||
$this->_File->getPathname(),
|
||||
$this->_config['mask']
|
||||
), E_USER_WARNING);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if cache directory is writable
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function _active()
|
||||
{
|
||||
$dir = new SplFileInfo($this->_config['path']);
|
||||
$path = $dir->getPathname();
|
||||
$success = true;
|
||||
if (!is_dir($path)) {
|
||||
//@codingStandardsIgnoreStart
|
||||
$success = @mkdir($path, 0775, true);
|
||||
//@codingStandardsIgnoreEnd
|
||||
}
|
||||
|
||||
$isWritableDir = ($dir->isDir() && $dir->isWritable());
|
||||
if (!$success || ($this->_init && !$isWritableDir)) {
|
||||
$this->_init = false;
|
||||
trigger_error(sprintf(
|
||||
'%s is not writable',
|
||||
$this->_config['path']
|
||||
), E_USER_WARNING);
|
||||
}
|
||||
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a safe key for use with cache engine storage engines.
|
||||
*
|
||||
* @param string $key the key passed over
|
||||
* @return mixed string $key or false
|
||||
*/
|
||||
public function key($key)
|
||||
{
|
||||
if (empty($key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$key = Inflector::underscore(str_replace(
|
||||
[DIRECTORY_SEPARATOR, '/', '.', '<', '>', '?', ':', '|', '*', '"'],
|
||||
'_',
|
||||
(string)$key
|
||||
));
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively deletes all files under any directory named as $group
|
||||
*
|
||||
* @param string $group The group to clear.
|
||||
* @return bool success
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
$this->_File = null;
|
||||
|
||||
$prefix = (string)$this->_config['prefix'];
|
||||
|
||||
$directoryIterator = new RecursiveDirectoryIterator($this->_config['path']);
|
||||
$contents = new RecursiveIteratorIterator(
|
||||
$directoryIterator,
|
||||
RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
$filtered = new CallbackFilterIterator(
|
||||
$contents,
|
||||
function (SplFileInfo $current) use ($group, $prefix) {
|
||||
if (!$current->isFile()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$hasPrefix = $prefix === ''
|
||||
|| strpos($current->getBasename(), $prefix) === 0;
|
||||
if ($hasPrefix === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$pos = strpos(
|
||||
$current->getPathname(),
|
||||
DIRECTORY_SEPARATOR . $group . DIRECTORY_SEPARATOR
|
||||
);
|
||||
|
||||
return $pos !== false;
|
||||
}
|
||||
);
|
||||
foreach ($filtered as $object) {
|
||||
$path = $object->getPathname();
|
||||
$object = null;
|
||||
// @codingStandardsIgnoreLine
|
||||
@unlink($path);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.5.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
use InvalidArgumentException;
|
||||
use Memcached;
|
||||
|
||||
/**
|
||||
* Memcached storage engine for cache. Memcached has some limitations in the amount of
|
||||
* control you have over expire times far in the future. See MemcachedEngine::write() for
|
||||
* more information.
|
||||
*
|
||||
* Memcached engine supports binary protocol and igbinary
|
||||
* serialization (if memcached extension is compiled with --enable-igbinary).
|
||||
* Compressed keys can also be incremented/decremented.
|
||||
*/
|
||||
class MemcachedEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* memcached wrapper.
|
||||
*
|
||||
* @var \Memcached
|
||||
*/
|
||||
protected $_Memcached;
|
||||
|
||||
/**
|
||||
* The default config used unless overridden by runtime configuration
|
||||
*
|
||||
* - `compress` Whether to compress data
|
||||
* - `duration` Specify how long items in this cache configuration last.
|
||||
* - `groups` List of groups or 'tags' associated to every key stored in this config.
|
||||
* handy for deleting a complete group from cache.
|
||||
* - `username` Login to access the Memcache server
|
||||
* - `password` Password to access the Memcache server
|
||||
* - `persistent` The name of the persistent connection. All configurations using
|
||||
* the same persistent value will share a single underlying connection.
|
||||
* - `prefix` Prepended to all entries. Good for when you need to share a keyspace
|
||||
* with either another cache config or another application.
|
||||
* - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
|
||||
* cache::gc from ever being called automatically.
|
||||
* - `serialize` The serializer engine used to serialize data. Available engines are php,
|
||||
* igbinary and json. Beside php, the memcached extension must be compiled with the
|
||||
* appropriate serializer support.
|
||||
* - `servers` String or array of memcached servers. If an array MemcacheEngine will use
|
||||
* them as a pool.
|
||||
* - `options` - Additional options for the memcached client. Should be an array of option => value.
|
||||
* Use the \Memcached::OPT_* constants as keys.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'compress' => false,
|
||||
'duration' => 3600,
|
||||
'groups' => [],
|
||||
'host' => null,
|
||||
'username' => null,
|
||||
'password' => null,
|
||||
'persistent' => false,
|
||||
'port' => null,
|
||||
'prefix' => 'cake_',
|
||||
'probability' => 100,
|
||||
'serialize' => 'php',
|
||||
'servers' => ['127.0.0.1'],
|
||||
'options' => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* List of available serializer engines
|
||||
*
|
||||
* Memcached must be compiled with json and igbinary support to use these engines
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_serializers = [];
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
protected $_compiledGroupNames = [];
|
||||
|
||||
/**
|
||||
* Initialize the Cache Engine
|
||||
*
|
||||
* Called automatically by the cache frontend
|
||||
*
|
||||
* @param array $config array of setting for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
* @throws \InvalidArgumentException When you try use authentication without
|
||||
* Memcached compiled with SASL support
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
if (!extension_loaded('memcached')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->_serializers = [
|
||||
'igbinary' => Memcached::SERIALIZER_IGBINARY,
|
||||
'json' => Memcached::SERIALIZER_JSON,
|
||||
'php' => Memcached::SERIALIZER_PHP,
|
||||
];
|
||||
if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
|
||||
$this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
|
||||
}
|
||||
|
||||
parent::init($config);
|
||||
|
||||
if (!empty($config['host'])) {
|
||||
if (empty($config['port'])) {
|
||||
$config['servers'] = [$config['host']];
|
||||
} else {
|
||||
$config['servers'] = [sprintf('%s:%d', $config['host'], $config['port'])];
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($config['servers'])) {
|
||||
$this->setConfig('servers', $config['servers'], false);
|
||||
}
|
||||
|
||||
if (!is_array($this->_config['servers'])) {
|
||||
$this->_config['servers'] = [$this->_config['servers']];
|
||||
}
|
||||
|
||||
if (isset($this->_Memcached)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->_config['persistent']) {
|
||||
$this->_Memcached = new Memcached((string)$this->_config['persistent']);
|
||||
} else {
|
||||
$this->_Memcached = new Memcached();
|
||||
}
|
||||
$this->_setOptions();
|
||||
|
||||
if (count($this->_Memcached->getServerList())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$servers = [];
|
||||
foreach ($this->_config['servers'] as $server) {
|
||||
$servers[] = $this->parseServerString($server);
|
||||
}
|
||||
|
||||
if (!$this->_Memcached->addServers($servers)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_array($this->_config['options'])) {
|
||||
foreach ($this->_config['options'] as $opt => $value) {
|
||||
$this->_Memcached->setOption($opt, $value);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($this->_config['username']) && !empty($this->_config['login'])) {
|
||||
throw new InvalidArgumentException(
|
||||
'Please pass "username" instead of "login" for connecting to Memcached'
|
||||
);
|
||||
}
|
||||
|
||||
if ($this->_config['username'] !== null && $this->_config['password'] !== null) {
|
||||
if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
|
||||
throw new InvalidArgumentException(
|
||||
'Memcached extension is not built with SASL support'
|
||||
);
|
||||
}
|
||||
$this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
|
||||
$this->_Memcached->setSaslAuthData(
|
||||
$this->_config['username'],
|
||||
$this->_config['password']
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings the memcached instance
|
||||
*
|
||||
* @return void
|
||||
* @throws \InvalidArgumentException When the Memcached extension is not built
|
||||
* with the desired serializer engine.
|
||||
*/
|
||||
protected function _setOptions()
|
||||
{
|
||||
$this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
|
||||
|
||||
$serializer = strtolower($this->_config['serialize']);
|
||||
if (!isset($this->_serializers[$serializer])) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('%s is not a valid serializer engine for Memcached', $serializer)
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
$serializer !== 'php' &&
|
||||
!constant('Memcached::HAVE_' . strtoupper($serializer))
|
||||
) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('Memcached extension is not compiled with %s support', $serializer)
|
||||
);
|
||||
}
|
||||
|
||||
$this->_Memcached->setOption(
|
||||
Memcached::OPT_SERIALIZER,
|
||||
$this->_serializers[$serializer]
|
||||
);
|
||||
|
||||
// Check for Amazon ElastiCache instance
|
||||
if (
|
||||
defined('Memcached::OPT_CLIENT_MODE') &&
|
||||
defined('Memcached::DYNAMIC_CLIENT_MODE')
|
||||
) {
|
||||
$this->_Memcached->setOption(
|
||||
Memcached::OPT_CLIENT_MODE,
|
||||
Memcached::DYNAMIC_CLIENT_MODE
|
||||
);
|
||||
}
|
||||
|
||||
$this->_Memcached->setOption(
|
||||
Memcached::OPT_COMPRESSION,
|
||||
(bool)$this->_config['compress']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the server address into the host/port. Handles both IPv6 and IPv4
|
||||
* addresses and Unix sockets
|
||||
*
|
||||
* @param string $server The server address string.
|
||||
* @return array Array containing host, port
|
||||
*/
|
||||
public function parseServerString($server)
|
||||
{
|
||||
$socketTransport = 'unix://';
|
||||
if (strpos($server, $socketTransport) === 0) {
|
||||
return [substr($server, strlen($socketTransport)), 0];
|
||||
}
|
||||
if (substr($server, 0, 1) === '[') {
|
||||
$position = strpos($server, ']:');
|
||||
if ($position !== false) {
|
||||
$position++;
|
||||
}
|
||||
} else {
|
||||
$position = strpos($server, ':');
|
||||
}
|
||||
$port = 11211;
|
||||
$host = $server;
|
||||
if ($position !== false) {
|
||||
$host = substr($server, 0, $position);
|
||||
$port = substr($server, $position + 1);
|
||||
}
|
||||
|
||||
return [$host, (int)$port];
|
||||
}
|
||||
|
||||
/**
|
||||
* Backwards compatible alias of parseServerString
|
||||
*
|
||||
* @param string $server The server address string.
|
||||
* @return array Array containing host, port
|
||||
* @deprecated 3.4.13 Will be removed in 4.0.0
|
||||
*/
|
||||
protected function _parseServerString($server)
|
||||
{
|
||||
return $this->parseServerString($server);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an option value from the memcached connection.
|
||||
*
|
||||
* @param string $name The option name to read.
|
||||
* @return string|int|bool|null
|
||||
*/
|
||||
public function getOption($name)
|
||||
{
|
||||
return $this->_Memcached->getOption($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache. When using memcached as your cache engine
|
||||
* remember that the Memcached pecl extension does not support cache expiry
|
||||
* times greater than 30 days in the future. Any duration greater than 30 days
|
||||
* will be treated as never expiring.
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
* @see https://secure.php.net/manual/en/memcache.set.php
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
$duration = $this->_config['duration'];
|
||||
if ($duration > 30 * DAY) {
|
||||
$duration = 0;
|
||||
}
|
||||
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Memcached->set($key, $value, $duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write many cache entries to the cache at once
|
||||
*
|
||||
* @param array $data An array of data to be stored in the cache
|
||||
* @return array of bools for each key provided, true if the data was
|
||||
* successfully cached, false on failure
|
||||
*/
|
||||
public function writeMany($data)
|
||||
{
|
||||
$cacheData = [];
|
||||
foreach ($data as $key => $value) {
|
||||
$cacheData[$this->_key($key)] = $value;
|
||||
}
|
||||
|
||||
$success = $this->_Memcached->setMulti($cacheData);
|
||||
|
||||
$return = [];
|
||||
foreach (array_keys($data) as $key) {
|
||||
$return[$key] = $success;
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist, has
|
||||
* expired, or if there was an error fetching it.
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Memcached->get($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read many keys from the cache at once
|
||||
*
|
||||
* @param array $keys An array of identifiers for the data
|
||||
* @return array An array containing, for each of the given $keys, the cached data or
|
||||
* false if cached data could not be retrieved.
|
||||
*/
|
||||
public function readMany($keys)
|
||||
{
|
||||
$cacheKeys = [];
|
||||
foreach ($keys as $key) {
|
||||
$cacheKeys[] = $this->_key($key);
|
||||
}
|
||||
|
||||
$values = $this->_Memcached->getMulti($cacheKeys);
|
||||
$return = [];
|
||||
foreach ($keys as &$key) {
|
||||
$return[$key] = array_key_exists($this->_key($key), $values) ?
|
||||
$values[$this->_key($key)] : false;
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to increment
|
||||
* @return int|false New incremented value, false otherwise
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Memcached->increment($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return int|false New decremented value, false otherwise
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Memcached->decrement($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't
|
||||
* exist or couldn't be removed.
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Memcached->delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete many keys from the cache at once
|
||||
*
|
||||
* @param array $keys An array of identifiers for the data
|
||||
* @return array of boolean values that are true if the key was successfully
|
||||
* deleted, false if it didn't exist or couldn't be removed.
|
||||
*/
|
||||
public function deleteMany($keys)
|
||||
{
|
||||
$cacheKeys = [];
|
||||
foreach ($keys as $key) {
|
||||
$cacheKeys[] = $this->_key($key);
|
||||
}
|
||||
|
||||
$success = $this->_Memcached->deleteMulti($cacheKeys);
|
||||
|
||||
$return = [];
|
||||
foreach ($keys as $key) {
|
||||
$return[$key] = $success;
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache
|
||||
*
|
||||
* @param bool $check If true will check expiration, otherwise delete all.
|
||||
* @return bool True if the cache was successfully cleared, false otherwise
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
if ($check) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$keys = $this->_Memcached->getAllKeys();
|
||||
if ($keys === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (strpos($key, $this->_config['prefix']) === 0) {
|
||||
$this->_Memcached->delete($key);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a key to the cache if it does not already exist.
|
||||
*
|
||||
* @param string $key Identifier for the data.
|
||||
* @param mixed $value Data to be cached.
|
||||
* @return bool True if the data was successfully cached, false on failure.
|
||||
*/
|
||||
public function add($key, $value)
|
||||
{
|
||||
$duration = $this->_config['duration'];
|
||||
if ($duration > 30 * DAY) {
|
||||
$duration = 0;
|
||||
}
|
||||
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Memcached->add($key, $value, $duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `group value` for each of the configured groups
|
||||
* If the group initial value was not found, then it initializes
|
||||
* the group accordingly.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
if (empty($this->_compiledGroupNames)) {
|
||||
foreach ($this->_config['groups'] as $group) {
|
||||
$this->_compiledGroupNames[] = $this->_config['prefix'] . $group;
|
||||
}
|
||||
}
|
||||
|
||||
$groups = $this->_Memcached->getMulti($this->_compiledGroupNames) ?: [];
|
||||
if (count($groups) !== count($this->_config['groups'])) {
|
||||
foreach ($this->_compiledGroupNames as $group) {
|
||||
if (!isset($groups[$group])) {
|
||||
$this->_Memcached->set($group, 1, 0);
|
||||
$groups[$group] = 1;
|
||||
}
|
||||
}
|
||||
ksort($groups);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$groups = array_values($groups);
|
||||
foreach ($this->_config['groups'] as $i => $group) {
|
||||
$result[] = $group . $groups[$i];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the group value to simulate deletion of all keys under a group
|
||||
* old values will remain in storage until they expire.
|
||||
*
|
||||
* @param string $group name of the group to be cleared
|
||||
* @return bool success
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
return (bool)$this->_Memcached->increment($this->_config['prefix'] . $group);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
|
||||
/**
|
||||
* Null cache engine, all operations appear to work, but do nothing.
|
||||
*
|
||||
* This is used internally for when Cache::disable() has been called.
|
||||
*/
|
||||
class NullEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function gc($expires = null)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function readMany($keys)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteMany($keys)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.2.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
use Redis;
|
||||
use RedisException;
|
||||
|
||||
/**
|
||||
* Redis storage engine for cache.
|
||||
*/
|
||||
class RedisEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* Redis wrapper.
|
||||
*
|
||||
* @var \Redis
|
||||
*/
|
||||
protected $_Redis;
|
||||
|
||||
/**
|
||||
* The default config used unless overridden by runtime configuration
|
||||
*
|
||||
* - `database` database number to use for connection.
|
||||
* - `duration` Specify how long items in this cache configuration last.
|
||||
* - `groups` List of groups or 'tags' associated to every key stored in this config.
|
||||
* handy for deleting a complete group from cache.
|
||||
* - `password` Redis server password.
|
||||
* - `persistent` Connect to the Redis server with a persistent connection
|
||||
* - `port` port number to the Redis server.
|
||||
* - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
|
||||
* with either another cache config or another application.
|
||||
* - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
|
||||
* cache::gc from ever being called automatically.
|
||||
* - `server` URL or ip to the Redis server host.
|
||||
* - `timeout` timeout in seconds (float).
|
||||
* - `unix_socket` Path to the unix socket file (default: false)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'database' => 0,
|
||||
'duration' => 3600,
|
||||
'groups' => [],
|
||||
'password' => false,
|
||||
'persistent' => true,
|
||||
'port' => 6379,
|
||||
'prefix' => 'cake_',
|
||||
'probability' => 100,
|
||||
'host' => null,
|
||||
'server' => '127.0.0.1',
|
||||
'timeout' => 0,
|
||||
'unix_socket' => false,
|
||||
];
|
||||
|
||||
/**
|
||||
* Initialize the Cache Engine
|
||||
*
|
||||
* Called automatically by the cache frontend
|
||||
*
|
||||
* @param array $config array of setting for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
if (!extension_loaded('redis')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!empty($config['host'])) {
|
||||
$config['server'] = $config['host'];
|
||||
}
|
||||
|
||||
parent::init($config);
|
||||
|
||||
return $this->_connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to a Redis server
|
||||
*
|
||||
* @return bool True if Redis server was connected
|
||||
*/
|
||||
protected function _connect()
|
||||
{
|
||||
try {
|
||||
$this->_Redis = new Redis();
|
||||
if (!empty($this->_config['unix_socket'])) {
|
||||
$return = $this->_Redis->connect($this->_config['unix_socket']);
|
||||
} elseif (empty($this->_config['persistent'])) {
|
||||
$return = $this->_Redis->connect($this->_config['server'], $this->_config['port'], $this->_config['timeout']);
|
||||
} else {
|
||||
$persistentId = $this->_config['port'] . $this->_config['timeout'] . $this->_config['database'];
|
||||
$return = $this->_Redis->pconnect($this->_config['server'], $this->_config['port'], $this->_config['timeout'], $persistentId);
|
||||
}
|
||||
} catch (RedisException $e) {
|
||||
return false;
|
||||
}
|
||||
if ($return && $this->_config['password']) {
|
||||
$return = $this->_Redis->auth($this->_config['password']);
|
||||
}
|
||||
if ($return) {
|
||||
$return = $this->_Redis->select($this->_config['database']);
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache.
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
if (!is_int($value)) {
|
||||
$value = serialize($value);
|
||||
}
|
||||
|
||||
$duration = $this->_config['duration'];
|
||||
if ($duration === 0) {
|
||||
return $this->_Redis->set($key, $value);
|
||||
}
|
||||
|
||||
return $this->_Redis->setEx($key, $duration, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
$value = $this->_Redis->get($key);
|
||||
if (preg_match('/^[-]?\d+$/', $value)) {
|
||||
return (int)$value;
|
||||
}
|
||||
if ($value !== false && is_string($value)) {
|
||||
return unserialize($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of an integer cached key & update the expiry time
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to increment
|
||||
* @return int|false New incremented value, false otherwise
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
$duration = $this->_config['duration'];
|
||||
$key = $this->_key($key);
|
||||
|
||||
$value = (int)$this->_Redis->incrBy($key, $offset);
|
||||
if ($duration > 0) {
|
||||
$this->_Redis->expire($key, $duration);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value of an integer cached key & update the expiry time
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return int|false New decremented value, false otherwise
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
$duration = $this->_config['duration'];
|
||||
$key = $this->_key($key);
|
||||
|
||||
$value = (int)$this->_Redis->decrBy($key, $offset);
|
||||
if ($duration > 0) {
|
||||
$this->_Redis->expire($key, $duration);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return $this->_Redis->del($key) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache
|
||||
*
|
||||
* @param bool $check If true will check expiration, otherwise delete all.
|
||||
* @return bool True if the cache was successfully cleared, false otherwise
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
if ($check) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->_Redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
|
||||
|
||||
$isAllDeleted = true;
|
||||
$iterator = null;
|
||||
$pattern = $this->_config['prefix'] . '*';
|
||||
|
||||
while (true) {
|
||||
$keys = $this->_Redis->scan($iterator, $pattern);
|
||||
|
||||
if ($keys === false) {
|
||||
break;
|
||||
}
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$isDeleted = ($this->_Redis->del($key) > 0);
|
||||
$isAllDeleted = $isAllDeleted && $isDeleted;
|
||||
}
|
||||
}
|
||||
|
||||
return $isAllDeleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache if it doesn't exist already.
|
||||
* If it already exists, it fails and returns false.
|
||||
*
|
||||
* @param string $key Identifier for the data.
|
||||
* @param mixed $value Data to be cached.
|
||||
* @return bool True if the data was successfully cached, false on failure.
|
||||
* @link https://github.com/phpredis/phpredis#set
|
||||
*/
|
||||
public function add($key, $value)
|
||||
{
|
||||
$duration = $this->_config['duration'];
|
||||
$key = $this->_key($key);
|
||||
|
||||
if (!is_int($value)) {
|
||||
$value = serialize($value);
|
||||
}
|
||||
|
||||
if ($this->_Redis->set($key, $value, ['nx', 'ex' => $duration])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `group value` for each of the configured groups
|
||||
* If the group initial value was not found, then it initializes
|
||||
* the group accordingly.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
$result = [];
|
||||
foreach ($this->_config['groups'] as $group) {
|
||||
$value = $this->_Redis->get($this->_config['prefix'] . $group);
|
||||
if (!$value) {
|
||||
$value = 1;
|
||||
$this->_Redis->set($this->_config['prefix'] . $group, $value);
|
||||
}
|
||||
$result[] = $group . $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the group value to simulate deletion of all keys under a group
|
||||
* old values will remain in storage until they expire.
|
||||
*
|
||||
* @param string $group name of the group to be cleared
|
||||
* @return bool success
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
return (bool)$this->_Redis->incr($this->_config['prefix'] . $group);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the redis server
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if (empty($this->_config['persistent']) && $this->_Redis instanceof Redis) {
|
||||
$this->_Redis->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 2.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
|
||||
/**
|
||||
* Wincache storage engine for cache
|
||||
*
|
||||
* Supports wincache 1.1.0 and higher.
|
||||
*/
|
||||
class WincacheEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* Contains the compiled group names
|
||||
* (prefixed with the global configuration prefix)
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_compiledGroupNames = [];
|
||||
|
||||
/**
|
||||
* Initialize the Cache Engine
|
||||
*
|
||||
* Called automatically by the cache frontend
|
||||
*
|
||||
* @param array $config array of setting for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
if (!extension_loaded('wincache')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
parent::init($config);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
$duration = $this->_config['duration'];
|
||||
|
||||
return wincache_ucache_set($key, $value, $duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist,
|
||||
* has expired, or if there was an error fetching it
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return wincache_ucache_get($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to increment
|
||||
* @return int|false New incremented value, false otherwise
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return wincache_ucache_inc($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value of an integer cached key
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return int|false New decremented value, false otherwise
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return wincache_ucache_dec($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return wincache_ucache_delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache. This will clear every
|
||||
* item in the cache matching the cache config prefix.
|
||||
*
|
||||
* @param bool $check If true, nothing will be cleared, as entries will
|
||||
* naturally expire in wincache..
|
||||
* @return bool True Returns true.
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
if ($check) {
|
||||
return true;
|
||||
}
|
||||
$info = wincache_ucache_info();
|
||||
$cacheKeys = $info['ucache_entries'];
|
||||
unset($info);
|
||||
foreach ($cacheKeys as $key) {
|
||||
if (strpos($key['key_name'], $this->_config['prefix']) === 0) {
|
||||
wincache_ucache_delete($key['key_name']);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `group value` for each of the configured groups
|
||||
* If the group initial value was not found, then it initializes
|
||||
* the group accordingly.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
if (empty($this->_compiledGroupNames)) {
|
||||
foreach ($this->_config['groups'] as $group) {
|
||||
$this->_compiledGroupNames[] = $this->_config['prefix'] . $group;
|
||||
}
|
||||
}
|
||||
|
||||
$groups = wincache_ucache_get($this->_compiledGroupNames);
|
||||
if (count($groups) !== count($this->_config['groups'])) {
|
||||
foreach ($this->_compiledGroupNames as $group) {
|
||||
if (!isset($groups[$group])) {
|
||||
wincache_ucache_set($group, 1);
|
||||
$groups[$group] = 1;
|
||||
}
|
||||
}
|
||||
ksort($groups);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$groups = array_values($groups);
|
||||
foreach ($this->_config['groups'] as $i => $group) {
|
||||
$result[] = $group . $groups[$i];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the group value to simulate deletion of all keys under a group
|
||||
* old values will remain in storage until they expire.
|
||||
*
|
||||
* @param string $group The group to clear.
|
||||
* @return bool success
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
$success = false;
|
||||
wincache_ucache_inc($this->_config['prefix'] . $group, 1, $success);
|
||||
|
||||
return $success;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 1.2.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache\Engine;
|
||||
|
||||
use Cake\Cache\CacheEngine;
|
||||
|
||||
/**
|
||||
* Xcache storage engine for cache
|
||||
*
|
||||
* @link http://trac.lighttpd.net/xcache/ Xcache
|
||||
* @deprecated 3.6.0 Xcache engine has been deprecated and will be removed in 4.0.0.
|
||||
*/
|
||||
class XcacheEngine extends CacheEngine
|
||||
{
|
||||
/**
|
||||
* The default config used unless overridden by runtime configuration
|
||||
*
|
||||
* - `duration` Specify how long items in this cache configuration last.
|
||||
* - `groups` List of groups or 'tags' associated to every key stored in this config.
|
||||
* handy for deleting a complete group from cache.
|
||||
* - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
|
||||
* with either another cache config or another application.
|
||||
* - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
|
||||
* cache::gc from ever being called automatically.
|
||||
* - `PHP_AUTH_USER` xcache.admin.user
|
||||
* - `PHP_AUTH_PW` xcache.admin.password
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_defaultConfig = [
|
||||
'duration' => 3600,
|
||||
'groups' => [],
|
||||
'prefix' => null,
|
||||
'probability' => 100,
|
||||
'PHP_AUTH_USER' => 'user',
|
||||
'PHP_AUTH_PW' => 'password',
|
||||
];
|
||||
|
||||
/**
|
||||
* Initialize the Cache Engine
|
||||
*
|
||||
* Called automatically by the cache frontend
|
||||
*
|
||||
* @param array $config array of setting for the engine
|
||||
* @return bool True if the engine has been successfully initialized, false if not
|
||||
*/
|
||||
public function init(array $config = [])
|
||||
{
|
||||
if (!extension_loaded('xcache')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
parent::init($config);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data for key into cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param mixed $value Data to be cached
|
||||
* @return bool True if the data was successfully cached, false on failure
|
||||
*/
|
||||
public function write($key, $value)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
if (!is_numeric($value)) {
|
||||
$value = serialize($value);
|
||||
}
|
||||
|
||||
$duration = $this->_config['duration'];
|
||||
$expires = time() + $duration;
|
||||
xcache_set($key . '_expires', $expires, $duration);
|
||||
|
||||
return xcache_set($key, $value, $duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return mixed The cached data, or false if the data doesn't exist,
|
||||
* has expired, or if there was an error fetching it
|
||||
*/
|
||||
public function read($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
if (xcache_isset($key)) {
|
||||
$time = time();
|
||||
$cachetime = (int)xcache_get($key . '_expires');
|
||||
if ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$value = xcache_get($key);
|
||||
if (is_string($value) && !is_numeric($value)) {
|
||||
$value = unserialize($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the value of an integer cached key
|
||||
* If the cache key is not an integer it will be treated as 0
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to increment
|
||||
* @return int|false New incremented value, false otherwise
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return xcache_inc($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrements the value of an integer cached key.
|
||||
* If the cache key is not an integer it will be treated as 0
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @param int $offset How much to subtract
|
||||
* @return int|false New decremented value, false otherwise
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return xcache_dec($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a key from the cache
|
||||
*
|
||||
* @param string $key Identifier for the data
|
||||
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$key = $this->_key($key);
|
||||
|
||||
return xcache_unset($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all keys from the cache
|
||||
*
|
||||
* @param bool $check If true no deletes will occur and instead CakePHP will rely
|
||||
* on key TTL values.
|
||||
* Unused for Xcache engine.
|
||||
* @return bool True if the cache was successfully cleared, false otherwise
|
||||
*/
|
||||
public function clear($check)
|
||||
{
|
||||
$this->_auth();
|
||||
$max = xcache_count(XC_TYPE_VAR);
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
xcache_clear_cache(XC_TYPE_VAR, $i);
|
||||
}
|
||||
$this->_auth(true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `group value` for each of the configured groups
|
||||
* If the group initial value was not found, then it initializes
|
||||
* the group accordingly.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function groups()
|
||||
{
|
||||
$result = [];
|
||||
foreach ($this->_config['groups'] as $group) {
|
||||
$value = xcache_get($this->_config['prefix'] . $group);
|
||||
if (!$value) {
|
||||
$value = 1;
|
||||
xcache_set($this->_config['prefix'] . $group, $value, 0);
|
||||
}
|
||||
$result[] = $group . $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the group value to simulate deletion of all keys under a group
|
||||
* old values will remain in storage until they expire.
|
||||
*
|
||||
* @param string $group The group to clear.
|
||||
* @return bool success
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
return (bool)xcache_inc($this->_config['prefix'] . $group, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates and reverses $_SERVER authentication values
|
||||
* Makes necessary changes (and reverting them back) in $_SERVER
|
||||
*
|
||||
* This has to be done because xcache_clear_cache() needs to pass Basic Http Auth
|
||||
* (see xcache.admin configuration config)
|
||||
*
|
||||
* @param bool $reverse Revert changes
|
||||
* @return void
|
||||
*/
|
||||
protected function _auth($reverse = false)
|
||||
{
|
||||
static $backup = [];
|
||||
$keys = ['PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password'];
|
||||
foreach ($keys as $key => $value) {
|
||||
if ($reverse) {
|
||||
if (isset($backup[$key])) {
|
||||
$_SERVER[$key] = $backup[$key];
|
||||
unset($backup[$key]);
|
||||
} else {
|
||||
unset($_SERVER[$key]);
|
||||
}
|
||||
} else {
|
||||
$value = env($key);
|
||||
if (!empty($value)) {
|
||||
$backup[$key] = $value;
|
||||
}
|
||||
if (!empty($this->_config[$value])) {
|
||||
$_SERVER[$key] = $this->_config[$value];
|
||||
} elseif (!empty($this->_config[$key])) {
|
||||
$_SERVER[$key] = $this->_config[$key];
|
||||
} else {
|
||||
$_SERVER[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.7.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Cache;
|
||||
|
||||
use Cake\Core\Exception\Exception;
|
||||
use Psr\SimpleCache\InvalidArgumentException as InvalidArgumentInterface;
|
||||
|
||||
/**
|
||||
* Exception raised when cache keys are invalid.
|
||||
*/
|
||||
class InvalidArgumentException extends Exception implements InvalidArgumentInterface
|
||||
{
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# CakePHP Caching Library
|
||||
|
||||
The Cache library provides a `Cache` service locator for interfacing with multiple caching backends using
|
||||
a simple to use interface.
|
||||
|
||||
The caching backends supported are:
|
||||
|
||||
* Files
|
||||
* APC
|
||||
* Memcached
|
||||
* Redis
|
||||
* Wincache
|
||||
* Xcache
|
||||
|
||||
## Usage
|
||||
|
||||
Caching engines need to be configured with the `Cache::config()` method.
|
||||
|
||||
```php
|
||||
use Cake\Cache\Cache;
|
||||
|
||||
// Using a short name
|
||||
Cache::config('default', [
|
||||
'className' => 'File',
|
||||
'duration' => '+1 hours',
|
||||
'path' => sys_get_tmp_dir(),
|
||||
'prefix' => 'my_app_'
|
||||
]);
|
||||
|
||||
// Using a fully namespaced name.
|
||||
Cache::config('long', [
|
||||
'className' => 'Cake\Cache\Engine\ApcuEngine',
|
||||
'duration' => '+1 week',
|
||||
'prefix' => 'my_app_'
|
||||
]);
|
||||
|
||||
// Using a constructed object.
|
||||
$object = new FileEngine($config);
|
||||
Cache::config('other', $object);
|
||||
```
|
||||
|
||||
You can now read a write from the cache:
|
||||
|
||||
```php
|
||||
$data = Cache::remember('my_cache_key', function () {
|
||||
return Service::expensiveCall();
|
||||
});
|
||||
```
|
||||
|
||||
The code above will try to look for data stored in cache under the `my_cache_key`, if not found
|
||||
the callback will be executed and the returned data will be cached for future calls.
|
||||
|
||||
## Documentation
|
||||
|
||||
Please make sure you check the [official documentation](https://book.cakephp.org/3/en/core-libraries/caching.html)
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.7.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
namespace Cake\Cache;
|
||||
|
||||
use Cake\Cache\CacheEngineInterface;
|
||||
use Psr\SimpleCache\CacheInterface;
|
||||
|
||||
/**
|
||||
* Wrapper for Cake engines that allow them to support
|
||||
* the PSR16 Simple Cache Interface
|
||||
*
|
||||
* @since 3.7.0
|
||||
* @link https://www.php-fig.org/psr/psr-16/
|
||||
*/
|
||||
class SimpleCacheEngine implements CacheInterface, CacheEngineInterface
|
||||
{
|
||||
/**
|
||||
* The wrapped cache engine object.
|
||||
*
|
||||
* @var \Cake\Cache\CacheEngine
|
||||
*/
|
||||
protected $innerEngine;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Cake\Cache\CacheEngine $innerEngine The decorated engine.
|
||||
*/
|
||||
public function __construct(CacheEngine $innerEngine)
|
||||
{
|
||||
$this->innerEngine = $innerEngine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the validity of the given cache key.
|
||||
*
|
||||
* @param string $key Key to check.
|
||||
* @return void
|
||||
* @throws \Cake\Cache\InvalidArgumentException When the key is not valid.
|
||||
*/
|
||||
protected function ensureValidKey($key)
|
||||
{
|
||||
if (!is_string($key) || strlen($key) === 0) {
|
||||
throw new InvalidArgumentException('A cache key must be a non-empty string.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the validity of the given cache keys.
|
||||
*
|
||||
* @param mixed $keys The keys to check.
|
||||
* @return void
|
||||
* @throws \Cake\Cache\InvalidArgumentException When the keys are not valid.
|
||||
*/
|
||||
protected function ensureValidKeys($keys)
|
||||
{
|
||||
if (!is_array($keys) && !($keys instanceof \Traversable)) {
|
||||
throw new InvalidArgumentException('A cache key set must be either an array or a Traversable.');
|
||||
}
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$this->ensureValidKey($key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the value for a given key from the cache.
|
||||
*
|
||||
* @param string $key The unique key of this item in the cache.
|
||||
* @param mixed $default Default value to return if the key does not exist.
|
||||
* @return mixed The value of the item from the cache, or $default in case of cache miss.
|
||||
* @throws \Cake\Cache\InvalidArgumentException If the $key string is not a legal value.
|
||||
*/
|
||||
public function get($key, $default = null)
|
||||
{
|
||||
$this->ensureValidKey($key);
|
||||
$result = $this->innerEngine->read($key);
|
||||
if ($result === false) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists data in the cache, uniquely referenced by the given key with an optional expiration TTL time.
|
||||
*
|
||||
* @param string $key The key of the item to store.
|
||||
* @param mixed $value The value of the item to store, must be serializable.
|
||||
* @param \DateInterval|int|null $ttl Optional. The TTL value of this item. If no value is sent and
|
||||
* the driver supports TTL then the library may set a default value
|
||||
* for it or let the driver take care of that.
|
||||
* @return bool True on success and false on failure.
|
||||
* @throws \Cake\Cache\InvalidArgumentException
|
||||
* MUST be thrown if the $key string is not a legal value.
|
||||
*/
|
||||
public function set($key, $value, $ttl = null)
|
||||
{
|
||||
$this->ensureValidKey($key);
|
||||
if ($ttl !== null) {
|
||||
$restore = $this->innerEngine->getConfig('duration');
|
||||
$this->innerEngine->setConfig('duration', $ttl);
|
||||
}
|
||||
try {
|
||||
$result = $this->innerEngine->write($key, $value);
|
||||
|
||||
return (bool)$result;
|
||||
} finally {
|
||||
if (isset($restore)) {
|
||||
$this->innerEngine->setConfig('duration', $restore);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an item from the cache by its unique key.
|
||||
*
|
||||
* @param string $key The unique cache key of the item to delete.
|
||||
* @return bool True if the item was successfully removed. False if there was an error.
|
||||
* @throws \Cake\Cache\InvalidArgumentException If the $key string is not a legal value.
|
||||
*/
|
||||
public function delete($key)
|
||||
{
|
||||
$this->ensureValidKey($key);
|
||||
|
||||
return $this->innerEngine->delete($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wipes clean the entire cache's keys.
|
||||
*
|
||||
* @return bool True on success and false on failure.
|
||||
*/
|
||||
public function clear()
|
||||
{
|
||||
return $this->innerEngine->clear(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains multiple cache items by their unique keys.
|
||||
*
|
||||
* @param iterable $keys A list of keys that can obtained in a single operation.
|
||||
* @param mixed $default Default value to return for keys that do not exist.
|
||||
* @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
|
||||
* @throws \Cake\Cache\InvalidArgumentException If $keys is neither an array nor a Traversable,
|
||||
* or if any of the $keys are not a legal value.
|
||||
*/
|
||||
public function getMultiple($keys, $default = null)
|
||||
{
|
||||
$this->ensureValidKeys($keys);
|
||||
|
||||
$results = $this->innerEngine->readMany($keys);
|
||||
foreach ($results as $key => $value) {
|
||||
if ($value === false) {
|
||||
$results[$key] = $default;
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists a set of key => value pairs in the cache, with an optional TTL.
|
||||
*
|
||||
* @param iterable $values A list of key => value pairs for a multiple-set operation.
|
||||
* @param \DateInterval|int|null $ttl Optional. The TTL value of this item. If no value is sent and
|
||||
* the driver supports TTL then the library may set a default value
|
||||
* for it or let the driver take care of that.
|
||||
* @return bool True on success and false on failure.
|
||||
* @throws \Cake\Cache\InvalidArgumentException If $values is neither an array nor a Traversable,
|
||||
* or if any of the $values are not a legal value.
|
||||
*/
|
||||
public function setMultiple($values, $ttl = null)
|
||||
{
|
||||
$this->ensureValidKeys(array_keys($values));
|
||||
|
||||
if ($ttl !== null) {
|
||||
$restore = $this->innerEngine->getConfig('duration');
|
||||
$this->innerEngine->setConfig('duration', $ttl);
|
||||
}
|
||||
try {
|
||||
$result = $this->innerEngine->writeMany($values);
|
||||
foreach ($result as $key => $success) {
|
||||
if ($success === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} finally {
|
||||
if (isset($restore)) {
|
||||
$this->innerEngine->setConfig('duration', $restore);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple cache items in a single operation.
|
||||
*
|
||||
* @param iterable $keys A list of string-based keys to be deleted.
|
||||
* @return bool True if the items were successfully removed. False if there was an error.
|
||||
* @throws \Cake\Cache\InvalidArgumentException If $keys is neither an array nor a Traversable,
|
||||
* or if any of the $keys are not a legal value.
|
||||
*/
|
||||
public function deleteMultiple($keys)
|
||||
{
|
||||
$this->ensureValidKeys($keys);
|
||||
|
||||
$result = $this->innerEngine->deleteMany($keys);
|
||||
foreach ($result as $key => $success) {
|
||||
if ($success === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether an item is present in the cache.
|
||||
*
|
||||
* NOTE: It is recommended that has() is only to be used for cache warming type purposes
|
||||
* and not to be used within your live applications operations for get/set, as this method
|
||||
* is subject to a race condition where your has() will return true and immediately after,
|
||||
* another script can remove it making the state of your app out of date.
|
||||
*
|
||||
* @param string $key The cache item key.
|
||||
* @return bool
|
||||
* @throws \Cake\Cache\InvalidArgumentException If the $key string is not a legal value.
|
||||
*/
|
||||
public function has($key)
|
||||
{
|
||||
return $this->get($key) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function add($key, $value)
|
||||
{
|
||||
return $this->innerEngine->add($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function increment($key, $offset = 1)
|
||||
{
|
||||
return $this->innerEngine->increment($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function decrement($key, $offset = 1)
|
||||
{
|
||||
return $this->innerEngine->decrement($key, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function clearGroup($group)
|
||||
{
|
||||
return $this->innerEngine->clearGroup($group);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "cakephp/cache",
|
||||
"description": "Easy to use Caching library with support for multiple caching backends",
|
||||
"type": "library",
|
||||
"keywords": [
|
||||
"cakephp",
|
||||
"caching",
|
||||
"cache"
|
||||
],
|
||||
"homepage": "https://cakephp.org",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "CakePHP Community",
|
||||
"homepage": "https://github.com/cakephp/cache/graphs/contributors"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/cakephp/cakephp/issues",
|
||||
"forum": "https://stackoverflow.com/tags/cakephp",
|
||||
"irc": "irc://irc.freenode.org/cakephp",
|
||||
"source": "https://github.com/cakephp/cache"
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.6.0",
|
||||
"psr/simple-cache": "^1.0.0",
|
||||
"cakephp/core": "^3.6.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Cake\\Cache\\": "."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Collection;
|
||||
|
||||
use ArrayIterator;
|
||||
use InvalidArgumentException;
|
||||
use IteratorIterator;
|
||||
use Serializable;
|
||||
use Traversable;
|
||||
|
||||
/**
|
||||
* A collection is an immutable list of elements with a handful of functions to
|
||||
* iterate, group, transform and extract information from it.
|
||||
*/
|
||||
class Collection extends IteratorIterator implements CollectionInterface, Serializable
|
||||
{
|
||||
use CollectionTrait;
|
||||
|
||||
/**
|
||||
* Constructor. You can provide an array or any traversable object
|
||||
*
|
||||
* @param array|\Traversable $items Items.
|
||||
* @throws \InvalidArgumentException If passed incorrect type for items.
|
||||
*/
|
||||
public function __construct($items)
|
||||
{
|
||||
if (is_array($items)) {
|
||||
$items = new ArrayIterator($items);
|
||||
}
|
||||
|
||||
if (!($items instanceof Traversable)) {
|
||||
$msg = 'Only an array or \Traversable is allowed for Collection';
|
||||
throw new InvalidArgumentException($msg);
|
||||
}
|
||||
|
||||
parent::__construct($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string representation of this object that can be used
|
||||
* to reconstruct it
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function serialize()
|
||||
{
|
||||
return serialize($this->buffered());
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserializes the passed string and rebuilds the Collection instance
|
||||
*
|
||||
* @param string $collection The serialized collection
|
||||
* @return void
|
||||
*/
|
||||
public function unserialize($collection)
|
||||
{
|
||||
$this->__construct(unserialize($collection));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
$traversable = $this->optimizeUnwrap();
|
||||
|
||||
if (is_array($traversable)) {
|
||||
return count($traversable);
|
||||
}
|
||||
|
||||
return iterator_count($traversable);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function countKeys()
|
||||
{
|
||||
return count($this->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array that can be used to describe the internal state of this
|
||||
* object.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __debugInfo()
|
||||
{
|
||||
return [
|
||||
'count' => $this->count(),
|
||||
];
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Collection;
|
||||
|
||||
use Traversable;
|
||||
|
||||
/**
|
||||
* Provides utility protected methods for extracting a property or column
|
||||
* from an array or object.
|
||||
*/
|
||||
trait ExtractTrait
|
||||
{
|
||||
/**
|
||||
* Returns a callable that can be used to extract a property or column from
|
||||
* an array or object based on a dot separated path.
|
||||
*
|
||||
* @param string|callable $callback A dot separated path of column to follow
|
||||
* so that the final one can be returned or a callable that will take care
|
||||
* of doing that.
|
||||
* @return callable
|
||||
*/
|
||||
protected function _propertyExtractor($callback)
|
||||
{
|
||||
if (!is_string($callback)) {
|
||||
return $callback;
|
||||
}
|
||||
|
||||
$path = explode('.', $callback);
|
||||
|
||||
if (strpos($callback, '{*}') !== false) {
|
||||
return function ($element) use ($path) {
|
||||
return $this->_extract($element, $path);
|
||||
};
|
||||
}
|
||||
|
||||
return function ($element) use ($path) {
|
||||
return $this->_simpleExtract($element, $path);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a column from $data that can be extracted
|
||||
* by iterating over the column names contained in $path.
|
||||
* It will return arrays for elements in represented with `{*}`
|
||||
*
|
||||
* @param array|\ArrayAccess $data Data.
|
||||
* @param string[] $path Path to extract from.
|
||||
* @return mixed
|
||||
*/
|
||||
protected function _extract($data, $path)
|
||||
{
|
||||
$value = null;
|
||||
$collectionTransform = false;
|
||||
|
||||
foreach ($path as $i => $column) {
|
||||
if ($column === '{*}') {
|
||||
$collectionTransform = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
$collectionTransform &&
|
||||
!($data instanceof Traversable || is_array($data))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($collectionTransform) {
|
||||
$rest = implode('.', array_slice($path, $i));
|
||||
|
||||
return (new Collection($data))->extract($rest);
|
||||
}
|
||||
|
||||
if (!isset($data[$column])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = $data[$column];
|
||||
$data = $value;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a column from $data that can be extracted
|
||||
* by iterating over the column names contained in $path
|
||||
*
|
||||
* @param array|\ArrayAccess $data Data.
|
||||
* @param string[] $path Path to extract from.
|
||||
* @return mixed
|
||||
*/
|
||||
protected function _simpleExtract($data, $path)
|
||||
{
|
||||
$value = null;
|
||||
foreach ($path as $column) {
|
||||
if (!isset($data[$column])) {
|
||||
return null;
|
||||
}
|
||||
$value = $data[$column];
|
||||
$data = $value;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a callable that receives a value and will return whether or not
|
||||
* it matches certain condition.
|
||||
*
|
||||
* @param array $conditions A key-value list of conditions to match where the
|
||||
* key is the property path to get from the current item and the value is the
|
||||
* value to be compared the item with.
|
||||
* @return \Closure
|
||||
*/
|
||||
protected function _createMatcherFilter(array $conditions)
|
||||
{
|
||||
$matchers = [];
|
||||
foreach ($conditions as $property => $value) {
|
||||
$extractor = $this->_propertyExtractor($property);
|
||||
$matchers[] = function ($v) use ($extractor, $value) {
|
||||
return $extractor($v) == $value;
|
||||
};
|
||||
}
|
||||
|
||||
return function ($value) use ($matchers) {
|
||||
foreach ($matchers as $match) {
|
||||
if (!$match($value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Collection\Iterator;
|
||||
|
||||
use Cake\Collection\Collection;
|
||||
use Countable;
|
||||
use Serializable;
|
||||
use SplDoublyLinkedList;
|
||||
|
||||
/**
|
||||
* Creates an iterator from another iterator that will keep the results of the inner
|
||||
* iterator in memory, so that results don't have to be re-calculated.
|
||||
*/
|
||||
class BufferedIterator extends Collection implements Countable, Serializable
|
||||
{
|
||||
/**
|
||||
* The in-memory cache containing results from previous iterators
|
||||
*
|
||||
* @var \SplDoublyLinkedList
|
||||
*/
|
||||
protected $_buffer;
|
||||
|
||||
/**
|
||||
* Points to the next record number that should be fetched
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $_index = 0;
|
||||
|
||||
/**
|
||||
* Last record fetched from the inner iterator
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $_current;
|
||||
|
||||
/**
|
||||
* Last key obtained from the inner iterator
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $_key;
|
||||
|
||||
/**
|
||||
* Whether or not the internal iterator's rewind method was already
|
||||
* called
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_started = false;
|
||||
|
||||
/**
|
||||
* Whether or not the internal iterator has reached its end.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_finished = false;
|
||||
|
||||
/**
|
||||
* Maintains an in-memory cache of the results yielded by the internal
|
||||
* iterator.
|
||||
*
|
||||
* @param array|\Traversable $items The items to be filtered.
|
||||
*/
|
||||
public function __construct($items)
|
||||
{
|
||||
$this->_buffer = new SplDoublyLinkedList();
|
||||
parent::__construct($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current key in the iterator
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function key()
|
||||
{
|
||||
return $this->_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current record in the iterator
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function current()
|
||||
{
|
||||
return $this->_current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewinds the collection
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function rewind()
|
||||
{
|
||||
if ($this->_index === 0 && !$this->_started) {
|
||||
$this->_started = true;
|
||||
parent::rewind();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->_index = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not the iterator has more elements
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function valid()
|
||||
{
|
||||
if ($this->_buffer->offsetExists($this->_index)) {
|
||||
$current = $this->_buffer->offsetGet($this->_index);
|
||||
$this->_current = $current['value'];
|
||||
$this->_key = $current['key'];
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$valid = parent::valid();
|
||||
|
||||
if ($valid) {
|
||||
$this->_current = parent::current();
|
||||
$this->_key = parent::key();
|
||||
$this->_buffer->push([
|
||||
'key' => $this->_key,
|
||||
'value' => $this->_current,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->_finished = !$valid;
|
||||
|
||||
return $valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances the iterator pointer to the next element
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function next()
|
||||
{
|
||||
$this->_index++;
|
||||
|
||||
if (!$this->_finished) {
|
||||
parent::next();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number or items in this collection
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
if (!$this->_started) {
|
||||
$this->rewind();
|
||||
}
|
||||
|
||||
while ($this->valid()) {
|
||||
$this->next();
|
||||
}
|
||||
|
||||
return $this->_buffer->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string representation of this object that can be used
|
||||
* to reconstruct it
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function serialize()
|
||||
{
|
||||
if (!$this->_finished) {
|
||||
$this->count();
|
||||
}
|
||||
|
||||
return serialize($this->_buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserializes the passed string and rebuilds the BufferedIterator instance
|
||||
*
|
||||
* @param string $buffer The serialized buffer iterator
|
||||
* @return void
|
||||
*/
|
||||
public function unserialize($buffer)
|
||||
{
|
||||
$this->__construct([]);
|
||||
$this->_buffer = unserialize($buffer);
|
||||
$this->_started = true;
|
||||
$this->_finished = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace Cake\Collection\Iterator;
|
||||
|
||||
use ArrayIterator;
|
||||
use Cake\Collection\Collection;
|
||||
use Cake\Collection\CollectionInterface;
|
||||
|
||||
/**
|
||||
* Creates an iterator from another iterator that extract the requested column
|
||||
* or property based on a path
|
||||
*/
|
||||
class ExtractIterator extends Collection
|
||||
{
|
||||
/**
|
||||
* A callable responsible for extracting a single value for each
|
||||
* item in the collection.
|
||||
*
|
||||
* @var callable
|
||||
*/
|
||||
protected $_extractor;
|
||||
|
||||
/**
|
||||
* Creates the iterator that will return the requested property for each value
|
||||
* in the collection expressed in $path
|
||||
*
|
||||
* ### Example:
|
||||
*
|
||||
* Extract the user name for all comments in the array:
|
||||
*
|
||||
* ```
|
||||
* $items = [
|
||||
* ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
|
||||
* ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
|
||||
* ];
|
||||
* $extractor = new ExtractIterator($items, 'comment.user.name'');
|
||||
* ```
|
||||
*
|
||||
* @param array|\Traversable $items The list of values to iterate
|
||||
* @param string $path a dot separated string symbolizing the path to follow
|
||||
* inside the hierarchy of each value so that the column can be extracted.
|
||||
*/
|
||||
public function __construct($items, $path)
|
||||
{
|
||||
$this->_extractor = $this->_propertyExtractor($path);
|
||||
parent::__construct($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the column value defined in $path or null if the path could not be
|
||||
* followed
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function current()
|
||||
{
|
||||
$extractor = $this->_extractor;
|
||||
|
||||
return $extractor(parent::current());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* We perform here some strictness analysis so that the
|
||||
* iterator logic is bypassed entirely.
|
||||
*
|
||||
* @return \Iterator
|
||||
*/
|
||||
public function unwrap()
|
||||
{
|
||||
$iterator = $this->getInnerIterator();
|
||||
|
||||
if ($iterator instanceof CollectionInterface) {
|
||||
$iterator = $iterator->unwrap();
|
||||
}
|
||||
|
||||
if (get_class($iterator) !== ArrayIterator::class) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
// ArrayIterator can be traversed strictly.
|
||||
// Let's do that for performance gains
|
||||
|
||||
$callback = $this->_extractor;
|
||||
$res = [];
|
||||
|
||||
/** @var \ArrayObject $iterator */
|
||||
foreach ($iterator->getArrayCopy() as $k => $v) {
|
||||
$res[$k] = $callback($v);
|
||||
}
|
||||
|
||||
return new ArrayIterator($res);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 2747 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user